PackageManagerService.java revision 4c8de7a60f2d38ce727cbe8890904cd7c4c2cb71
18a44513648da0c5f5551f96b329cf56b66f5b303pkanwar/*
28a44513648da0c5f5551f96b329cf56b66f5b303pkanwar * Copyright (C) 2006 The Android Open Source Project
38a44513648da0c5f5551f96b329cf56b66f5b303pkanwar *
48a44513648da0c5f5551f96b329cf56b66f5b303pkanwar * Licensed under the Apache License, Version 2.0 (the "License");
58a44513648da0c5f5551f96b329cf56b66f5b303pkanwar * you may not use this file except in compliance with the License.
68a44513648da0c5f5551f96b329cf56b66f5b303pkanwar * You may obtain a copy of the License at
78a44513648da0c5f5551f96b329cf56b66f5b303pkanwar *
88a44513648da0c5f5551f96b329cf56b66f5b303pkanwar *      http://www.apache.org/licenses/LICENSE-2.0
98a44513648da0c5f5551f96b329cf56b66f5b303pkanwar *
108a44513648da0c5f5551f96b329cf56b66f5b303pkanwar * Unless required by applicable law or agreed to in writing, software
118a44513648da0c5f5551f96b329cf56b66f5b303pkanwar * distributed under the License is distributed on an "AS IS" BASIS,
128a44513648da0c5f5551f96b329cf56b66f5b303pkanwar * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
138a44513648da0c5f5551f96b329cf56b66f5b303pkanwar * See the License for the specific language governing permissions and
148a44513648da0c5f5551f96b329cf56b66f5b303pkanwar * limitations under the License.
158a44513648da0c5f5551f96b329cf56b66f5b303pkanwar */
168a44513648da0c5f5551f96b329cf56b66f5b303pkanwar
178a44513648da0c5f5551f96b329cf56b66f5b303pkanwarpackage com.android.server.pm;
188a44513648da0c5f5551f96b329cf56b66f5b303pkanwar
198a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.Manifest.permission.DELETE_PACKAGES;
208a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.Manifest.permission.INSTALL_PACKAGES;
218a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
228a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
238a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.Manifest.permission.READ_EXTERNAL_STORAGE;
248a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
258a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
268a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
278a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
288a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.CERT_INPUT_SHA256;
298a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
308a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
318a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
328a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
338a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
348a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.DELETE_KEEP_DATA;
358a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
368a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
378a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
388a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
398a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
408a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
418a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
428a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_EXTERNAL;
438a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
448a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
458a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
468a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
478a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
488a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
498a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
508a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
518a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
528a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
538a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
548a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
558a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
568a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
578a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
588a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
598a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_INTERNAL;
608a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
618a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
628a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
638a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
648a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
658a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
668a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MATCH_ALL;
678a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MATCH_ANY_USER;
688a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
698a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
708a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
718a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
728a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
738a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
748a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
758a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
768a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
778a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
788a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
798a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
808a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
818a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
828a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
838a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.PERMISSION_DENIED;
848a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageManager.PERMISSION_GRANTED;
858a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.content.pm.PackageParser.isApkFile;
868a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
878a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.os.storage.StorageManager.FLAG_STORAGE_CE;
888a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.os.storage.StorageManager.FLAG_STORAGE_DE;
898a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.system.OsConstants.O_CREAT;
908a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static android.system.OsConstants.O_RDWR;
918a44513648da0c5f5551f96b329cf56b66f5b303pkanwar
928a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
938a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
948a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
958a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
968a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.internal.util.ArrayUtils.appendInt;
978a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
988a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
998a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
1008a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
1018a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
1028a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
1038a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
1048a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
1058a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
1068a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
1078a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
1088a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
1098a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
1108a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
1118a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
1128a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
1138a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
1148a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
1158a44513648da0c5f5551f96b329cf56b66f5b303pkanwar
1168a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.Manifest;
1178a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.annotation.IntDef;
1188a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.annotation.NonNull;
1198a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.annotation.Nullable;
1208a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.annotation.UserIdInt;
1218a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.app.ActivityManager;
1228a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.app.ActivityManagerInternal;
1238a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.app.AppOpsManager;
1248a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.app.IActivityManager;
1258a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.app.ResourcesManager;
1268a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.app.admin.IDevicePolicyManager;
1278a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.app.admin.SecurityLog;
1288a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.app.backup.IBackupManager;
1298a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.BroadcastReceiver;
1308a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.ComponentName;
1318a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.ContentResolver;
1328a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.Context;
1338a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.IIntentReceiver;
1348a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.Intent;
1358a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.IntentFilter;
1368a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.IntentSender;
1378a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.IntentSender.SendIntentException;
1388a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.ServiceConnection;
1398a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.pm.ActivityInfo;
1408a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.pm.ApplicationInfo;
1418a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.pm.AppsQueryHelper;
1428a44513648da0c5f5551f96b329cf56b66f5b303pkanwarimport android.content.pm.AuxiliaryResolveInfo;
143import android.content.pm.ChangedPackages;
144import android.content.pm.ComponentInfo;
145import android.content.pm.FallbackCategoryProvider;
146import android.content.pm.FeatureInfo;
147import android.content.pm.IDexModuleRegisterCallback;
148import android.content.pm.IOnPermissionsChangeListener;
149import android.content.pm.IPackageDataObserver;
150import android.content.pm.IPackageDeleteObserver;
151import android.content.pm.IPackageDeleteObserver2;
152import android.content.pm.IPackageInstallObserver2;
153import android.content.pm.IPackageInstaller;
154import android.content.pm.IPackageManager;
155import android.content.pm.IPackageManagerNative;
156import android.content.pm.IPackageMoveObserver;
157import android.content.pm.IPackageStatsObserver;
158import android.content.pm.InstantAppInfo;
159import android.content.pm.InstantAppRequest;
160import android.content.pm.InstantAppResolveInfo;
161import android.content.pm.InstrumentationInfo;
162import android.content.pm.IntentFilterVerificationInfo;
163import android.content.pm.KeySet;
164import android.content.pm.PackageCleanItem;
165import android.content.pm.PackageInfo;
166import android.content.pm.PackageInfoLite;
167import android.content.pm.PackageInstaller;
168import android.content.pm.PackageList;
169import android.content.pm.PackageManager;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal;
172import android.content.pm.PackageManagerInternal.PackageListObserver;
173import android.content.pm.PackageParser;
174import android.content.pm.PackageParser.ActivityIntentInfo;
175import android.content.pm.PackageParser.Package;
176import android.content.pm.PackageParser.PackageLite;
177import android.content.pm.PackageParser.PackageParserException;
178import android.content.pm.PackageParser.ParseFlags;
179import android.content.pm.PackageParser.ServiceIntentInfo;
180import android.content.pm.PackageParser.SigningDetails;
181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
182import android.content.pm.PackageStats;
183import android.content.pm.PackageUserState;
184import android.content.pm.ParceledListSlice;
185import android.content.pm.PermissionGroupInfo;
186import android.content.pm.PermissionInfo;
187import android.content.pm.ProviderInfo;
188import android.content.pm.ResolveInfo;
189import android.content.pm.SELinuxUtil;
190import android.content.pm.ServiceInfo;
191import android.content.pm.SharedLibraryInfo;
192import android.content.pm.Signature;
193import android.content.pm.UserInfo;
194import android.content.pm.VerifierDeviceIdentity;
195import android.content.pm.VerifierInfo;
196import android.content.pm.VersionedPackage;
197import android.content.pm.dex.ArtManager;
198import android.content.pm.dex.DexMetadataHelper;
199import android.content.pm.dex.IArtManager;
200import android.content.res.Resources;
201import android.database.ContentObserver;
202import android.graphics.Bitmap;
203import android.hardware.display.DisplayManager;
204import android.net.Uri;
205import android.os.AsyncTask;
206import android.os.Binder;
207import android.os.Build;
208import android.os.Bundle;
209import android.os.Debug;
210import android.os.Environment;
211import android.os.Environment.UserEnvironment;
212import android.os.FileUtils;
213import android.os.Handler;
214import android.os.IBinder;
215import android.os.Looper;
216import android.os.Message;
217import android.os.Parcel;
218import android.os.ParcelFileDescriptor;
219import android.os.PatternMatcher;
220import android.os.PersistableBundle;
221import android.os.Process;
222import android.os.RemoteCallbackList;
223import android.os.RemoteException;
224import android.os.ResultReceiver;
225import android.os.SELinux;
226import android.os.ServiceManager;
227import android.os.ShellCallback;
228import android.os.SystemClock;
229import android.os.SystemProperties;
230import android.os.Trace;
231import android.os.UserHandle;
232import android.os.UserManager;
233import android.os.UserManagerInternal;
234import android.os.storage.IStorageManager;
235import android.os.storage.StorageEventListener;
236import android.os.storage.StorageManager;
237import android.os.storage.StorageManagerInternal;
238import android.os.storage.VolumeInfo;
239import android.os.storage.VolumeRecord;
240import android.provider.Settings.Global;
241import android.provider.Settings.Secure;
242import android.security.KeyStore;
243import android.security.SystemKeyStore;
244import android.service.pm.PackageServiceDumpProto;
245import android.system.ErrnoException;
246import android.system.Os;
247import android.text.TextUtils;
248import android.text.format.DateUtils;
249import android.util.ArrayMap;
250import android.util.ArraySet;
251import android.util.Base64;
252import android.util.ByteStringUtils;
253import android.util.DisplayMetrics;
254import android.util.EventLog;
255import android.util.ExceptionUtils;
256import android.util.Log;
257import android.util.LogPrinter;
258import android.util.LongSparseArray;
259import android.util.LongSparseLongArray;
260import android.util.MathUtils;
261import android.util.PackageUtils;
262import android.util.Pair;
263import android.util.PrintStreamPrinter;
264import android.util.Slog;
265import android.util.SparseArray;
266import android.util.SparseBooleanArray;
267import android.util.SparseIntArray;
268import android.util.TimingsTraceLog;
269import android.util.Xml;
270import android.util.jar.StrictJarFile;
271import android.util.proto.ProtoOutputStream;
272import android.view.Display;
273
274import com.android.internal.R;
275import com.android.internal.annotations.GuardedBy;
276import com.android.internal.app.IMediaContainerService;
277import com.android.internal.app.ResolverActivity;
278import com.android.internal.content.NativeLibraryHelper;
279import com.android.internal.content.PackageHelper;
280import com.android.internal.logging.MetricsLogger;
281import com.android.internal.os.IParcelFileDescriptorFactory;
282import com.android.internal.os.SomeArgs;
283import com.android.internal.os.Zygote;
284import com.android.internal.telephony.CarrierAppUtils;
285import com.android.internal.util.ArrayUtils;
286import com.android.internal.util.ConcurrentUtils;
287import com.android.internal.util.DumpUtils;
288import com.android.internal.util.FastXmlSerializer;
289import com.android.internal.util.IndentingPrintWriter;
290import com.android.internal.util.Preconditions;
291import com.android.internal.util.XmlUtils;
292import com.android.server.AttributeCache;
293import com.android.server.DeviceIdleController;
294import com.android.server.EventLogTags;
295import com.android.server.FgThread;
296import com.android.server.IntentResolver;
297import com.android.server.LocalServices;
298import com.android.server.LockGuard;
299import com.android.server.ServiceThread;
300import com.android.server.SystemConfig;
301import com.android.server.SystemServerInitThreadPool;
302import com.android.server.Watchdog;
303import com.android.server.net.NetworkPolicyManagerInternal;
304import com.android.server.pm.Installer.InstallerException;
305import com.android.server.pm.Settings.DatabaseVersion;
306import com.android.server.pm.Settings.VersionInfo;
307import com.android.server.pm.dex.ArtManagerService;
308import com.android.server.pm.dex.DexLogger;
309import com.android.server.pm.dex.DexManager;
310import com.android.server.pm.dex.DexoptOptions;
311import com.android.server.pm.dex.PackageDexUsage;
312import com.android.server.pm.permission.BasePermission;
313import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
314import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
315import com.android.server.pm.permission.PermissionManagerInternal;
316import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
317import com.android.server.pm.permission.PermissionManagerService;
318import com.android.server.pm.permission.PermissionsState;
319import com.android.server.pm.permission.PermissionsState.PermissionState;
320import com.android.server.security.VerityUtils;
321import com.android.server.storage.DeviceStorageMonitorInternal;
322
323import dalvik.system.CloseGuard;
324import dalvik.system.VMRuntime;
325
326import libcore.io.IoUtils;
327
328import org.xmlpull.v1.XmlPullParser;
329import org.xmlpull.v1.XmlPullParserException;
330import org.xmlpull.v1.XmlSerializer;
331
332import java.io.BufferedOutputStream;
333import java.io.ByteArrayInputStream;
334import java.io.ByteArrayOutputStream;
335import java.io.File;
336import java.io.FileDescriptor;
337import java.io.FileInputStream;
338import java.io.FileOutputStream;
339import java.io.FilenameFilter;
340import java.io.IOException;
341import java.io.PrintWriter;
342import java.lang.annotation.Retention;
343import java.lang.annotation.RetentionPolicy;
344import java.nio.charset.StandardCharsets;
345import java.security.DigestException;
346import java.security.DigestInputStream;
347import java.security.MessageDigest;
348import java.security.NoSuchAlgorithmException;
349import java.security.PublicKey;
350import java.security.SecureRandom;
351import java.security.cert.CertificateException;
352import java.util.ArrayList;
353import java.util.Arrays;
354import java.util.Collection;
355import java.util.Collections;
356import java.util.Comparator;
357import java.util.HashMap;
358import java.util.HashSet;
359import java.util.Iterator;
360import java.util.LinkedHashSet;
361import java.util.List;
362import java.util.Map;
363import java.util.Objects;
364import java.util.Set;
365import java.util.concurrent.CountDownLatch;
366import java.util.concurrent.Future;
367import java.util.concurrent.TimeUnit;
368import java.util.concurrent.atomic.AtomicBoolean;
369import java.util.concurrent.atomic.AtomicInteger;
370
371/**
372 * Keep track of all those APKs everywhere.
373 * <p>
374 * Internally there are two important locks:
375 * <ul>
376 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
377 * and other related state. It is a fine-grained lock that should only be held
378 * momentarily, as it's one of the most contended locks in the system.
379 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
380 * operations typically involve heavy lifting of application data on disk. Since
381 * {@code installd} is single-threaded, and it's operations can often be slow,
382 * this lock should never be acquired while already holding {@link #mPackages}.
383 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
384 * holding {@link #mInstallLock}.
385 * </ul>
386 * Many internal methods rely on the caller to hold the appropriate locks, and
387 * this contract is expressed through method name suffixes:
388 * <ul>
389 * <li>fooLI(): the caller must hold {@link #mInstallLock}
390 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
391 * being modified must be frozen
392 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
393 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
394 * </ul>
395 * <p>
396 * Because this class is very central to the platform's security; please run all
397 * CTS and unit tests whenever making modifications:
398 *
399 * <pre>
400 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
401 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
402 * </pre>
403 */
404public class PackageManagerService extends IPackageManager.Stub
405        implements PackageSender {
406    static final String TAG = "PackageManager";
407    public static final boolean DEBUG_SETTINGS = false;
408    static final boolean DEBUG_PREFERRED = false;
409    static final boolean DEBUG_UPGRADE = false;
410    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
411    private static final boolean DEBUG_BACKUP = false;
412    public static final boolean DEBUG_INSTALL = false;
413    public static final boolean DEBUG_REMOVE = false;
414    private static final boolean DEBUG_BROADCASTS = false;
415    private static final boolean DEBUG_SHOW_INFO = false;
416    private static final boolean DEBUG_PACKAGE_INFO = false;
417    private static final boolean DEBUG_INTENT_MATCHING = false;
418    public static final boolean DEBUG_PACKAGE_SCANNING = false;
419    private static final boolean DEBUG_VERIFY = false;
420    private static final boolean DEBUG_FILTERS = false;
421    public static final boolean DEBUG_PERMISSIONS = false;
422    private static final boolean DEBUG_SHARED_LIBRARIES = false;
423    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
424
425    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
426    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
427    // user, but by default initialize to this.
428    public static final boolean DEBUG_DEXOPT = false;
429
430    private static final boolean DEBUG_ABI_SELECTION = false;
431    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
432    private static final boolean DEBUG_TRIAGED_MISSING = false;
433    private static final boolean DEBUG_APP_DATA = false;
434
435    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
436    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
437
438    private static final boolean HIDE_EPHEMERAL_APIS = false;
439
440    private static final boolean ENABLE_FREE_CACHE_V2 =
441            SystemProperties.getBoolean("fw.free_cache_v2", true);
442
443    private static final int RADIO_UID = Process.PHONE_UID;
444    private static final int LOG_UID = Process.LOG_UID;
445    private static final int NFC_UID = Process.NFC_UID;
446    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
447    private static final int SHELL_UID = Process.SHELL_UID;
448    private static final int SE_UID = Process.SE_UID;
449
450    // Suffix used during package installation when copying/moving
451    // package apks to install directory.
452    private static final String INSTALL_PACKAGE_SUFFIX = "-";
453
454    static final int SCAN_NO_DEX = 1<<0;
455    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
456    static final int SCAN_NEW_INSTALL = 1<<2;
457    static final int SCAN_UPDATE_TIME = 1<<3;
458    static final int SCAN_BOOTING = 1<<4;
459    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
460    static final int SCAN_REQUIRE_KNOWN = 1<<7;
461    static final int SCAN_MOVE = 1<<8;
462    static final int SCAN_INITIAL = 1<<9;
463    static final int SCAN_CHECK_ONLY = 1<<10;
464    static final int SCAN_DONT_KILL_APP = 1<<11;
465    static final int SCAN_IGNORE_FROZEN = 1<<12;
466    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
467    static final int SCAN_AS_INSTANT_APP = 1<<14;
468    static final int SCAN_AS_FULL_APP = 1<<15;
469    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
470    static final int SCAN_AS_SYSTEM = 1<<17;
471    static final int SCAN_AS_PRIVILEGED = 1<<18;
472    static final int SCAN_AS_OEM = 1<<19;
473    static final int SCAN_AS_VENDOR = 1<<20;
474    static final int SCAN_AS_PRODUCT = 1<<21;
475
476    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
477            SCAN_NO_DEX,
478            SCAN_UPDATE_SIGNATURE,
479            SCAN_NEW_INSTALL,
480            SCAN_UPDATE_TIME,
481            SCAN_BOOTING,
482            SCAN_DELETE_DATA_ON_FAILURES,
483            SCAN_REQUIRE_KNOWN,
484            SCAN_MOVE,
485            SCAN_INITIAL,
486            SCAN_CHECK_ONLY,
487            SCAN_DONT_KILL_APP,
488            SCAN_IGNORE_FROZEN,
489            SCAN_FIRST_BOOT_OR_UPGRADE,
490            SCAN_AS_INSTANT_APP,
491            SCAN_AS_FULL_APP,
492            SCAN_AS_VIRTUAL_PRELOAD,
493    })
494    @Retention(RetentionPolicy.SOURCE)
495    public @interface ScanFlags {}
496
497    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
498    /** Extension of the compressed packages */
499    public final static String COMPRESSED_EXTENSION = ".gz";
500    /** Suffix of stub packages on the system partition */
501    public final static String STUB_SUFFIX = "-Stub";
502
503    private static final int[] EMPTY_INT_ARRAY = new int[0];
504
505    private static final int TYPE_UNKNOWN = 0;
506    private static final int TYPE_ACTIVITY = 1;
507    private static final int TYPE_RECEIVER = 2;
508    private static final int TYPE_SERVICE = 3;
509    private static final int TYPE_PROVIDER = 4;
510    @IntDef(prefix = { "TYPE_" }, value = {
511            TYPE_UNKNOWN,
512            TYPE_ACTIVITY,
513            TYPE_RECEIVER,
514            TYPE_SERVICE,
515            TYPE_PROVIDER,
516    })
517    @Retention(RetentionPolicy.SOURCE)
518    public @interface ComponentType {}
519
520    /**
521     * Timeout (in milliseconds) after which the watchdog should declare that
522     * our handler thread is wedged.  The usual default for such things is one
523     * minute but we sometimes do very lengthy I/O operations on this thread,
524     * such as installing multi-gigabyte applications, so ours needs to be longer.
525     */
526    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
527
528    /**
529     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
530     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
531     * settings entry if available, otherwise we use the hardcoded default.  If it's been
532     * more than this long since the last fstrim, we force one during the boot sequence.
533     *
534     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
535     * one gets run at the next available charging+idle time.  This final mandatory
536     * no-fstrim check kicks in only of the other scheduling criteria is never met.
537     */
538    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
539
540    /**
541     * Whether verification is enabled by default.
542     */
543    private static final boolean DEFAULT_VERIFY_ENABLE = true;
544
545    /**
546     * The default maximum time to wait for the verification agent to return in
547     * milliseconds.
548     */
549    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
550
551    /**
552     * The default response for package verification timeout.
553     *
554     * This can be either PackageManager.VERIFICATION_ALLOW or
555     * PackageManager.VERIFICATION_REJECT.
556     */
557    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
558
559    public static final String PLATFORM_PACKAGE_NAME = "android";
560
561    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
562
563    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
564            DEFAULT_CONTAINER_PACKAGE,
565            "com.android.defcontainer.DefaultContainerService");
566
567    private static final String KILL_APP_REASON_GIDS_CHANGED =
568            "permission grant or revoke changed gids";
569
570    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
571            "permissions revoked";
572
573    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
574
575    private static final String PACKAGE_SCHEME = "package";
576
577    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
578
579    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
580
581    /** Canonical intent used to identify what counts as a "web browser" app */
582    private static final Intent sBrowserIntent;
583    static {
584        sBrowserIntent = new Intent();
585        sBrowserIntent.setAction(Intent.ACTION_VIEW);
586        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
587        sBrowserIntent.setData(Uri.parse("http:"));
588        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
589    }
590
591    /**
592     * The set of all protected actions [i.e. those actions for which a high priority
593     * intent filter is disallowed].
594     */
595    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
596    static {
597        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
598        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
599        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
600        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
601    }
602
603    // Compilation reasons.
604    public static final int REASON_UNKNOWN = -1;
605    public static final int REASON_FIRST_BOOT = 0;
606    public static final int REASON_BOOT = 1;
607    public static final int REASON_INSTALL = 2;
608    public static final int REASON_BACKGROUND_DEXOPT = 3;
609    public static final int REASON_AB_OTA = 4;
610    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
611    public static final int REASON_SHARED = 6;
612
613    public static final int REASON_LAST = REASON_SHARED;
614
615    /**
616     * Version number for the package parser cache. Increment this whenever the format or
617     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
618     */
619    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
620
621    /**
622     * Whether the package parser cache is enabled.
623     */
624    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
625
626    /**
627     * Permissions required in order to receive instant application lifecycle broadcasts.
628     */
629    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
630            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
631
632    final ServiceThread mHandlerThread;
633
634    final PackageHandler mHandler;
635
636    private final ProcessLoggingHandler mProcessLoggingHandler;
637
638    /**
639     * Messages for {@link #mHandler} that need to wait for system ready before
640     * being dispatched.
641     */
642    private ArrayList<Message> mPostSystemReadyMessages;
643
644    final int mSdkVersion = Build.VERSION.SDK_INT;
645
646    final Context mContext;
647    final boolean mFactoryTest;
648    final boolean mOnlyCore;
649    final DisplayMetrics mMetrics;
650    final int mDefParseFlags;
651    final String[] mSeparateProcesses;
652    final boolean mIsUpgrade;
653    final boolean mIsPreNUpgrade;
654    final boolean mIsPreNMR1Upgrade;
655
656    // Have we told the Activity Manager to whitelist the default container service by uid yet?
657    @GuardedBy("mPackages")
658    boolean mDefaultContainerWhitelisted = false;
659
660    @GuardedBy("mPackages")
661    private boolean mDexOptDialogShown;
662
663    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
664    // LOCK HELD.  Can be called with mInstallLock held.
665    @GuardedBy("mInstallLock")
666    final Installer mInstaller;
667
668    /** Directory where installed applications are stored */
669    private static final File sAppInstallDir =
670            new File(Environment.getDataDirectory(), "app");
671    /** Directory where installed application's 32-bit native libraries are copied. */
672    private static final File sAppLib32InstallDir =
673            new File(Environment.getDataDirectory(), "app-lib");
674    /** Directory where code and non-resource assets of forward-locked applications are stored */
675    private static final File sDrmAppPrivateInstallDir =
676            new File(Environment.getDataDirectory(), "app-private");
677
678    // ----------------------------------------------------------------
679
680    // Lock for state used when installing and doing other long running
681    // operations.  Methods that must be called with this lock held have
682    // the suffix "LI".
683    final Object mInstallLock = new Object();
684
685    // ----------------------------------------------------------------
686
687    // Keys are String (package name), values are Package.  This also serves
688    // as the lock for the global state.  Methods that must be called with
689    // this lock held have the prefix "LP".
690    @GuardedBy("mPackages")
691    final ArrayMap<String, PackageParser.Package> mPackages =
692            new ArrayMap<String, PackageParser.Package>();
693
694    final ArrayMap<String, Set<String>> mKnownCodebase =
695            new ArrayMap<String, Set<String>>();
696
697    // Keys are isolated uids and values are the uid of the application
698    // that created the isolated proccess.
699    @GuardedBy("mPackages")
700    final SparseIntArray mIsolatedOwners = new SparseIntArray();
701
702    /**
703     * Tracks new system packages [received in an OTA] that we expect to
704     * find updated user-installed versions. Keys are package name, values
705     * are package location.
706     */
707    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
708    /**
709     * Tracks high priority intent filters for protected actions. During boot, certain
710     * filter actions are protected and should never be allowed to have a high priority
711     * intent filter for them. However, there is one, and only one exception -- the
712     * setup wizard. It must be able to define a high priority intent filter for these
713     * actions to ensure there are no escapes from the wizard. We need to delay processing
714     * of these during boot as we need to look at all of the system packages in order
715     * to know which component is the setup wizard.
716     */
717    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
718    /**
719     * Whether or not processing protected filters should be deferred.
720     */
721    private boolean mDeferProtectedFilters = true;
722
723    /**
724     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
725     */
726    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
727    /**
728     * Whether or not system app permissions should be promoted from install to runtime.
729     */
730    boolean mPromoteSystemApps;
731
732    @GuardedBy("mPackages")
733    final Settings mSettings;
734
735    /**
736     * Set of package names that are currently "frozen", which means active
737     * surgery is being done on the code/data for that package. The platform
738     * will refuse to launch frozen packages to avoid race conditions.
739     *
740     * @see PackageFreezer
741     */
742    @GuardedBy("mPackages")
743    final ArraySet<String> mFrozenPackages = new ArraySet<>();
744
745    final ProtectedPackages mProtectedPackages;
746
747    @GuardedBy("mLoadedVolumes")
748    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
749
750    boolean mFirstBoot;
751
752    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
753
754    @GuardedBy("mAvailableFeatures")
755    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
756
757    private final InstantAppRegistry mInstantAppRegistry;
758
759    @GuardedBy("mPackages")
760    int mChangedPackagesSequenceNumber;
761    /**
762     * List of changed [installed, removed or updated] packages.
763     * mapping from user id -> sequence number -> package name
764     */
765    @GuardedBy("mPackages")
766    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
767    /**
768     * The sequence number of the last change to a package.
769     * mapping from user id -> package name -> sequence number
770     */
771    @GuardedBy("mPackages")
772    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
773
774    @GuardedBy("mPackages")
775    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
776
777    class PackageParserCallback implements PackageParser.Callback {
778        @Override public final boolean hasFeature(String feature) {
779            return PackageManagerService.this.hasSystemFeature(feature, 0);
780        }
781
782        final List<PackageParser.Package> getStaticOverlayPackages(
783                Collection<PackageParser.Package> allPackages, String targetPackageName) {
784            if ("android".equals(targetPackageName)) {
785                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
786                // native AssetManager.
787                return null;
788            }
789
790            List<PackageParser.Package> overlayPackages = null;
791            for (PackageParser.Package p : allPackages) {
792                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
793                    if (overlayPackages == null) {
794                        overlayPackages = new ArrayList<PackageParser.Package>();
795                    }
796                    overlayPackages.add(p);
797                }
798            }
799            if (overlayPackages != null) {
800                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
801                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
802                        return p1.mOverlayPriority - p2.mOverlayPriority;
803                    }
804                };
805                Collections.sort(overlayPackages, cmp);
806            }
807            return overlayPackages;
808        }
809
810        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
811                String targetPath) {
812            if (overlayPackages == null || overlayPackages.isEmpty()) {
813                return null;
814            }
815            List<String> overlayPathList = null;
816            for (PackageParser.Package overlayPackage : overlayPackages) {
817                if (targetPath == null) {
818                    if (overlayPathList == null) {
819                        overlayPathList = new ArrayList<String>();
820                    }
821                    overlayPathList.add(overlayPackage.baseCodePath);
822                    continue;
823                }
824
825                try {
826                    // Creates idmaps for system to parse correctly the Android manifest of the
827                    // target package.
828                    //
829                    // OverlayManagerService will update each of them with a correct gid from its
830                    // target package app id.
831                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
832                            UserHandle.getSharedAppGid(
833                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
834                    if (overlayPathList == null) {
835                        overlayPathList = new ArrayList<String>();
836                    }
837                    overlayPathList.add(overlayPackage.baseCodePath);
838                } catch (InstallerException e) {
839                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
840                            overlayPackage.baseCodePath);
841                }
842            }
843            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
844        }
845
846        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
847            List<PackageParser.Package> overlayPackages;
848            synchronized (mInstallLock) {
849                synchronized (mPackages) {
850                    overlayPackages = getStaticOverlayPackages(
851                            mPackages.values(), targetPackageName);
852                }
853                // It is safe to keep overlayPackages without holding mPackages because static overlay
854                // packages can't be uninstalled or disabled.
855                return getStaticOverlayPaths(overlayPackages, targetPath);
856            }
857        }
858
859        @Override public final String[] getOverlayApks(String targetPackageName) {
860            return getStaticOverlayPaths(targetPackageName, null);
861        }
862
863        @Override public final String[] getOverlayPaths(String targetPackageName,
864                String targetPath) {
865            return getStaticOverlayPaths(targetPackageName, targetPath);
866        }
867    }
868
869    class ParallelPackageParserCallback extends PackageParserCallback {
870        List<PackageParser.Package> mOverlayPackages = null;
871
872        void findStaticOverlayPackages() {
873            synchronized (mPackages) {
874                for (PackageParser.Package p : mPackages.values()) {
875                    if (p.mOverlayIsStatic) {
876                        if (mOverlayPackages == null) {
877                            mOverlayPackages = new ArrayList<PackageParser.Package>();
878                        }
879                        mOverlayPackages.add(p);
880                    }
881                }
882            }
883        }
884
885        @Override
886        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
887            // We can trust mOverlayPackages without holding mPackages because package uninstall
888            // can't happen while running parallel parsing.
889            // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
890            // because mInstallLock is held before running parallel parsing.
891            // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
892            return mOverlayPackages == null ? null :
893                    getStaticOverlayPaths(
894                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
895                            targetPath);
896        }
897    }
898
899    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
900    final ParallelPackageParserCallback mParallelPackageParserCallback =
901            new ParallelPackageParserCallback();
902
903    public static final class SharedLibraryEntry {
904        public final @Nullable String path;
905        public final @Nullable String apk;
906        public final @NonNull SharedLibraryInfo info;
907
908        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
909                String declaringPackageName, long declaringPackageVersionCode) {
910            path = _path;
911            apk = _apk;
912            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
913                    declaringPackageName, declaringPackageVersionCode), null);
914        }
915    }
916
917    // Currently known shared libraries.
918    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
919    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
920            new ArrayMap<>();
921
922    // All available activities, for your resolving pleasure.
923    final ActivityIntentResolver mActivities =
924            new ActivityIntentResolver();
925
926    // All available receivers, for your resolving pleasure.
927    final ActivityIntentResolver mReceivers =
928            new ActivityIntentResolver();
929
930    // All available services, for your resolving pleasure.
931    final ServiceIntentResolver mServices = new ServiceIntentResolver();
932
933    // All available providers, for your resolving pleasure.
934    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
935
936    // Mapping from provider base names (first directory in content URI codePath)
937    // to the provider information.
938    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
939            new ArrayMap<String, PackageParser.Provider>();
940
941    // Mapping from instrumentation class names to info about them.
942    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
943            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
944
945    // Packages whose data we have transfered into another package, thus
946    // should no longer exist.
947    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
948
949    // Broadcast actions that are only available to the system.
950    @GuardedBy("mProtectedBroadcasts")
951    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
952
953    /** List of packages waiting for verification. */
954    final SparseArray<PackageVerificationState> mPendingVerification
955            = new SparseArray<PackageVerificationState>();
956
957    final PackageInstallerService mInstallerService;
958
959    final ArtManagerService mArtManagerService;
960
961    private final PackageDexOptimizer mPackageDexOptimizer;
962    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
963    // is used by other apps).
964    private final DexManager mDexManager;
965
966    private AtomicInteger mNextMoveId = new AtomicInteger();
967    private final MoveCallbacks mMoveCallbacks;
968
969    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
970
971    // Cache of users who need badging.
972    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
973
974    /** Token for keys in mPendingVerification. */
975    private int mPendingVerificationToken = 0;
976
977    volatile boolean mSystemReady;
978    volatile boolean mSafeMode;
979    volatile boolean mHasSystemUidErrors;
980    private volatile boolean mWebInstantAppsDisabled;
981
982    ApplicationInfo mAndroidApplication;
983    final ActivityInfo mResolveActivity = new ActivityInfo();
984    final ResolveInfo mResolveInfo = new ResolveInfo();
985    ComponentName mResolveComponentName;
986    PackageParser.Package mPlatformPackage;
987    ComponentName mCustomResolverComponentName;
988
989    boolean mResolverReplaced = false;
990
991    private final @Nullable ComponentName mIntentFilterVerifierComponent;
992    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
993
994    private int mIntentFilterVerificationToken = 0;
995
996    /** The service connection to the ephemeral resolver */
997    final InstantAppResolverConnection mInstantAppResolverConnection;
998    /** Component used to show resolver settings for Instant Apps */
999    final ComponentName mInstantAppResolverSettingsComponent;
1000
1001    /** Activity used to install instant applications */
1002    ActivityInfo mInstantAppInstallerActivity;
1003    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1004
1005    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1006            = new SparseArray<IntentFilterVerificationState>();
1007
1008    // TODO remove this and go through mPermissonManager directly
1009    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1010    private final PermissionManagerInternal mPermissionManager;
1011
1012    // List of packages names to keep cached, even if they are uninstalled for all users
1013    private List<String> mKeepUninstalledPackages;
1014
1015    private UserManagerInternal mUserManagerInternal;
1016    private ActivityManagerInternal mActivityManagerInternal;
1017
1018    private DeviceIdleController.LocalService mDeviceIdleController;
1019
1020    private File mCacheDir;
1021
1022    private Future<?> mPrepareAppDataFuture;
1023
1024    private static class IFVerificationParams {
1025        PackageParser.Package pkg;
1026        boolean replacing;
1027        int userId;
1028        int verifierUid;
1029
1030        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1031                int _userId, int _verifierUid) {
1032            pkg = _pkg;
1033            replacing = _replacing;
1034            userId = _userId;
1035            replacing = _replacing;
1036            verifierUid = _verifierUid;
1037        }
1038    }
1039
1040    private interface IntentFilterVerifier<T extends IntentFilter> {
1041        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1042                                               T filter, String packageName);
1043        void startVerifications(int userId);
1044        void receiveVerificationResponse(int verificationId);
1045    }
1046
1047    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1048        private Context mContext;
1049        private ComponentName mIntentFilterVerifierComponent;
1050        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1051
1052        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1053            mContext = context;
1054            mIntentFilterVerifierComponent = verifierComponent;
1055        }
1056
1057        private String getDefaultScheme() {
1058            return IntentFilter.SCHEME_HTTPS;
1059        }
1060
1061        @Override
1062        public void startVerifications(int userId) {
1063            // Launch verifications requests
1064            int count = mCurrentIntentFilterVerifications.size();
1065            for (int n=0; n<count; n++) {
1066                int verificationId = mCurrentIntentFilterVerifications.get(n);
1067                final IntentFilterVerificationState ivs =
1068                        mIntentFilterVerificationStates.get(verificationId);
1069
1070                String packageName = ivs.getPackageName();
1071
1072                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1073                final int filterCount = filters.size();
1074                ArraySet<String> domainsSet = new ArraySet<>();
1075                for (int m=0; m<filterCount; m++) {
1076                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1077                    domainsSet.addAll(filter.getHostsList());
1078                }
1079                synchronized (mPackages) {
1080                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1081                            packageName, domainsSet) != null) {
1082                        scheduleWriteSettingsLocked();
1083                    }
1084                }
1085                sendVerificationRequest(verificationId, ivs);
1086            }
1087            mCurrentIntentFilterVerifications.clear();
1088        }
1089
1090        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1091            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1092            verificationIntent.putExtra(
1093                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1094                    verificationId);
1095            verificationIntent.putExtra(
1096                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1097                    getDefaultScheme());
1098            verificationIntent.putExtra(
1099                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1100                    ivs.getHostsString());
1101            verificationIntent.putExtra(
1102                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1103                    ivs.getPackageName());
1104            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1105            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1106
1107            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1108            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1109                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1110                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1111
1112            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1113            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1114                    "Sending IntentFilter verification broadcast");
1115        }
1116
1117        public void receiveVerificationResponse(int verificationId) {
1118            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1119
1120            final boolean verified = ivs.isVerified();
1121
1122            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1123            final int count = filters.size();
1124            if (DEBUG_DOMAIN_VERIFICATION) {
1125                Slog.i(TAG, "Received verification response " + verificationId
1126                        + " for " + count + " filters, verified=" + verified);
1127            }
1128            for (int n=0; n<count; n++) {
1129                PackageParser.ActivityIntentInfo filter = filters.get(n);
1130                filter.setVerified(verified);
1131
1132                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1133                        + " verified with result:" + verified + " and hosts:"
1134                        + ivs.getHostsString());
1135            }
1136
1137            mIntentFilterVerificationStates.remove(verificationId);
1138
1139            final String packageName = ivs.getPackageName();
1140            IntentFilterVerificationInfo ivi = null;
1141
1142            synchronized (mPackages) {
1143                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1144            }
1145            if (ivi == null) {
1146                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1147                        + verificationId + " packageName:" + packageName);
1148                return;
1149            }
1150            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1151                    "Updating IntentFilterVerificationInfo for package " + packageName
1152                            +" verificationId:" + verificationId);
1153
1154            synchronized (mPackages) {
1155                if (verified) {
1156                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1157                } else {
1158                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1159                }
1160                scheduleWriteSettingsLocked();
1161
1162                final int userId = ivs.getUserId();
1163                if (userId != UserHandle.USER_ALL) {
1164                    final int userStatus =
1165                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1166
1167                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1168                    boolean needUpdate = false;
1169
1170                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1171                    // already been set by the User thru the Disambiguation dialog
1172                    switch (userStatus) {
1173                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1174                            if (verified) {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1176                            } else {
1177                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1178                            }
1179                            needUpdate = true;
1180                            break;
1181
1182                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1183                            if (verified) {
1184                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1185                                needUpdate = true;
1186                            }
1187                            break;
1188
1189                        default:
1190                            // Nothing to do
1191                    }
1192
1193                    if (needUpdate) {
1194                        mSettings.updateIntentFilterVerificationStatusLPw(
1195                                packageName, updatedStatus, userId);
1196                        scheduleWritePackageRestrictionsLocked(userId);
1197                    }
1198                }
1199            }
1200        }
1201
1202        @Override
1203        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1204                    ActivityIntentInfo filter, String packageName) {
1205            if (!hasValidDomains(filter)) {
1206                return false;
1207            }
1208            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1209            if (ivs == null) {
1210                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1211                        packageName);
1212            }
1213            if (DEBUG_DOMAIN_VERIFICATION) {
1214                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1215            }
1216            ivs.addFilter(filter);
1217            return true;
1218        }
1219
1220        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1221                int userId, int verificationId, String packageName) {
1222            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1223                    verifierUid, userId, packageName);
1224            ivs.setPendingState();
1225            synchronized (mPackages) {
1226                mIntentFilterVerificationStates.append(verificationId, ivs);
1227                mCurrentIntentFilterVerifications.add(verificationId);
1228            }
1229            return ivs;
1230        }
1231    }
1232
1233    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1234        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1235                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1236                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1237    }
1238
1239    // Set of pending broadcasts for aggregating enable/disable of components.
1240    static class PendingPackageBroadcasts {
1241        // for each user id, a map of <package name -> components within that package>
1242        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1243
1244        public PendingPackageBroadcasts() {
1245            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1246        }
1247
1248        public ArrayList<String> get(int userId, String packageName) {
1249            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1250            return packages.get(packageName);
1251        }
1252
1253        public void put(int userId, String packageName, ArrayList<String> components) {
1254            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1255            packages.put(packageName, components);
1256        }
1257
1258        public void remove(int userId, String packageName) {
1259            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1260            if (packages != null) {
1261                packages.remove(packageName);
1262            }
1263        }
1264
1265        public void remove(int userId) {
1266            mUidMap.remove(userId);
1267        }
1268
1269        public int userIdCount() {
1270            return mUidMap.size();
1271        }
1272
1273        public int userIdAt(int n) {
1274            return mUidMap.keyAt(n);
1275        }
1276
1277        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1278            return mUidMap.get(userId);
1279        }
1280
1281        public int size() {
1282            // total number of pending broadcast entries across all userIds
1283            int num = 0;
1284            for (int i = 0; i< mUidMap.size(); i++) {
1285                num += mUidMap.valueAt(i).size();
1286            }
1287            return num;
1288        }
1289
1290        public void clear() {
1291            mUidMap.clear();
1292        }
1293
1294        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1295            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1296            if (map == null) {
1297                map = new ArrayMap<String, ArrayList<String>>();
1298                mUidMap.put(userId, map);
1299            }
1300            return map;
1301        }
1302    }
1303    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1304
1305    // Service Connection to remote media container service to copy
1306    // package uri's from external media onto secure containers
1307    // or internal storage.
1308    private IMediaContainerService mContainerService = null;
1309
1310    static final int SEND_PENDING_BROADCAST = 1;
1311    static final int MCS_BOUND = 3;
1312    static final int END_COPY = 4;
1313    static final int INIT_COPY = 5;
1314    static final int MCS_UNBIND = 6;
1315    static final int START_CLEANING_PACKAGE = 7;
1316    static final int FIND_INSTALL_LOC = 8;
1317    static final int POST_INSTALL = 9;
1318    static final int MCS_RECONNECT = 10;
1319    static final int MCS_GIVE_UP = 11;
1320    static final int WRITE_SETTINGS = 13;
1321    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1322    static final int PACKAGE_VERIFIED = 15;
1323    static final int CHECK_PENDING_VERIFICATION = 16;
1324    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1325    static final int INTENT_FILTER_VERIFIED = 18;
1326    static final int WRITE_PACKAGE_LIST = 19;
1327    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1328    static final int DEF_CONTAINER_BIND = 21;
1329
1330    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1331
1332    // Delay time in millisecs
1333    static final int BROADCAST_DELAY = 10 * 1000;
1334
1335    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1336            2 * 60 * 60 * 1000L; /* two hours */
1337
1338    static UserManagerService sUserManager;
1339
1340    // Stores a list of users whose package restrictions file needs to be updated
1341    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1342
1343    final private DefaultContainerConnection mDefContainerConn =
1344            new DefaultContainerConnection();
1345    class DefaultContainerConnection implements ServiceConnection {
1346        public void onServiceConnected(ComponentName name, IBinder service) {
1347            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1348            final IMediaContainerService imcs = IMediaContainerService.Stub
1349                    .asInterface(Binder.allowBlocking(service));
1350            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1351        }
1352
1353        public void onServiceDisconnected(ComponentName name) {
1354            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1355        }
1356    }
1357
1358    // Recordkeeping of restore-after-install operations that are currently in flight
1359    // between the Package Manager and the Backup Manager
1360    static class PostInstallData {
1361        public InstallArgs args;
1362        public PackageInstalledInfo res;
1363
1364        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1365            args = _a;
1366            res = _r;
1367        }
1368    }
1369
1370    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1371    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1372
1373    // XML tags for backup/restore of various bits of state
1374    private static final String TAG_PREFERRED_BACKUP = "pa";
1375    private static final String TAG_DEFAULT_APPS = "da";
1376    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1377
1378    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1379    private static final String TAG_ALL_GRANTS = "rt-grants";
1380    private static final String TAG_GRANT = "grant";
1381    private static final String ATTR_PACKAGE_NAME = "pkg";
1382
1383    private static final String TAG_PERMISSION = "perm";
1384    private static final String ATTR_PERMISSION_NAME = "name";
1385    private static final String ATTR_IS_GRANTED = "g";
1386    private static final String ATTR_USER_SET = "set";
1387    private static final String ATTR_USER_FIXED = "fixed";
1388    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1389
1390    // System/policy permission grants are not backed up
1391    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1392            FLAG_PERMISSION_POLICY_FIXED
1393            | FLAG_PERMISSION_SYSTEM_FIXED
1394            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1395
1396    // And we back up these user-adjusted states
1397    private static final int USER_RUNTIME_GRANT_MASK =
1398            FLAG_PERMISSION_USER_SET
1399            | FLAG_PERMISSION_USER_FIXED
1400            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1401
1402    final @Nullable String mRequiredVerifierPackage;
1403    final @NonNull String mRequiredInstallerPackage;
1404    final @NonNull String mRequiredUninstallerPackage;
1405    final @Nullable String mSetupWizardPackage;
1406    final @Nullable String mStorageManagerPackage;
1407    final @Nullable String mSystemTextClassifierPackage;
1408    final @NonNull String mServicesSystemSharedLibraryPackageName;
1409    final @NonNull String mSharedSystemSharedLibraryPackageName;
1410
1411    private final PackageUsage mPackageUsage = new PackageUsage();
1412    private final CompilerStats mCompilerStats = new CompilerStats();
1413
1414    class PackageHandler extends Handler {
1415        private boolean mBound = false;
1416        final ArrayList<HandlerParams> mPendingInstalls =
1417            new ArrayList<HandlerParams>();
1418
1419        private boolean connectToService() {
1420            if (DEBUG_INSTALL) Log.i(TAG, "Trying to bind to DefaultContainerService");
1421            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1424                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1425                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426                mBound = true;
1427                return true;
1428            }
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1430            return false;
1431        }
1432
1433        private void disconnectService() {
1434            mContainerService = null;
1435            mBound = false;
1436            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1437            mContext.unbindService(mDefContainerConn);
1438            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1439        }
1440
1441        PackageHandler(Looper looper) {
1442            super(looper);
1443        }
1444
1445        public void handleMessage(Message msg) {
1446            try {
1447                doHandleMessage(msg);
1448            } finally {
1449                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1450            }
1451        }
1452
1453        void doHandleMessage(Message msg) {
1454            switch (msg.what) {
1455                case DEF_CONTAINER_BIND:
1456                    if (!mBound) {
1457                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1458                                System.identityHashCode(mHandler));
1459                        if (!connectToService()) {
1460                            Slog.e(TAG, "Failed to bind to media container service");
1461                        }
1462                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1463                                System.identityHashCode(mHandler));
1464                    }
1465                    break;
1466                case INIT_COPY: {
1467                    HandlerParams params = (HandlerParams) msg.obj;
1468                    int idx = mPendingInstalls.size();
1469                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1470                    // If a bind was already initiated we dont really
1471                    // need to do anything. The pending install
1472                    // will be processed later on.
1473                    if (!mBound) {
1474                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1475                                System.identityHashCode(mHandler));
1476                        // If this is the only one pending we might
1477                        // have to bind to the service again.
1478                        if (!connectToService()) {
1479                            Slog.e(TAG, "Failed to bind to media container service");
1480                            params.serviceError();
1481                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1482                                    System.identityHashCode(mHandler));
1483                            if (params.traceMethod != null) {
1484                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1485                                        params.traceCookie);
1486                            }
1487                            return;
1488                        } else {
1489                            // Once we bind to the service, the first
1490                            // pending request will be processed.
1491                            mPendingInstalls.add(idx, params);
1492                        }
1493                    } else {
1494                        mPendingInstalls.add(idx, params);
1495                        // Already bound to the service. Just make
1496                        // sure we trigger off processing the first request.
1497                        if (idx == 0) {
1498                            mHandler.sendEmptyMessage(MCS_BOUND);
1499                        }
1500                    }
1501                    break;
1502                }
1503                case MCS_BOUND: {
1504                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1505                    if (msg.obj != null) {
1506                        mContainerService = (IMediaContainerService) msg.obj;
1507                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1508                                System.identityHashCode(mHandler));
1509                    }
1510                    if (mContainerService == null) {
1511                        if (!mBound) {
1512                            // Something seriously wrong since we are not bound and we are not
1513                            // waiting for connection. Bail out.
1514                            Slog.e(TAG, "Cannot bind to media container service");
1515                            for (HandlerParams params : mPendingInstalls) {
1516                                // Indicate service bind error
1517                                params.serviceError();
1518                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1519                                        System.identityHashCode(params));
1520                                if (params.traceMethod != null) {
1521                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1522                                            params.traceMethod, params.traceCookie);
1523                                }
1524                            }
1525                            mPendingInstalls.clear();
1526                        } else {
1527                            Slog.w(TAG, "Waiting to connect to media container service");
1528                        }
1529                    } else if (mPendingInstalls.size() > 0) {
1530                        HandlerParams params = mPendingInstalls.get(0);
1531                        if (params != null) {
1532                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1533                                    System.identityHashCode(params));
1534                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1535                            if (params.startCopy()) {
1536                                // We are done...  look for more work or to
1537                                // go idle.
1538                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1539                                        "Checking for more work or unbind...");
1540                                // Delete pending install
1541                                if (mPendingInstalls.size() > 0) {
1542                                    mPendingInstalls.remove(0);
1543                                }
1544                                if (mPendingInstalls.size() == 0) {
1545                                    if (mBound) {
1546                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1547                                                "Posting delayed MCS_UNBIND");
1548                                        removeMessages(MCS_UNBIND);
1549                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1550                                        // Unbind after a little delay, to avoid
1551                                        // continual thrashing.
1552                                        sendMessageDelayed(ubmsg, 10000);
1553                                    }
1554                                } else {
1555                                    // There are more pending requests in queue.
1556                                    // Just post MCS_BOUND message to trigger processing
1557                                    // of next pending install.
1558                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1559                                            "Posting MCS_BOUND for next work");
1560                                    mHandler.sendEmptyMessage(MCS_BOUND);
1561                                }
1562                            }
1563                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1564                        }
1565                    } else {
1566                        // Should never happen ideally.
1567                        Slog.w(TAG, "Empty queue");
1568                    }
1569                    break;
1570                }
1571                case MCS_RECONNECT: {
1572                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1573                    if (mPendingInstalls.size() > 0) {
1574                        if (mBound) {
1575                            disconnectService();
1576                        }
1577                        if (!connectToService()) {
1578                            Slog.e(TAG, "Failed to bind to media container service");
1579                            for (HandlerParams params : mPendingInstalls) {
1580                                // Indicate service bind error
1581                                params.serviceError();
1582                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1583                                        System.identityHashCode(params));
1584                            }
1585                            mPendingInstalls.clear();
1586                        }
1587                    }
1588                    break;
1589                }
1590                case MCS_UNBIND: {
1591                    // If there is no actual work left, then time to unbind.
1592                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1593
1594                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1595                        if (mBound) {
1596                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1597
1598                            disconnectService();
1599                        }
1600                    } else if (mPendingInstalls.size() > 0) {
1601                        // There are more pending requests in queue.
1602                        // Just post MCS_BOUND message to trigger processing
1603                        // of next pending install.
1604                        mHandler.sendEmptyMessage(MCS_BOUND);
1605                    }
1606
1607                    break;
1608                }
1609                case MCS_GIVE_UP: {
1610                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1611                    HandlerParams params = mPendingInstalls.remove(0);
1612                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1613                            System.identityHashCode(params));
1614                    break;
1615                }
1616                case SEND_PENDING_BROADCAST: {
1617                    String packages[];
1618                    ArrayList<String> components[];
1619                    int size = 0;
1620                    int uids[];
1621                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1622                    synchronized (mPackages) {
1623                        if (mPendingBroadcasts == null) {
1624                            return;
1625                        }
1626                        size = mPendingBroadcasts.size();
1627                        if (size <= 0) {
1628                            // Nothing to be done. Just return
1629                            return;
1630                        }
1631                        packages = new String[size];
1632                        components = new ArrayList[size];
1633                        uids = new int[size];
1634                        int i = 0;  // filling out the above arrays
1635
1636                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1637                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1638                            Iterator<Map.Entry<String, ArrayList<String>>> it
1639                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1640                                            .entrySet().iterator();
1641                            while (it.hasNext() && i < size) {
1642                                Map.Entry<String, ArrayList<String>> ent = it.next();
1643                                packages[i] = ent.getKey();
1644                                components[i] = ent.getValue();
1645                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1646                                uids[i] = (ps != null)
1647                                        ? UserHandle.getUid(packageUserId, ps.appId)
1648                                        : -1;
1649                                i++;
1650                            }
1651                        }
1652                        size = i;
1653                        mPendingBroadcasts.clear();
1654                    }
1655                    // Send broadcasts
1656                    for (int i = 0; i < size; i++) {
1657                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1658                    }
1659                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1660                    break;
1661                }
1662                case START_CLEANING_PACKAGE: {
1663                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1664                    final String packageName = (String)msg.obj;
1665                    final int userId = msg.arg1;
1666                    final boolean andCode = msg.arg2 != 0;
1667                    synchronized (mPackages) {
1668                        if (userId == UserHandle.USER_ALL) {
1669                            int[] users = sUserManager.getUserIds();
1670                            for (int user : users) {
1671                                mSettings.addPackageToCleanLPw(
1672                                        new PackageCleanItem(user, packageName, andCode));
1673                            }
1674                        } else {
1675                            mSettings.addPackageToCleanLPw(
1676                                    new PackageCleanItem(userId, packageName, andCode));
1677                        }
1678                    }
1679                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1680                    startCleaningPackages();
1681                } break;
1682                case POST_INSTALL: {
1683                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1684
1685                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1686                    final boolean didRestore = (msg.arg2 != 0);
1687                    mRunningInstalls.delete(msg.arg1);
1688
1689                    if (data != null) {
1690                        InstallArgs args = data.args;
1691                        PackageInstalledInfo parentRes = data.res;
1692
1693                        final boolean grantPermissions = (args.installFlags
1694                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1695                        final boolean killApp = (args.installFlags
1696                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1697                        final boolean virtualPreload = ((args.installFlags
1698                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1699                        final String[] grantedPermissions = args.installGrantPermissions;
1700
1701                        // Handle the parent package
1702                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1703                                virtualPreload, grantedPermissions, didRestore,
1704                                args.installerPackageName, args.observer);
1705
1706                        // Handle the child packages
1707                        final int childCount = (parentRes.addedChildPackages != null)
1708                                ? parentRes.addedChildPackages.size() : 0;
1709                        for (int i = 0; i < childCount; i++) {
1710                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1711                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1712                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1713                                    args.installerPackageName, args.observer);
1714                        }
1715
1716                        // Log tracing if needed
1717                        if (args.traceMethod != null) {
1718                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1719                                    args.traceCookie);
1720                        }
1721                    } else {
1722                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1723                    }
1724
1725                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1726                } break;
1727                case WRITE_SETTINGS: {
1728                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1729                    synchronized (mPackages) {
1730                        removeMessages(WRITE_SETTINGS);
1731                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1732                        mSettings.writeLPr();
1733                        mDirtyUsers.clear();
1734                    }
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1736                } break;
1737                case WRITE_PACKAGE_RESTRICTIONS: {
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1739                    synchronized (mPackages) {
1740                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1741                        for (int userId : mDirtyUsers) {
1742                            mSettings.writePackageRestrictionsLPr(userId);
1743                        }
1744                        mDirtyUsers.clear();
1745                    }
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747                } break;
1748                case WRITE_PACKAGE_LIST: {
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1750                    synchronized (mPackages) {
1751                        removeMessages(WRITE_PACKAGE_LIST);
1752                        mSettings.writePackageListLPr(msg.arg1);
1753                    }
1754                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1755                } break;
1756                case CHECK_PENDING_VERIFICATION: {
1757                    final int verificationId = msg.arg1;
1758                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1759
1760                    if ((state != null) && !state.timeoutExtended()) {
1761                        final InstallArgs args = state.getInstallArgs();
1762                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1763
1764                        Slog.i(TAG, "Verification timed out for " + originUri);
1765                        mPendingVerification.remove(verificationId);
1766
1767                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1768
1769                        final UserHandle user = args.getUser();
1770                        if (getDefaultVerificationResponse(user)
1771                                == PackageManager.VERIFICATION_ALLOW) {
1772                            Slog.i(TAG, "Continuing with installation of " + originUri);
1773                            state.setVerifierResponse(Binder.getCallingUid(),
1774                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1775                            broadcastPackageVerified(verificationId, originUri,
1776                                    PackageManager.VERIFICATION_ALLOW, user);
1777                            try {
1778                                ret = args.copyApk(mContainerService, true);
1779                            } catch (RemoteException e) {
1780                                Slog.e(TAG, "Could not contact the ContainerService");
1781                            }
1782                        } else {
1783                            broadcastPackageVerified(verificationId, originUri,
1784                                    PackageManager.VERIFICATION_REJECT, user);
1785                        }
1786
1787                        Trace.asyncTraceEnd(
1788                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1789
1790                        processPendingInstall(args, ret);
1791                        mHandler.sendEmptyMessage(MCS_UNBIND);
1792                    }
1793                    break;
1794                }
1795                case PACKAGE_VERIFIED: {
1796                    final int verificationId = msg.arg1;
1797
1798                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1799                    if (state == null) {
1800                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1801                        break;
1802                    }
1803
1804                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1805
1806                    state.setVerifierResponse(response.callerUid, response.code);
1807
1808                    if (state.isVerificationComplete()) {
1809                        mPendingVerification.remove(verificationId);
1810
1811                        final InstallArgs args = state.getInstallArgs();
1812                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1813
1814                        int ret;
1815                        if (state.isInstallAllowed()) {
1816                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1817                            broadcastPackageVerified(verificationId, originUri,
1818                                    response.code, state.getInstallArgs().getUser());
1819                            try {
1820                                ret = args.copyApk(mContainerService, true);
1821                            } catch (RemoteException e) {
1822                                Slog.e(TAG, "Could not contact the ContainerService");
1823                            }
1824                        } else {
1825                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1826                        }
1827
1828                        Trace.asyncTraceEnd(
1829                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1830
1831                        processPendingInstall(args, ret);
1832                        mHandler.sendEmptyMessage(MCS_UNBIND);
1833                    }
1834
1835                    break;
1836                }
1837                case START_INTENT_FILTER_VERIFICATIONS: {
1838                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1839                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1840                            params.replacing, params.pkg);
1841                    break;
1842                }
1843                case INTENT_FILTER_VERIFIED: {
1844                    final int verificationId = msg.arg1;
1845
1846                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1847                            verificationId);
1848                    if (state == null) {
1849                        Slog.w(TAG, "Invalid IntentFilter verification token "
1850                                + verificationId + " received");
1851                        break;
1852                    }
1853
1854                    final int userId = state.getUserId();
1855
1856                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857                            "Processing IntentFilter verification with token:"
1858                            + verificationId + " and userId:" + userId);
1859
1860                    final IntentFilterVerificationResponse response =
1861                            (IntentFilterVerificationResponse) msg.obj;
1862
1863                    state.setVerifierResponse(response.callerUid, response.code);
1864
1865                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1866                            "IntentFilter verification with token:" + verificationId
1867                            + " and userId:" + userId
1868                            + " is settings verifier response with response code:"
1869                            + response.code);
1870
1871                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1872                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1873                                + response.getFailedDomainsString());
1874                    }
1875
1876                    if (state.isVerificationComplete()) {
1877                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1878                    } else {
1879                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1880                                "IntentFilter verification with token:" + verificationId
1881                                + " was not said to be complete");
1882                    }
1883
1884                    break;
1885                }
1886                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1887                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1888                            mInstantAppResolverConnection,
1889                            (InstantAppRequest) msg.obj,
1890                            mInstantAppInstallerActivity,
1891                            mHandler);
1892                }
1893            }
1894        }
1895    }
1896
1897    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1898        @Override
1899        public void onGidsChanged(int appId, int userId) {
1900            mHandler.post(new Runnable() {
1901                @Override
1902                public void run() {
1903                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1904                }
1905            });
1906        }
1907        @Override
1908        public void onPermissionGranted(int uid, int userId) {
1909            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1910
1911            // Not critical; if this is lost, the application has to request again.
1912            synchronized (mPackages) {
1913                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1914            }
1915        }
1916        @Override
1917        public void onInstallPermissionGranted() {
1918            synchronized (mPackages) {
1919                scheduleWriteSettingsLocked();
1920            }
1921        }
1922        @Override
1923        public void onPermissionRevoked(int uid, int userId) {
1924            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1925
1926            synchronized (mPackages) {
1927                // Critical; after this call the application should never have the permission
1928                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1929            }
1930
1931            final int appId = UserHandle.getAppId(uid);
1932            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1933        }
1934        @Override
1935        public void onInstallPermissionRevoked() {
1936            synchronized (mPackages) {
1937                scheduleWriteSettingsLocked();
1938            }
1939        }
1940        @Override
1941        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1942            synchronized (mPackages) {
1943                for (int userId : updatedUserIds) {
1944                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1945                }
1946            }
1947        }
1948        @Override
1949        public void onInstallPermissionUpdated() {
1950            synchronized (mPackages) {
1951                scheduleWriteSettingsLocked();
1952            }
1953        }
1954        @Override
1955        public void onPermissionRemoved() {
1956            synchronized (mPackages) {
1957                mSettings.writeLPr();
1958            }
1959        }
1960    };
1961
1962    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1963            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1964            boolean launchedForRestore, String installerPackage,
1965            IPackageInstallObserver2 installObserver) {
1966        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1967            // Send the removed broadcasts
1968            if (res.removedInfo != null) {
1969                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1970            }
1971
1972            // Now that we successfully installed the package, grant runtime
1973            // permissions if requested before broadcasting the install. Also
1974            // for legacy apps in permission review mode we clear the permission
1975            // review flag which is used to emulate runtime permissions for
1976            // legacy apps.
1977            if (grantPermissions) {
1978                final int callingUid = Binder.getCallingUid();
1979                mPermissionManager.grantRequestedRuntimePermissions(
1980                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1981                        mPermissionCallback);
1982            }
1983
1984            final boolean update = res.removedInfo != null
1985                    && res.removedInfo.removedPackage != null;
1986            final String installerPackageName =
1987                    res.installerPackageName != null
1988                            ? res.installerPackageName
1989                            : res.removedInfo != null
1990                                    ? res.removedInfo.installerPackageName
1991                                    : null;
1992
1993            // If this is the first time we have child packages for a disabled privileged
1994            // app that had no children, we grant requested runtime permissions to the new
1995            // children if the parent on the system image had them already granted.
1996            if (res.pkg.parentPackage != null) {
1997                final int callingUid = Binder.getCallingUid();
1998                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1999                        res.pkg, callingUid, mPermissionCallback);
2000            }
2001
2002            synchronized (mPackages) {
2003                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2004            }
2005
2006            final String packageName = res.pkg.applicationInfo.packageName;
2007
2008            // Determine the set of users who are adding this package for
2009            // the first time vs. those who are seeing an update.
2010            int[] firstUserIds = EMPTY_INT_ARRAY;
2011            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2012            int[] updateUserIds = EMPTY_INT_ARRAY;
2013            int[] instantUserIds = EMPTY_INT_ARRAY;
2014            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2015            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2016            for (int newUser : res.newUsers) {
2017                final boolean isInstantApp = ps.getInstantApp(newUser);
2018                if (allNewUsers) {
2019                    if (isInstantApp) {
2020                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2021                    } else {
2022                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2023                    }
2024                    continue;
2025                }
2026                boolean isNew = true;
2027                for (int origUser : res.origUsers) {
2028                    if (origUser == newUser) {
2029                        isNew = false;
2030                        break;
2031                    }
2032                }
2033                if (isNew) {
2034                    if (isInstantApp) {
2035                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2036                    } else {
2037                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2038                    }
2039                } else {
2040                    if (isInstantApp) {
2041                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2042                    } else {
2043                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2044                    }
2045                }
2046            }
2047
2048            // Send installed broadcasts if the package is not a static shared lib.
2049            if (res.pkg.staticSharedLibName == null) {
2050                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2051
2052                // Send added for users that see the package for the first time
2053                // sendPackageAddedForNewUsers also deals with system apps
2054                int appId = UserHandle.getAppId(res.uid);
2055                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2056                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2057                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2058
2059                // Send added for users that don't see the package for the first time
2060                Bundle extras = new Bundle(1);
2061                extras.putInt(Intent.EXTRA_UID, res.uid);
2062                if (update) {
2063                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2064                }
2065                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2066                        extras, 0 /*flags*/,
2067                        null /*targetPackage*/, null /*finishedReceiver*/,
2068                        updateUserIds, instantUserIds);
2069                if (installerPackageName != null) {
2070                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2071                            extras, 0 /*flags*/,
2072                            installerPackageName, null /*finishedReceiver*/,
2073                            updateUserIds, instantUserIds);
2074                }
2075                // if the required verifier is defined, but, is not the installer of record
2076                // for the package, it gets notified
2077                final boolean notifyVerifier = mRequiredVerifierPackage != null
2078                        && !mRequiredVerifierPackage.equals(installerPackageName);
2079                if (notifyVerifier) {
2080                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2081                            extras, 0 /*flags*/,
2082                            mRequiredVerifierPackage, null /*finishedReceiver*/,
2083                            updateUserIds, instantUserIds);
2084                }
2085
2086                // Send replaced for users that don't see the package for the first time
2087                if (update) {
2088                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2089                            packageName, extras, 0 /*flags*/,
2090                            null /*targetPackage*/, null /*finishedReceiver*/,
2091                            updateUserIds, instantUserIds);
2092                    if (installerPackageName != null) {
2093                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2094                                extras, 0 /*flags*/,
2095                                installerPackageName, null /*finishedReceiver*/,
2096                                updateUserIds, instantUserIds);
2097                    }
2098                    if (notifyVerifier) {
2099                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2100                                extras, 0 /*flags*/,
2101                                mRequiredVerifierPackage, null /*finishedReceiver*/,
2102                                updateUserIds, instantUserIds);
2103                    }
2104                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2105                            null /*package*/, null /*extras*/, 0 /*flags*/,
2106                            packageName /*targetPackage*/,
2107                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2108                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2109                    // First-install and we did a restore, so we're responsible for the
2110                    // first-launch broadcast.
2111                    if (DEBUG_BACKUP) {
2112                        Slog.i(TAG, "Post-restore of " + packageName
2113                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2114                    }
2115                    sendFirstLaunchBroadcast(packageName, installerPackage,
2116                            firstUserIds, firstInstantUserIds);
2117                }
2118
2119                // Send broadcast package appeared if forward locked/external for all users
2120                // treat asec-hosted packages like removable media on upgrade
2121                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2122                    if (DEBUG_INSTALL) {
2123                        Slog.i(TAG, "upgrading pkg " + res.pkg
2124                                + " is ASEC-hosted -> AVAILABLE");
2125                    }
2126                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2127                    ArrayList<String> pkgList = new ArrayList<>(1);
2128                    pkgList.add(packageName);
2129                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2130                }
2131            }
2132
2133            // Work that needs to happen on first install within each user
2134            if (firstUserIds != null && firstUserIds.length > 0) {
2135                synchronized (mPackages) {
2136                    for (int userId : firstUserIds) {
2137                        // If this app is a browser and it's newly-installed for some
2138                        // users, clear any default-browser state in those users. The
2139                        // app's nature doesn't depend on the user, so we can just check
2140                        // its browser nature in any user and generalize.
2141                        if (packageIsBrowser(packageName, userId)) {
2142                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2143                        }
2144
2145                        // We may also need to apply pending (restored) runtime
2146                        // permission grants within these users.
2147                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2148                    }
2149                }
2150            }
2151
2152            if (allNewUsers && !update) {
2153                notifyPackageAdded(packageName);
2154            }
2155
2156            // Log current value of "unknown sources" setting
2157            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2158                    getUnknownSourcesSettings());
2159
2160            // Remove the replaced package's older resources safely now
2161            // We delete after a gc for applications  on sdcard.
2162            if (res.removedInfo != null && res.removedInfo.args != null) {
2163                Runtime.getRuntime().gc();
2164                synchronized (mInstallLock) {
2165                    res.removedInfo.args.doPostDeleteLI(true);
2166                }
2167            } else {
2168                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2169                // and not block here.
2170                VMRuntime.getRuntime().requestConcurrentGC();
2171            }
2172
2173            // Notify DexManager that the package was installed for new users.
2174            // The updated users should already be indexed and the package code paths
2175            // should not change.
2176            // Don't notify the manager for ephemeral apps as they are not expected to
2177            // survive long enough to benefit of background optimizations.
2178            for (int userId : firstUserIds) {
2179                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2180                // There's a race currently where some install events may interleave with an uninstall.
2181                // This can lead to package info being null (b/36642664).
2182                if (info != null) {
2183                    mDexManager.notifyPackageInstalled(info, userId);
2184                }
2185            }
2186        }
2187
2188        // If someone is watching installs - notify them
2189        if (installObserver != null) {
2190            try {
2191                Bundle extras = extrasForInstallResult(res);
2192                installObserver.onPackageInstalled(res.name, res.returnCode,
2193                        res.returnMsg, extras);
2194            } catch (RemoteException e) {
2195                Slog.i(TAG, "Observer no longer exists.");
2196            }
2197        }
2198    }
2199
2200    private StorageEventListener mStorageListener = new StorageEventListener() {
2201        @Override
2202        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2203            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2204                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2205                    final String volumeUuid = vol.getFsUuid();
2206
2207                    // Clean up any users or apps that were removed or recreated
2208                    // while this volume was missing
2209                    sUserManager.reconcileUsers(volumeUuid);
2210                    reconcileApps(volumeUuid);
2211
2212                    // Clean up any install sessions that expired or were
2213                    // cancelled while this volume was missing
2214                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2215
2216                    loadPrivatePackages(vol);
2217
2218                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2219                    unloadPrivatePackages(vol);
2220                }
2221            }
2222        }
2223
2224        @Override
2225        public void onVolumeForgotten(String fsUuid) {
2226            if (TextUtils.isEmpty(fsUuid)) {
2227                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2228                return;
2229            }
2230
2231            // Remove any apps installed on the forgotten volume
2232            synchronized (mPackages) {
2233                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2234                for (PackageSetting ps : packages) {
2235                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2236                    deletePackageVersioned(new VersionedPackage(ps.name,
2237                            PackageManager.VERSION_CODE_HIGHEST),
2238                            new LegacyPackageDeleteObserver(null).getBinder(),
2239                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2240                    // Try very hard to release any references to this package
2241                    // so we don't risk the system server being killed due to
2242                    // open FDs
2243                    AttributeCache.instance().removePackage(ps.name);
2244                }
2245
2246                mSettings.onVolumeForgotten(fsUuid);
2247                mSettings.writeLPr();
2248            }
2249        }
2250    };
2251
2252    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2253        Bundle extras = null;
2254        switch (res.returnCode) {
2255            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2256                extras = new Bundle();
2257                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2258                        res.origPermission);
2259                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2260                        res.origPackage);
2261                break;
2262            }
2263            case PackageManager.INSTALL_SUCCEEDED: {
2264                extras = new Bundle();
2265                extras.putBoolean(Intent.EXTRA_REPLACING,
2266                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2267                break;
2268            }
2269        }
2270        return extras;
2271    }
2272
2273    void scheduleWriteSettingsLocked() {
2274        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2275            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2276        }
2277    }
2278
2279    void scheduleWritePackageListLocked(int userId) {
2280        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2281            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2282            msg.arg1 = userId;
2283            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2284        }
2285    }
2286
2287    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2288        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2289        scheduleWritePackageRestrictionsLocked(userId);
2290    }
2291
2292    void scheduleWritePackageRestrictionsLocked(int userId) {
2293        final int[] userIds = (userId == UserHandle.USER_ALL)
2294                ? sUserManager.getUserIds() : new int[]{userId};
2295        for (int nextUserId : userIds) {
2296            if (!sUserManager.exists(nextUserId)) return;
2297            mDirtyUsers.add(nextUserId);
2298            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2299                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2300            }
2301        }
2302    }
2303
2304    public static PackageManagerService main(Context context, Installer installer,
2305            boolean factoryTest, boolean onlyCore) {
2306        // Self-check for initial settings.
2307        PackageManagerServiceCompilerMapping.checkProperties();
2308
2309        PackageManagerService m = new PackageManagerService(context, installer,
2310                factoryTest, onlyCore);
2311        m.enableSystemUserPackages();
2312        ServiceManager.addService("package", m);
2313        final PackageManagerNative pmn = m.new PackageManagerNative();
2314        ServiceManager.addService("package_native", pmn);
2315        return m;
2316    }
2317
2318    private void enableSystemUserPackages() {
2319        if (!UserManager.isSplitSystemUser()) {
2320            return;
2321        }
2322        // For system user, enable apps based on the following conditions:
2323        // - app is whitelisted or belong to one of these groups:
2324        //   -- system app which has no launcher icons
2325        //   -- system app which has INTERACT_ACROSS_USERS permission
2326        //   -- system IME app
2327        // - app is not in the blacklist
2328        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2329        Set<String> enableApps = new ArraySet<>();
2330        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2331                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2332                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2333        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2334        enableApps.addAll(wlApps);
2335        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2336                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2337        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2338        enableApps.removeAll(blApps);
2339        Log.i(TAG, "Applications installed for system user: " + enableApps);
2340        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2341                UserHandle.SYSTEM);
2342        final int allAppsSize = allAps.size();
2343        synchronized (mPackages) {
2344            for (int i = 0; i < allAppsSize; i++) {
2345                String pName = allAps.get(i);
2346                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2347                // Should not happen, but we shouldn't be failing if it does
2348                if (pkgSetting == null) {
2349                    continue;
2350                }
2351                boolean install = enableApps.contains(pName);
2352                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2353                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2354                            + " for system user");
2355                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2356                }
2357            }
2358            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2359        }
2360    }
2361
2362    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2363        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2364                Context.DISPLAY_SERVICE);
2365        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2366    }
2367
2368    /**
2369     * Requests that files preopted on a secondary system partition be copied to the data partition
2370     * if possible.  Note that the actual copying of the files is accomplished by init for security
2371     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2372     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2373     */
2374    private static void requestCopyPreoptedFiles() {
2375        final int WAIT_TIME_MS = 100;
2376        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2377        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2378            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2379            // We will wait for up to 100 seconds.
2380            final long timeStart = SystemClock.uptimeMillis();
2381            final long timeEnd = timeStart + 100 * 1000;
2382            long timeNow = timeStart;
2383            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2384                try {
2385                    Thread.sleep(WAIT_TIME_MS);
2386                } catch (InterruptedException e) {
2387                    // Do nothing
2388                }
2389                timeNow = SystemClock.uptimeMillis();
2390                if (timeNow > timeEnd) {
2391                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2392                    Slog.wtf(TAG, "cppreopt did not finish!");
2393                    break;
2394                }
2395            }
2396
2397            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2398        }
2399    }
2400
2401    public PackageManagerService(Context context, Installer installer,
2402            boolean factoryTest, boolean onlyCore) {
2403        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2404        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2405        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2406                SystemClock.uptimeMillis());
2407
2408        if (mSdkVersion <= 0) {
2409            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2410        }
2411
2412        mContext = context;
2413
2414        mFactoryTest = factoryTest;
2415        mOnlyCore = onlyCore;
2416        mMetrics = new DisplayMetrics();
2417        mInstaller = installer;
2418
2419        // Create sub-components that provide services / data. Order here is important.
2420        synchronized (mInstallLock) {
2421        synchronized (mPackages) {
2422            // Expose private service for system components to use.
2423            LocalServices.addService(
2424                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2425            sUserManager = new UserManagerService(context, this,
2426                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2427            mPermissionManager = PermissionManagerService.create(context,
2428                    new DefaultPermissionGrantedCallback() {
2429                        @Override
2430                        public void onDefaultRuntimePermissionsGranted(int userId) {
2431                            synchronized(mPackages) {
2432                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2433                            }
2434                        }
2435                    }, mPackages /*externalLock*/);
2436            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2437            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2438        }
2439        }
2440        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2441                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2442        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2443                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2444        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2445                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2446        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2447                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2448        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2449                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2450        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2451                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2452        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2453                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2454
2455        String separateProcesses = SystemProperties.get("debug.separate_processes");
2456        if (separateProcesses != null && separateProcesses.length() > 0) {
2457            if ("*".equals(separateProcesses)) {
2458                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2459                mSeparateProcesses = null;
2460                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2461            } else {
2462                mDefParseFlags = 0;
2463                mSeparateProcesses = separateProcesses.split(",");
2464                Slog.w(TAG, "Running with debug.separate_processes: "
2465                        + separateProcesses);
2466            }
2467        } else {
2468            mDefParseFlags = 0;
2469            mSeparateProcesses = null;
2470        }
2471
2472        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2473                "*dexopt*");
2474        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2475                installer, mInstallLock);
2476        mDexManager = new DexManager(mContext, this, mPackageDexOptimizer, installer, mInstallLock,
2477                dexManagerListener);
2478        mArtManagerService = new ArtManagerService(mContext, this, installer, mInstallLock);
2479        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2480
2481        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2482                FgThread.get().getLooper());
2483
2484        getDefaultDisplayMetrics(context, mMetrics);
2485
2486        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2487        SystemConfig systemConfig = SystemConfig.getInstance();
2488        mAvailableFeatures = systemConfig.getAvailableFeatures();
2489        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2490
2491        mProtectedPackages = new ProtectedPackages(mContext);
2492
2493        synchronized (mInstallLock) {
2494        // writer
2495        synchronized (mPackages) {
2496            mHandlerThread = new ServiceThread(TAG,
2497                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2498            mHandlerThread.start();
2499            mHandler = new PackageHandler(mHandlerThread.getLooper());
2500            mProcessLoggingHandler = new ProcessLoggingHandler();
2501            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2502            mInstantAppRegistry = new InstantAppRegistry(this);
2503
2504            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2505            final int builtInLibCount = libConfig.size();
2506            for (int i = 0; i < builtInLibCount; i++) {
2507                String name = libConfig.keyAt(i);
2508                String path = libConfig.valueAt(i);
2509                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2510                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2511            }
2512
2513            SELinuxMMAC.readInstallPolicy();
2514
2515            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2516            FallbackCategoryProvider.loadFallbacks();
2517            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2518
2519            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2520            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2521            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2522
2523            // Clean up orphaned packages for which the code path doesn't exist
2524            // and they are an update to a system app - caused by bug/32321269
2525            final int packageSettingCount = mSettings.mPackages.size();
2526            for (int i = packageSettingCount - 1; i >= 0; i--) {
2527                PackageSetting ps = mSettings.mPackages.valueAt(i);
2528                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2529                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2530                    mSettings.mPackages.removeAt(i);
2531                    mSettings.enableSystemPackageLPw(ps.name);
2532                }
2533            }
2534
2535            if (mFirstBoot) {
2536                requestCopyPreoptedFiles();
2537            }
2538
2539            String customResolverActivity = Resources.getSystem().getString(
2540                    R.string.config_customResolverActivity);
2541            if (TextUtils.isEmpty(customResolverActivity)) {
2542                customResolverActivity = null;
2543            } else {
2544                mCustomResolverComponentName = ComponentName.unflattenFromString(
2545                        customResolverActivity);
2546            }
2547
2548            long startTime = SystemClock.uptimeMillis();
2549
2550            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2551                    startTime);
2552
2553            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2554            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2555
2556            if (bootClassPath == null) {
2557                Slog.w(TAG, "No BOOTCLASSPATH found!");
2558            }
2559
2560            if (systemServerClassPath == null) {
2561                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2562            }
2563
2564            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2565
2566            final VersionInfo ver = mSettings.getInternalVersion();
2567            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2568            if (mIsUpgrade) {
2569                logCriticalInfo(Log.INFO,
2570                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2571            }
2572
2573            // when upgrading from pre-M, promote system app permissions from install to runtime
2574            mPromoteSystemApps =
2575                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2576
2577            // When upgrading from pre-N, we need to handle package extraction like first boot,
2578            // as there is no profiling data available.
2579            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2580
2581            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2582
2583            // save off the names of pre-existing system packages prior to scanning; we don't
2584            // want to automatically grant runtime permissions for new system apps
2585            if (mPromoteSystemApps) {
2586                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2587                while (pkgSettingIter.hasNext()) {
2588                    PackageSetting ps = pkgSettingIter.next();
2589                    if (isSystemApp(ps)) {
2590                        mExistingSystemPackages.add(ps.name);
2591                    }
2592                }
2593            }
2594
2595            mCacheDir = preparePackageParserCache(mIsUpgrade);
2596
2597            // Set flag to monitor and not change apk file paths when
2598            // scanning install directories.
2599            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2600
2601            if (mIsUpgrade || mFirstBoot) {
2602                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2603            }
2604
2605            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2606            // For security and version matching reason, only consider
2607            // overlay packages if they reside in the right directory.
2608            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2609                    mDefParseFlags
2610                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2611                    scanFlags
2612                    | SCAN_AS_SYSTEM
2613                    | SCAN_AS_VENDOR,
2614                    0);
2615            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2616                    mDefParseFlags
2617                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2618                    scanFlags
2619                    | SCAN_AS_SYSTEM
2620                    | SCAN_AS_PRODUCT,
2621                    0);
2622
2623            mParallelPackageParserCallback.findStaticOverlayPackages();
2624
2625            // Find base frameworks (resource packages without code).
2626            scanDirTracedLI(frameworkDir,
2627                    mDefParseFlags
2628                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2629                    scanFlags
2630                    | SCAN_NO_DEX
2631                    | SCAN_AS_SYSTEM
2632                    | SCAN_AS_PRIVILEGED,
2633                    0);
2634
2635            // Collect privileged system packages.
2636            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2637            scanDirTracedLI(privilegedAppDir,
2638                    mDefParseFlags
2639                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2640                    scanFlags
2641                    | SCAN_AS_SYSTEM
2642                    | SCAN_AS_PRIVILEGED,
2643                    0);
2644
2645            // Collect ordinary system packages.
2646            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2647            scanDirTracedLI(systemAppDir,
2648                    mDefParseFlags
2649                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2650                    scanFlags
2651                    | SCAN_AS_SYSTEM,
2652                    0);
2653
2654            // Collect privileged vendor packages.
2655            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2656            try {
2657                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2658            } catch (IOException e) {
2659                // failed to look up canonical path, continue with original one
2660            }
2661            scanDirTracedLI(privilegedVendorAppDir,
2662                    mDefParseFlags
2663                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2664                    scanFlags
2665                    | SCAN_AS_SYSTEM
2666                    | SCAN_AS_VENDOR
2667                    | SCAN_AS_PRIVILEGED,
2668                    0);
2669
2670            // Collect ordinary vendor packages.
2671            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2672            try {
2673                vendorAppDir = vendorAppDir.getCanonicalFile();
2674            } catch (IOException e) {
2675                // failed to look up canonical path, continue with original one
2676            }
2677            scanDirTracedLI(vendorAppDir,
2678                    mDefParseFlags
2679                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2680                    scanFlags
2681                    | SCAN_AS_SYSTEM
2682                    | SCAN_AS_VENDOR,
2683                    0);
2684
2685            // Collect privileged odm packages. /odm is another vendor partition
2686            // other than /vendor.
2687            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2688                        "priv-app");
2689            try {
2690                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2691            } catch (IOException e) {
2692                // failed to look up canonical path, continue with original one
2693            }
2694            scanDirTracedLI(privilegedOdmAppDir,
2695                    mDefParseFlags
2696                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2697                    scanFlags
2698                    | SCAN_AS_SYSTEM
2699                    | SCAN_AS_VENDOR
2700                    | SCAN_AS_PRIVILEGED,
2701                    0);
2702
2703            // Collect ordinary odm packages. /odm is another vendor partition
2704            // other than /vendor.
2705            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2706            try {
2707                odmAppDir = odmAppDir.getCanonicalFile();
2708            } catch (IOException e) {
2709                // failed to look up canonical path, continue with original one
2710            }
2711            scanDirTracedLI(odmAppDir,
2712                    mDefParseFlags
2713                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2714                    scanFlags
2715                    | SCAN_AS_SYSTEM
2716                    | SCAN_AS_VENDOR,
2717                    0);
2718
2719            // Collect all OEM packages.
2720            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2721            scanDirTracedLI(oemAppDir,
2722                    mDefParseFlags
2723                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2724                    scanFlags
2725                    | SCAN_AS_SYSTEM
2726                    | SCAN_AS_OEM,
2727                    0);
2728
2729            // Collected privileged product packages.
2730            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2731            try {
2732                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2733            } catch (IOException e) {
2734                // failed to look up canonical path, continue with original one
2735            }
2736            scanDirTracedLI(privilegedProductAppDir,
2737                    mDefParseFlags
2738                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2739                    scanFlags
2740                    | SCAN_AS_SYSTEM
2741                    | SCAN_AS_PRODUCT
2742                    | SCAN_AS_PRIVILEGED,
2743                    0);
2744
2745            // Collect ordinary product packages.
2746            File productAppDir = new File(Environment.getProductDirectory(), "app");
2747            try {
2748                productAppDir = productAppDir.getCanonicalFile();
2749            } catch (IOException e) {
2750                // failed to look up canonical path, continue with original one
2751            }
2752            scanDirTracedLI(productAppDir,
2753                    mDefParseFlags
2754                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2755                    scanFlags
2756                    | SCAN_AS_SYSTEM
2757                    | SCAN_AS_PRODUCT,
2758                    0);
2759
2760            // Prune any system packages that no longer exist.
2761            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2762            // Stub packages must either be replaced with full versions in the /data
2763            // partition or be disabled.
2764            final List<String> stubSystemApps = new ArrayList<>();
2765            if (!mOnlyCore) {
2766                // do this first before mucking with mPackages for the "expecting better" case
2767                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2768                while (pkgIterator.hasNext()) {
2769                    final PackageParser.Package pkg = pkgIterator.next();
2770                    if (pkg.isStub) {
2771                        stubSystemApps.add(pkg.packageName);
2772                    }
2773                }
2774
2775                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2776                while (psit.hasNext()) {
2777                    PackageSetting ps = psit.next();
2778
2779                    /*
2780                     * If this is not a system app, it can't be a
2781                     * disable system app.
2782                     */
2783                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2784                        continue;
2785                    }
2786
2787                    /*
2788                     * If the package is scanned, it's not erased.
2789                     */
2790                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2791                    if (scannedPkg != null) {
2792                        /*
2793                         * If the system app is both scanned and in the
2794                         * disabled packages list, then it must have been
2795                         * added via OTA. Remove it from the currently
2796                         * scanned package so the previously user-installed
2797                         * application can be scanned.
2798                         */
2799                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2800                            logCriticalInfo(Log.WARN,
2801                                    "Expecting better updated system app for " + ps.name
2802                                    + "; removing system app.  Last known"
2803                                    + " codePath=" + ps.codePathString
2804                                    + ", versionCode=" + ps.versionCode
2805                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2806                            removePackageLI(scannedPkg, true);
2807                            mExpectingBetter.put(ps.name, ps.codePath);
2808                        }
2809
2810                        continue;
2811                    }
2812
2813                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2814                        psit.remove();
2815                        logCriticalInfo(Log.WARN, "System package " + ps.name
2816                                + " no longer exists; it's data will be wiped");
2817                        // Actual deletion of code and data will be handled by later
2818                        // reconciliation step
2819                    } else {
2820                        // we still have a disabled system package, but, it still might have
2821                        // been removed. check the code path still exists and check there's
2822                        // still a package. the latter can happen if an OTA keeps the same
2823                        // code path, but, changes the package name.
2824                        final PackageSetting disabledPs =
2825                                mSettings.getDisabledSystemPkgLPr(ps.name);
2826                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2827                                || disabledPs.pkg == null) {
2828                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2829                        }
2830                    }
2831                }
2832            }
2833
2834            //delete tmp files
2835            deleteTempPackageFiles();
2836
2837            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2838
2839            // Remove any shared userIDs that have no associated packages
2840            mSettings.pruneSharedUsersLPw();
2841            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2842            final int systemPackagesCount = mPackages.size();
2843            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2844                    + " ms, packageCount: " + systemPackagesCount
2845                    + " , timePerPackage: "
2846                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2847                    + " , cached: " + cachedSystemApps);
2848            if (mIsUpgrade && systemPackagesCount > 0) {
2849                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2850                        ((int) systemScanTime) / systemPackagesCount);
2851            }
2852            if (!mOnlyCore) {
2853                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2854                        SystemClock.uptimeMillis());
2855                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2856
2857                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2858                        | PackageParser.PARSE_FORWARD_LOCK,
2859                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2860
2861                // Remove disable package settings for updated system apps that were
2862                // removed via an OTA. If the update is no longer present, remove the
2863                // app completely. Otherwise, revoke their system privileges.
2864                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2865                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2866                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2867                    final String msg;
2868                    if (deletedPkg == null) {
2869                        // should have found an update, but, we didn't; remove everything
2870                        msg = "Updated system package " + deletedAppName
2871                                + " no longer exists; removing its data";
2872                        // Actual deletion of code and data will be handled by later
2873                        // reconciliation step
2874                    } else {
2875                        // found an update; revoke system privileges
2876                        msg = "Updated system package + " + deletedAppName
2877                                + " no longer exists; revoking system privileges";
2878
2879                        // Don't do anything if a stub is removed from the system image. If
2880                        // we were to remove the uncompressed version from the /data partition,
2881                        // this is where it'd be done.
2882
2883                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2884                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2885                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2886                    }
2887                    logCriticalInfo(Log.WARN, msg);
2888                }
2889
2890                /*
2891                 * Make sure all system apps that we expected to appear on
2892                 * the userdata partition actually showed up. If they never
2893                 * appeared, crawl back and revive the system version.
2894                 */
2895                for (int i = 0; i < mExpectingBetter.size(); i++) {
2896                    final String packageName = mExpectingBetter.keyAt(i);
2897                    if (!mPackages.containsKey(packageName)) {
2898                        final File scanFile = mExpectingBetter.valueAt(i);
2899
2900                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2901                                + " but never showed up; reverting to system");
2902
2903                        final @ParseFlags int reparseFlags;
2904                        final @ScanFlags int rescanFlags;
2905                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2906                            reparseFlags =
2907                                    mDefParseFlags |
2908                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2909                            rescanFlags =
2910                                    scanFlags
2911                                    | SCAN_AS_SYSTEM
2912                                    | SCAN_AS_PRIVILEGED;
2913                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2914                            reparseFlags =
2915                                    mDefParseFlags |
2916                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2917                            rescanFlags =
2918                                    scanFlags
2919                                    | SCAN_AS_SYSTEM;
2920                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2921                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2922                            reparseFlags =
2923                                    mDefParseFlags |
2924                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2925                            rescanFlags =
2926                                    scanFlags
2927                                    | SCAN_AS_SYSTEM
2928                                    | SCAN_AS_VENDOR
2929                                    | SCAN_AS_PRIVILEGED;
2930                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2931                                || FileUtils.contains(odmAppDir, scanFile)) {
2932                            reparseFlags =
2933                                    mDefParseFlags |
2934                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2935                            rescanFlags =
2936                                    scanFlags
2937                                    | SCAN_AS_SYSTEM
2938                                    | SCAN_AS_VENDOR;
2939                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2940                            reparseFlags =
2941                                    mDefParseFlags |
2942                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2943                            rescanFlags =
2944                                    scanFlags
2945                                    | SCAN_AS_SYSTEM
2946                                    | SCAN_AS_OEM;
2947                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2948                            reparseFlags =
2949                                    mDefParseFlags |
2950                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2951                            rescanFlags =
2952                                    scanFlags
2953                                    | SCAN_AS_SYSTEM
2954                                    | SCAN_AS_PRODUCT
2955                                    | SCAN_AS_PRIVILEGED;
2956                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2957                            reparseFlags =
2958                                    mDefParseFlags |
2959                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2960                            rescanFlags =
2961                                    scanFlags
2962                                    | SCAN_AS_SYSTEM
2963                                    | SCAN_AS_PRODUCT;
2964                        } else {
2965                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2966                            continue;
2967                        }
2968
2969                        mSettings.enableSystemPackageLPw(packageName);
2970
2971                        try {
2972                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2973                        } catch (PackageManagerException e) {
2974                            Slog.e(TAG, "Failed to parse original system package: "
2975                                    + e.getMessage());
2976                        }
2977                    }
2978                }
2979
2980                // Uncompress and install any stubbed system applications.
2981                // This must be done last to ensure all stubs are replaced or disabled.
2982                decompressSystemApplications(stubSystemApps, scanFlags);
2983
2984                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2985                                - cachedSystemApps;
2986
2987                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2988                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2989                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2990                        + " ms, packageCount: " + dataPackagesCount
2991                        + " , timePerPackage: "
2992                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2993                        + " , cached: " + cachedNonSystemApps);
2994                if (mIsUpgrade && dataPackagesCount > 0) {
2995                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2996                            ((int) dataScanTime) / dataPackagesCount);
2997                }
2998            }
2999            mExpectingBetter.clear();
3000
3001            // Resolve the storage manager.
3002            mStorageManagerPackage = getStorageManagerPackageName();
3003
3004            // Resolve protected action filters. Only the setup wizard is allowed to
3005            // have a high priority filter for these actions.
3006            mSetupWizardPackage = getSetupWizardPackageName();
3007            if (mProtectedFilters.size() > 0) {
3008                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
3009                    Slog.i(TAG, "No setup wizard;"
3010                        + " All protected intents capped to priority 0");
3011                }
3012                for (ActivityIntentInfo filter : mProtectedFilters) {
3013                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
3014                        if (DEBUG_FILTERS) {
3015                            Slog.i(TAG, "Found setup wizard;"
3016                                + " allow priority " + filter.getPriority() + ";"
3017                                + " package: " + filter.activity.info.packageName
3018                                + " activity: " + filter.activity.className
3019                                + " priority: " + filter.getPriority());
3020                        }
3021                        // skip setup wizard; allow it to keep the high priority filter
3022                        continue;
3023                    }
3024                    if (DEBUG_FILTERS) {
3025                        Slog.i(TAG, "Protected action; cap priority to 0;"
3026                                + " package: " + filter.activity.info.packageName
3027                                + " activity: " + filter.activity.className
3028                                + " origPrio: " + filter.getPriority());
3029                    }
3030                    filter.setPriority(0);
3031                }
3032            }
3033
3034            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3035
3036            mDeferProtectedFilters = false;
3037            mProtectedFilters.clear();
3038
3039            // Now that we know all of the shared libraries, update all clients to have
3040            // the correct library paths.
3041            updateAllSharedLibrariesLPw(null);
3042
3043            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3044                // NOTE: We ignore potential failures here during a system scan (like
3045                // the rest of the commands above) because there's precious little we
3046                // can do about it. A settings error is reported, though.
3047                final List<String> changedAbiCodePath =
3048                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3049                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3050                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3051                        final String codePathString = changedAbiCodePath.get(i);
3052                        try {
3053                            mInstaller.rmdex(codePathString,
3054                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3055                        } catch (InstallerException ignored) {
3056                        }
3057                    }
3058                }
3059                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3060                // SELinux domain.
3061                setting.fixSeInfoLocked();
3062            }
3063
3064            // Now that we know all the packages we are keeping,
3065            // read and update their last usage times.
3066            mPackageUsage.read(mPackages);
3067            mCompilerStats.read();
3068
3069            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3070                    SystemClock.uptimeMillis());
3071            Slog.i(TAG, "Time to scan packages: "
3072                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3073                    + " seconds");
3074
3075            // If the platform SDK has changed since the last time we booted,
3076            // we need to re-grant app permission to catch any new ones that
3077            // appear.  This is really a hack, and means that apps can in some
3078            // cases get permissions that the user didn't initially explicitly
3079            // allow...  it would be nice to have some better way to handle
3080            // this situation.
3081            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3082            if (sdkUpdated) {
3083                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3084                        + mSdkVersion + "; regranting permissions for internal storage");
3085            }
3086            mPermissionManager.updateAllPermissions(
3087                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3088                    mPermissionCallback);
3089            ver.sdkVersion = mSdkVersion;
3090
3091            // If this is the first boot or an update from pre-M, and it is a normal
3092            // boot, then we need to initialize the default preferred apps across
3093            // all defined users.
3094            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3095                for (UserInfo user : sUserManager.getUsers(true)) {
3096                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3097                    applyFactoryDefaultBrowserLPw(user.id);
3098                    primeDomainVerificationsLPw(user.id);
3099                }
3100            }
3101
3102            // Prepare storage for system user really early during boot,
3103            // since core system apps like SettingsProvider and SystemUI
3104            // can't wait for user to start
3105            final int storageFlags;
3106            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3107                storageFlags = StorageManager.FLAG_STORAGE_DE;
3108            } else {
3109                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3110            }
3111            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3112                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3113                    true /* onlyCoreApps */);
3114            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3115                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3116                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3117                traceLog.traceBegin("AppDataFixup");
3118                try {
3119                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3120                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3121                } catch (InstallerException e) {
3122                    Slog.w(TAG, "Trouble fixing GIDs", e);
3123                }
3124                traceLog.traceEnd();
3125
3126                traceLog.traceBegin("AppDataPrepare");
3127                if (deferPackages == null || deferPackages.isEmpty()) {
3128                    return;
3129                }
3130                int count = 0;
3131                for (String pkgName : deferPackages) {
3132                    PackageParser.Package pkg = null;
3133                    synchronized (mPackages) {
3134                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3135                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3136                            pkg = ps.pkg;
3137                        }
3138                    }
3139                    if (pkg != null) {
3140                        synchronized (mInstallLock) {
3141                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3142                                    true /* maybeMigrateAppData */);
3143                        }
3144                        count++;
3145                    }
3146                }
3147                traceLog.traceEnd();
3148                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3149            }, "prepareAppData");
3150
3151            // If this is first boot after an OTA, and a normal boot, then
3152            // we need to clear code cache directories.
3153            // Note that we do *not* clear the application profiles. These remain valid
3154            // across OTAs and are used to drive profile verification (post OTA) and
3155            // profile compilation (without waiting to collect a fresh set of profiles).
3156            if (mIsUpgrade && !onlyCore) {
3157                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3158                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3159                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3160                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3161                        // No apps are running this early, so no need to freeze
3162                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3163                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3164                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3165                    }
3166                }
3167                ver.fingerprint = Build.FINGERPRINT;
3168            }
3169
3170            checkDefaultBrowser();
3171
3172            // clear only after permissions and other defaults have been updated
3173            mExistingSystemPackages.clear();
3174            mPromoteSystemApps = false;
3175
3176            // All the changes are done during package scanning.
3177            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3178
3179            // can downgrade to reader
3180            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3181            mSettings.writeLPr();
3182            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3183            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3184                    SystemClock.uptimeMillis());
3185
3186            if (!mOnlyCore) {
3187                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3188                mRequiredInstallerPackage = getRequiredInstallerLPr();
3189                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3190                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3191                if (mIntentFilterVerifierComponent != null) {
3192                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3193                            mIntentFilterVerifierComponent);
3194                } else {
3195                    mIntentFilterVerifier = null;
3196                }
3197                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3198                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3199                        SharedLibraryInfo.VERSION_UNDEFINED);
3200                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3201                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3202                        SharedLibraryInfo.VERSION_UNDEFINED);
3203            } else {
3204                mRequiredVerifierPackage = null;
3205                mRequiredInstallerPackage = null;
3206                mRequiredUninstallerPackage = null;
3207                mIntentFilterVerifierComponent = null;
3208                mIntentFilterVerifier = null;
3209                mServicesSystemSharedLibraryPackageName = null;
3210                mSharedSystemSharedLibraryPackageName = null;
3211            }
3212
3213            mInstallerService = new PackageInstallerService(context, this);
3214            final Pair<ComponentName, String> instantAppResolverComponent =
3215                    getInstantAppResolverLPr();
3216            if (instantAppResolverComponent != null) {
3217                if (DEBUG_INSTANT) {
3218                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3219                }
3220                mInstantAppResolverConnection = new InstantAppResolverConnection(
3221                        mContext, instantAppResolverComponent.first,
3222                        instantAppResolverComponent.second);
3223                mInstantAppResolverSettingsComponent =
3224                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3225            } else {
3226                mInstantAppResolverConnection = null;
3227                mInstantAppResolverSettingsComponent = null;
3228            }
3229            updateInstantAppInstallerLocked(null);
3230
3231            // Read and update the usage of dex files.
3232            // Do this at the end of PM init so that all the packages have their
3233            // data directory reconciled.
3234            // At this point we know the code paths of the packages, so we can validate
3235            // the disk file and build the internal cache.
3236            // The usage file is expected to be small so loading and verifying it
3237            // should take a fairly small time compare to the other activities (e.g. package
3238            // scanning).
3239            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3240            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3241            for (int userId : currentUserIds) {
3242                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3243            }
3244            mDexManager.load(userPackages);
3245            if (mIsUpgrade) {
3246                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3247                        (int) (SystemClock.uptimeMillis() - startTime));
3248            }
3249        } // synchronized (mPackages)
3250        } // synchronized (mInstallLock)
3251
3252        // Now after opening every single application zip, make sure they
3253        // are all flushed.  Not really needed, but keeps things nice and
3254        // tidy.
3255        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3256        Runtime.getRuntime().gc();
3257        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3258
3259        // The initial scanning above does many calls into installd while
3260        // holding the mPackages lock, but we're mostly interested in yelling
3261        // once we have a booted system.
3262        mInstaller.setWarnIfHeld(mPackages);
3263
3264        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3265    }
3266
3267    /**
3268     * Uncompress and install stub applications.
3269     * <p>In order to save space on the system partition, some applications are shipped in a
3270     * compressed form. In addition the compressed bits for the full application, the
3271     * system image contains a tiny stub comprised of only the Android manifest.
3272     * <p>During the first boot, attempt to uncompress and install the full application. If
3273     * the application can't be installed for any reason, disable the stub and prevent
3274     * uncompressing the full application during future boots.
3275     * <p>In order to forcefully attempt an installation of a full application, go to app
3276     * settings and enable the application.
3277     */
3278    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3279        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3280            final String pkgName = stubSystemApps.get(i);
3281            // skip if the system package is already disabled
3282            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3283                stubSystemApps.remove(i);
3284                continue;
3285            }
3286            // skip if the package isn't installed (?!); this should never happen
3287            final PackageParser.Package pkg = mPackages.get(pkgName);
3288            if (pkg == null) {
3289                stubSystemApps.remove(i);
3290                continue;
3291            }
3292            // skip if the package has been disabled by the user
3293            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3294            if (ps != null) {
3295                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3296                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3297                    stubSystemApps.remove(i);
3298                    continue;
3299                }
3300            }
3301
3302            if (DEBUG_COMPRESSION) {
3303                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3304            }
3305
3306            // uncompress the binary to its eventual destination on /data
3307            final File scanFile = decompressPackage(pkg);
3308            if (scanFile == null) {
3309                continue;
3310            }
3311
3312            // install the package to replace the stub on /system
3313            try {
3314                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3315                removePackageLI(pkg, true /*chatty*/);
3316                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3317                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3318                        UserHandle.USER_SYSTEM, "android");
3319                stubSystemApps.remove(i);
3320                continue;
3321            } catch (PackageManagerException e) {
3322                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3323            }
3324
3325            // any failed attempt to install the package will be cleaned up later
3326        }
3327
3328        // disable any stub still left; these failed to install the full application
3329        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3330            final String pkgName = stubSystemApps.get(i);
3331            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3332            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3333                    UserHandle.USER_SYSTEM, "android");
3334            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3335        }
3336    }
3337
3338    /**
3339     * Decompresses the given package on the system image onto
3340     * the /data partition.
3341     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3342     */
3343    private File decompressPackage(PackageParser.Package pkg) {
3344        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3345        if (compressedFiles == null || compressedFiles.length == 0) {
3346            if (DEBUG_COMPRESSION) {
3347                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3348            }
3349            return null;
3350        }
3351        final File dstCodePath =
3352                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3353        int ret = PackageManager.INSTALL_SUCCEEDED;
3354        try {
3355            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3356            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3357            for (File srcFile : compressedFiles) {
3358                final String srcFileName = srcFile.getName();
3359                final String dstFileName = srcFileName.substring(
3360                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3361                final File dstFile = new File(dstCodePath, dstFileName);
3362                ret = decompressFile(srcFile, dstFile);
3363                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3364                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3365                            + "; pkg: " + pkg.packageName
3366                            + ", file: " + dstFileName);
3367                    break;
3368                }
3369            }
3370        } catch (ErrnoException e) {
3371            logCriticalInfo(Log.ERROR, "Failed to decompress"
3372                    + "; pkg: " + pkg.packageName
3373                    + ", err: " + e.errno);
3374        }
3375        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3376            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3377            NativeLibraryHelper.Handle handle = null;
3378            try {
3379                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3380                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3381                        null /*abiOverride*/);
3382            } catch (IOException e) {
3383                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3384                        + "; pkg: " + pkg.packageName);
3385                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3386            } finally {
3387                IoUtils.closeQuietly(handle);
3388            }
3389        }
3390        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3391            if (dstCodePath == null || !dstCodePath.exists()) {
3392                return null;
3393            }
3394            removeCodePathLI(dstCodePath);
3395            return null;
3396        }
3397
3398        return dstCodePath;
3399    }
3400
3401    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3402        // we're only interested in updating the installer appliction when 1) it's not
3403        // already set or 2) the modified package is the installer
3404        if (mInstantAppInstallerActivity != null
3405                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3406                        .equals(modifiedPackage)) {
3407            return;
3408        }
3409        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3410    }
3411
3412    private static File preparePackageParserCache(boolean isUpgrade) {
3413        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3414            return null;
3415        }
3416
3417        // Disable package parsing on eng builds to allow for faster incremental development.
3418        if (Build.IS_ENG) {
3419            return null;
3420        }
3421
3422        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3423            Slog.i(TAG, "Disabling package parser cache due to system property.");
3424            return null;
3425        }
3426
3427        // The base directory for the package parser cache lives under /data/system/.
3428        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3429                "package_cache");
3430        if (cacheBaseDir == null) {
3431            return null;
3432        }
3433
3434        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3435        // This also serves to "GC" unused entries when the package cache version changes (which
3436        // can only happen during upgrades).
3437        if (isUpgrade) {
3438            FileUtils.deleteContents(cacheBaseDir);
3439        }
3440
3441
3442        // Return the versioned package cache directory. This is something like
3443        // "/data/system/package_cache/1"
3444        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3445
3446        if (cacheDir == null) {
3447            // Something went wrong. Attempt to delete everything and return.
3448            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3449            FileUtils.deleteContentsAndDir(cacheBaseDir);
3450            return null;
3451        }
3452
3453        // The following is a workaround to aid development on non-numbered userdebug
3454        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3455        // the system partition is newer.
3456        //
3457        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3458        // that starts with "eng." to signify that this is an engineering build and not
3459        // destined for release.
3460        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3461            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3462
3463            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3464            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3465            // in general and should not be used for production changes. In this specific case,
3466            // we know that they will work.
3467            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3468            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3469                FileUtils.deleteContents(cacheBaseDir);
3470                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3471            }
3472        }
3473
3474        return cacheDir;
3475    }
3476
3477    @Override
3478    public boolean isFirstBoot() {
3479        // allow instant applications
3480        return mFirstBoot;
3481    }
3482
3483    @Override
3484    public boolean isOnlyCoreApps() {
3485        // allow instant applications
3486        return mOnlyCore;
3487    }
3488
3489    @Override
3490    public boolean isUpgrade() {
3491        // allow instant applications
3492        // The system property allows testing ota flow when upgraded to the same image.
3493        return mIsUpgrade || SystemProperties.getBoolean(
3494                "persist.pm.mock-upgrade", false /* default */);
3495    }
3496
3497    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3498        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3499
3500        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3501                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3502                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3503        if (matches.size() == 1) {
3504            return matches.get(0).getComponentInfo().packageName;
3505        } else if (matches.size() == 0) {
3506            Log.e(TAG, "There should probably be a verifier, but, none were found");
3507            return null;
3508        }
3509        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3510    }
3511
3512    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3513        synchronized (mPackages) {
3514            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3515            if (libraryEntry == null) {
3516                throw new IllegalStateException("Missing required shared library:" + name);
3517            }
3518            return libraryEntry.apk;
3519        }
3520    }
3521
3522    private @NonNull String getRequiredInstallerLPr() {
3523        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3524        intent.addCategory(Intent.CATEGORY_DEFAULT);
3525        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3526
3527        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3528                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3529                UserHandle.USER_SYSTEM);
3530        if (matches.size() == 1) {
3531            ResolveInfo resolveInfo = matches.get(0);
3532            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3533                throw new RuntimeException("The installer must be a privileged app");
3534            }
3535            return matches.get(0).getComponentInfo().packageName;
3536        } else {
3537            throw new RuntimeException("There must be exactly one installer; found " + matches);
3538        }
3539    }
3540
3541    private @NonNull String getRequiredUninstallerLPr() {
3542        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3543        intent.addCategory(Intent.CATEGORY_DEFAULT);
3544        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3545
3546        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3547                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3548                UserHandle.USER_SYSTEM);
3549        if (resolveInfo == null ||
3550                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3551            throw new RuntimeException("There must be exactly one uninstaller; found "
3552                    + resolveInfo);
3553        }
3554        return resolveInfo.getComponentInfo().packageName;
3555    }
3556
3557    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3558        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3559
3560        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3561                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3562                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3563        ResolveInfo best = null;
3564        final int N = matches.size();
3565        for (int i = 0; i < N; i++) {
3566            final ResolveInfo cur = matches.get(i);
3567            final String packageName = cur.getComponentInfo().packageName;
3568            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3569                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3570                continue;
3571            }
3572
3573            if (best == null || cur.priority > best.priority) {
3574                best = cur;
3575            }
3576        }
3577
3578        if (best != null) {
3579            return best.getComponentInfo().getComponentName();
3580        }
3581        Slog.w(TAG, "Intent filter verifier not found");
3582        return null;
3583    }
3584
3585    @Override
3586    public @Nullable ComponentName getInstantAppResolverComponent() {
3587        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3588            return null;
3589        }
3590        synchronized (mPackages) {
3591            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3592            if (instantAppResolver == null) {
3593                return null;
3594            }
3595            return instantAppResolver.first;
3596        }
3597    }
3598
3599    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3600        final String[] packageArray =
3601                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3602        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3603            if (DEBUG_INSTANT) {
3604                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3605            }
3606            return null;
3607        }
3608
3609        final int callingUid = Binder.getCallingUid();
3610        final int resolveFlags =
3611                MATCH_DIRECT_BOOT_AWARE
3612                | MATCH_DIRECT_BOOT_UNAWARE
3613                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3614        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3615        final Intent resolverIntent = new Intent(actionName);
3616        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3617                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3618        final int N = resolvers.size();
3619        if (N == 0) {
3620            if (DEBUG_INSTANT) {
3621                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3622            }
3623            return null;
3624        }
3625
3626        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3627        for (int i = 0; i < N; i++) {
3628            final ResolveInfo info = resolvers.get(i);
3629
3630            if (info.serviceInfo == null) {
3631                continue;
3632            }
3633
3634            final String packageName = info.serviceInfo.packageName;
3635            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3636                if (DEBUG_INSTANT) {
3637                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3638                            + " pkg: " + packageName + ", info:" + info);
3639                }
3640                continue;
3641            }
3642
3643            if (DEBUG_INSTANT) {
3644                Slog.v(TAG, "Ephemeral resolver found;"
3645                        + " pkg: " + packageName + ", info:" + info);
3646            }
3647            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3648        }
3649        if (DEBUG_INSTANT) {
3650            Slog.v(TAG, "Ephemeral resolver NOT found");
3651        }
3652        return null;
3653    }
3654
3655    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3656        String[] orderedActions = Build.IS_ENG
3657                ? new String[]{
3658                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3659                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3660                : new String[]{
3661                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3662
3663        final int resolveFlags =
3664                MATCH_DIRECT_BOOT_AWARE
3665                        | MATCH_DIRECT_BOOT_UNAWARE
3666                        | Intent.FLAG_IGNORE_EPHEMERAL
3667                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3668        final Intent intent = new Intent();
3669        intent.addCategory(Intent.CATEGORY_DEFAULT);
3670        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3671        List<ResolveInfo> matches = null;
3672        for (String action : orderedActions) {
3673            intent.setAction(action);
3674            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3675                    resolveFlags, UserHandle.USER_SYSTEM);
3676            if (matches.isEmpty()) {
3677                if (DEBUG_INSTANT) {
3678                    Slog.d(TAG, "Instant App installer not found with " + action);
3679                }
3680            } else {
3681                break;
3682            }
3683        }
3684        Iterator<ResolveInfo> iter = matches.iterator();
3685        while (iter.hasNext()) {
3686            final ResolveInfo rInfo = iter.next();
3687            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3688            if (ps != null) {
3689                final PermissionsState permissionsState = ps.getPermissionsState();
3690                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3691                        || Build.IS_ENG) {
3692                    continue;
3693                }
3694            }
3695            iter.remove();
3696        }
3697        if (matches.size() == 0) {
3698            return null;
3699        } else if (matches.size() == 1) {
3700            return (ActivityInfo) matches.get(0).getComponentInfo();
3701        } else {
3702            throw new RuntimeException(
3703                    "There must be at most one ephemeral installer; found " + matches);
3704        }
3705    }
3706
3707    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3708            @NonNull ComponentName resolver) {
3709        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3710                .addCategory(Intent.CATEGORY_DEFAULT)
3711                .setPackage(resolver.getPackageName());
3712        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3713        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3714                UserHandle.USER_SYSTEM);
3715        if (matches.isEmpty()) {
3716            return null;
3717        }
3718        return matches.get(0).getComponentInfo().getComponentName();
3719    }
3720
3721    private void primeDomainVerificationsLPw(int userId) {
3722        if (DEBUG_DOMAIN_VERIFICATION) {
3723            Slog.d(TAG, "Priming domain verifications in user " + userId);
3724        }
3725
3726        SystemConfig systemConfig = SystemConfig.getInstance();
3727        ArraySet<String> packages = systemConfig.getLinkedApps();
3728
3729        for (String packageName : packages) {
3730            PackageParser.Package pkg = mPackages.get(packageName);
3731            if (pkg != null) {
3732                if (!pkg.isSystem()) {
3733                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3734                    continue;
3735                }
3736
3737                ArraySet<String> domains = null;
3738                for (PackageParser.Activity a : pkg.activities) {
3739                    for (ActivityIntentInfo filter : a.intents) {
3740                        if (hasValidDomains(filter)) {
3741                            if (domains == null) {
3742                                domains = new ArraySet<String>();
3743                            }
3744                            domains.addAll(filter.getHostsList());
3745                        }
3746                    }
3747                }
3748
3749                if (domains != null && domains.size() > 0) {
3750                    if (DEBUG_DOMAIN_VERIFICATION) {
3751                        Slog.v(TAG, "      + " + packageName);
3752                    }
3753                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3754                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3755                    // and then 'always' in the per-user state actually used for intent resolution.
3756                    final IntentFilterVerificationInfo ivi;
3757                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3758                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3759                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3760                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3761                } else {
3762                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3763                            + "' does not handle web links");
3764                }
3765            } else {
3766                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3767            }
3768        }
3769
3770        scheduleWritePackageRestrictionsLocked(userId);
3771        scheduleWriteSettingsLocked();
3772    }
3773
3774    private void applyFactoryDefaultBrowserLPw(int userId) {
3775        // The default browser app's package name is stored in a string resource,
3776        // with a product-specific overlay used for vendor customization.
3777        String browserPkg = mContext.getResources().getString(
3778                com.android.internal.R.string.default_browser);
3779        if (!TextUtils.isEmpty(browserPkg)) {
3780            // non-empty string => required to be a known package
3781            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3782            if (ps == null) {
3783                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3784                browserPkg = null;
3785            } else {
3786                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3787            }
3788        }
3789
3790        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3791        // default.  If there's more than one, just leave everything alone.
3792        if (browserPkg == null) {
3793            calculateDefaultBrowserLPw(userId);
3794        }
3795    }
3796
3797    private void calculateDefaultBrowserLPw(int userId) {
3798        List<String> allBrowsers = resolveAllBrowserApps(userId);
3799        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3800        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3801    }
3802
3803    private List<String> resolveAllBrowserApps(int userId) {
3804        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3805        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3806                PackageManager.MATCH_ALL, userId);
3807
3808        final int count = list.size();
3809        List<String> result = new ArrayList<String>(count);
3810        for (int i=0; i<count; i++) {
3811            ResolveInfo info = list.get(i);
3812            if (info.activityInfo == null
3813                    || !info.handleAllWebDataURI
3814                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3815                    || result.contains(info.activityInfo.packageName)) {
3816                continue;
3817            }
3818            result.add(info.activityInfo.packageName);
3819        }
3820
3821        return result;
3822    }
3823
3824    private boolean packageIsBrowser(String packageName, int userId) {
3825        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3826                PackageManager.MATCH_ALL, userId);
3827        final int N = list.size();
3828        for (int i = 0; i < N; i++) {
3829            ResolveInfo info = list.get(i);
3830            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3831                return true;
3832            }
3833        }
3834        return false;
3835    }
3836
3837    private void checkDefaultBrowser() {
3838        final int myUserId = UserHandle.myUserId();
3839        final String packageName = getDefaultBrowserPackageName(myUserId);
3840        if (packageName != null) {
3841            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3842            if (info == null) {
3843                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3844                synchronized (mPackages) {
3845                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3846                }
3847            }
3848        }
3849    }
3850
3851    @Override
3852    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3853            throws RemoteException {
3854        try {
3855            return super.onTransact(code, data, reply, flags);
3856        } catch (RuntimeException e) {
3857            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3858                Slog.wtf(TAG, "Package Manager Crash", e);
3859            }
3860            throw e;
3861        }
3862    }
3863
3864    static int[] appendInts(int[] cur, int[] add) {
3865        if (add == null) return cur;
3866        if (cur == null) return add;
3867        final int N = add.length;
3868        for (int i=0; i<N; i++) {
3869            cur = appendInt(cur, add[i]);
3870        }
3871        return cur;
3872    }
3873
3874    /**
3875     * Returns whether or not a full application can see an instant application.
3876     * <p>
3877     * Currently, there are three cases in which this can occur:
3878     * <ol>
3879     * <li>The calling application is a "special" process. Special processes
3880     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3881     * <li>The calling application has the permission
3882     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3883     * <li>The calling application is the default launcher on the
3884     *     system partition.</li>
3885     * </ol>
3886     */
3887    private boolean canViewInstantApps(int callingUid, int userId) {
3888        if (callingUid < Process.FIRST_APPLICATION_UID) {
3889            return true;
3890        }
3891        if (mContext.checkCallingOrSelfPermission(
3892                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3893            return true;
3894        }
3895        if (mContext.checkCallingOrSelfPermission(
3896                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3897            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3898            if (homeComponent != null
3899                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3900                return true;
3901            }
3902        }
3903        return false;
3904    }
3905
3906    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3907        if (!sUserManager.exists(userId)) return null;
3908        if (ps == null) {
3909            return null;
3910        }
3911        final int callingUid = Binder.getCallingUid();
3912        // Filter out ephemeral app metadata:
3913        //   * The system/shell/root can see metadata for any app
3914        //   * An installed app can see metadata for 1) other installed apps
3915        //     and 2) ephemeral apps that have explicitly interacted with it
3916        //   * Ephemeral apps can only see their own data and exposed installed apps
3917        //   * Holding a signature permission allows seeing instant apps
3918        if (filterAppAccessLPr(ps, callingUid, userId)) {
3919            return null;
3920        }
3921
3922        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3923                && ps.isSystem()) {
3924            flags |= MATCH_ANY_USER;
3925        }
3926
3927        final PackageUserState state = ps.readUserState(userId);
3928        PackageParser.Package p = ps.pkg;
3929        if (p != null) {
3930            final PermissionsState permissionsState = ps.getPermissionsState();
3931
3932            // Compute GIDs only if requested
3933            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3934                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3935            // Compute granted permissions only if package has requested permissions
3936            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3937                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3938
3939            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3940                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3941
3942            if (packageInfo == null) {
3943                return null;
3944            }
3945
3946            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3947                    resolveExternalPackageNameLPr(p);
3948
3949            return packageInfo;
3950        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3951            PackageInfo pi = new PackageInfo();
3952            pi.packageName = ps.name;
3953            pi.setLongVersionCode(ps.versionCode);
3954            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3955            pi.firstInstallTime = ps.firstInstallTime;
3956            pi.lastUpdateTime = ps.lastUpdateTime;
3957
3958            ApplicationInfo ai = new ApplicationInfo();
3959            ai.packageName = ps.name;
3960            ai.uid = UserHandle.getUid(userId, ps.appId);
3961            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3962            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3963            ai.setVersionCode(ps.versionCode);
3964            ai.flags = ps.pkgFlags;
3965            ai.privateFlags = ps.pkgPrivateFlags;
3966            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3967
3968            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3969                    + ps.name + "]. Provides a minimum info.");
3970            return pi;
3971        } else {
3972            return null;
3973        }
3974    }
3975
3976    @Override
3977    public void checkPackageStartable(String packageName, int userId) {
3978        final int callingUid = Binder.getCallingUid();
3979        if (getInstantAppPackageName(callingUid) != null) {
3980            throw new SecurityException("Instant applications don't have access to this method");
3981        }
3982        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3983        synchronized (mPackages) {
3984            final PackageSetting ps = mSettings.mPackages.get(packageName);
3985            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3986                throw new SecurityException("Package " + packageName + " was not found!");
3987            }
3988
3989            if (!ps.getInstalled(userId)) {
3990                throw new SecurityException(
3991                        "Package " + packageName + " was not installed for user " + userId + "!");
3992            }
3993
3994            if (mSafeMode && !ps.isSystem()) {
3995                throw new SecurityException("Package " + packageName + " not a system app!");
3996            }
3997
3998            if (mFrozenPackages.contains(packageName)) {
3999                throw new SecurityException("Package " + packageName + " is currently frozen!");
4000            }
4001
4002            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
4003                throw new SecurityException("Package " + packageName + " is not encryption aware!");
4004            }
4005        }
4006    }
4007
4008    @Override
4009    public boolean isPackageAvailable(String packageName, int userId) {
4010        if (!sUserManager.exists(userId)) return false;
4011        final int callingUid = Binder.getCallingUid();
4012        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4013                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
4014        synchronized (mPackages) {
4015            PackageParser.Package p = mPackages.get(packageName);
4016            if (p != null) {
4017                final PackageSetting ps = (PackageSetting) p.mExtras;
4018                if (filterAppAccessLPr(ps, callingUid, userId)) {
4019                    return false;
4020                }
4021                if (ps != null) {
4022                    final PackageUserState state = ps.readUserState(userId);
4023                    if (state != null) {
4024                        return PackageParser.isAvailable(state);
4025                    }
4026                }
4027            }
4028        }
4029        return false;
4030    }
4031
4032    @Override
4033    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4034        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4035                flags, Binder.getCallingUid(), userId);
4036    }
4037
4038    @Override
4039    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4040            int flags, int userId) {
4041        return getPackageInfoInternal(versionedPackage.getPackageName(),
4042                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4043    }
4044
4045    /**
4046     * Important: The provided filterCallingUid is used exclusively to filter out packages
4047     * that can be seen based on user state. It's typically the original caller uid prior
4048     * to clearing. Because it can only be provided by trusted code, it's value can be
4049     * trusted and will be used as-is; unlike userId which will be validated by this method.
4050     */
4051    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4052            int flags, int filterCallingUid, int userId) {
4053        if (!sUserManager.exists(userId)) return null;
4054        flags = updateFlagsForPackage(flags, userId, packageName);
4055        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4056                false /* requireFullPermission */, false /* checkShell */, "get package info");
4057
4058        // reader
4059        synchronized (mPackages) {
4060            // Normalize package name to handle renamed packages and static libs
4061            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4062
4063            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4064            if (matchFactoryOnly) {
4065                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4066                if (ps != null) {
4067                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4068                        return null;
4069                    }
4070                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4071                        return null;
4072                    }
4073                    return generatePackageInfo(ps, flags, userId);
4074                }
4075            }
4076
4077            PackageParser.Package p = mPackages.get(packageName);
4078            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4079                return null;
4080            }
4081            if (DEBUG_PACKAGE_INFO)
4082                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4083            if (p != null) {
4084                final PackageSetting ps = (PackageSetting) p.mExtras;
4085                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4086                    return null;
4087                }
4088                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4089                    return null;
4090                }
4091                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4092            }
4093            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4094                final PackageSetting ps = mSettings.mPackages.get(packageName);
4095                if (ps == null) return null;
4096                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4097                    return null;
4098                }
4099                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4100                    return null;
4101                }
4102                return generatePackageInfo(ps, flags, userId);
4103            }
4104        }
4105        return null;
4106    }
4107
4108    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4109        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4110            return true;
4111        }
4112        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4113            return true;
4114        }
4115        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4116            return true;
4117        }
4118        return false;
4119    }
4120
4121    private boolean isComponentVisibleToInstantApp(
4122            @Nullable ComponentName component, @ComponentType int type) {
4123        if (type == TYPE_ACTIVITY) {
4124            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4125            if (activity == null) {
4126                return false;
4127            }
4128            final boolean visibleToInstantApp =
4129                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4130            final boolean explicitlyVisibleToInstantApp =
4131                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4132            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4133        } else if (type == TYPE_RECEIVER) {
4134            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4135            if (activity == null) {
4136                return false;
4137            }
4138            final boolean visibleToInstantApp =
4139                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4140            final boolean explicitlyVisibleToInstantApp =
4141                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4142            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4143        } else if (type == TYPE_SERVICE) {
4144            final PackageParser.Service service = mServices.mServices.get(component);
4145            return service != null
4146                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4147                    : false;
4148        } else if (type == TYPE_PROVIDER) {
4149            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4150            return provider != null
4151                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4152                    : false;
4153        } else if (type == TYPE_UNKNOWN) {
4154            return isComponentVisibleToInstantApp(component);
4155        }
4156        return false;
4157    }
4158
4159    /**
4160     * Returns whether or not access to the application should be filtered.
4161     * <p>
4162     * Access may be limited based upon whether the calling or target applications
4163     * are instant applications.
4164     *
4165     * @see #canAccessInstantApps(int)
4166     */
4167    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4168            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4169        // if we're in an isolated process, get the real calling UID
4170        if (Process.isIsolated(callingUid)) {
4171            callingUid = mIsolatedOwners.get(callingUid);
4172        }
4173        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4174        final boolean callerIsInstantApp = instantAppPkgName != null;
4175        if (ps == null) {
4176            if (callerIsInstantApp) {
4177                // pretend the application exists, but, needs to be filtered
4178                return true;
4179            }
4180            return false;
4181        }
4182        // if the target and caller are the same application, don't filter
4183        if (isCallerSameApp(ps.name, callingUid)) {
4184            return false;
4185        }
4186        if (callerIsInstantApp) {
4187            // both caller and target are both instant, but, different applications, filter
4188            if (ps.getInstantApp(userId)) {
4189                return true;
4190            }
4191            // request for a specific component; if it hasn't been explicitly exposed through
4192            // property or instrumentation target, filter
4193            if (component != null) {
4194                final PackageParser.Instrumentation instrumentation =
4195                        mInstrumentation.get(component);
4196                if (instrumentation != null
4197                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4198                    return false;
4199                }
4200                return !isComponentVisibleToInstantApp(component, componentType);
4201            }
4202            // request for application; if no components have been explicitly exposed, filter
4203            return !ps.pkg.visibleToInstantApps;
4204        }
4205        if (ps.getInstantApp(userId)) {
4206            // caller can see all components of all instant applications, don't filter
4207            if (canViewInstantApps(callingUid, userId)) {
4208                return false;
4209            }
4210            // request for a specific instant application component, filter
4211            if (component != null) {
4212                return true;
4213            }
4214            // request for an instant application; if the caller hasn't been granted access, filter
4215            return !mInstantAppRegistry.isInstantAccessGranted(
4216                    userId, UserHandle.getAppId(callingUid), ps.appId);
4217        }
4218        return false;
4219    }
4220
4221    /**
4222     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4223     */
4224    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4225        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4226    }
4227
4228    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4229            int flags) {
4230        // Callers can access only the libs they depend on, otherwise they need to explicitly
4231        // ask for the shared libraries given the caller is allowed to access all static libs.
4232        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4233            // System/shell/root get to see all static libs
4234            final int appId = UserHandle.getAppId(uid);
4235            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4236                    || appId == Process.ROOT_UID) {
4237                return false;
4238            }
4239            // Installer gets to see all static libs.
4240            if (PackageManager.PERMISSION_GRANTED
4241                    == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) {
4242                return false;
4243            }
4244        }
4245
4246        // No package means no static lib as it is always on internal storage
4247        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4248            return false;
4249        }
4250
4251        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4252                ps.pkg.staticSharedLibVersion);
4253        if (libEntry == null) {
4254            return false;
4255        }
4256
4257        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4258        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4259        if (uidPackageNames == null) {
4260            return true;
4261        }
4262
4263        for (String uidPackageName : uidPackageNames) {
4264            if (ps.name.equals(uidPackageName)) {
4265                return false;
4266            }
4267            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4268            if (uidPs != null) {
4269                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4270                        libEntry.info.getName());
4271                if (index < 0) {
4272                    continue;
4273                }
4274                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4275                    return false;
4276                }
4277            }
4278        }
4279        return true;
4280    }
4281
4282    @Override
4283    public String[] currentToCanonicalPackageNames(String[] names) {
4284        final int callingUid = Binder.getCallingUid();
4285        if (getInstantAppPackageName(callingUid) != null) {
4286            return names;
4287        }
4288        final String[] out = new String[names.length];
4289        // reader
4290        synchronized (mPackages) {
4291            final int callingUserId = UserHandle.getUserId(callingUid);
4292            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4293            for (int i=names.length-1; i>=0; i--) {
4294                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4295                boolean translateName = false;
4296                if (ps != null && ps.realName != null) {
4297                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4298                    translateName = !targetIsInstantApp
4299                            || canViewInstantApps
4300                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4301                                    UserHandle.getAppId(callingUid), ps.appId);
4302                }
4303                out[i] = translateName ? ps.realName : names[i];
4304            }
4305        }
4306        return out;
4307    }
4308
4309    @Override
4310    public String[] canonicalToCurrentPackageNames(String[] names) {
4311        final int callingUid = Binder.getCallingUid();
4312        if (getInstantAppPackageName(callingUid) != null) {
4313            return names;
4314        }
4315        final String[] out = new String[names.length];
4316        // reader
4317        synchronized (mPackages) {
4318            final int callingUserId = UserHandle.getUserId(callingUid);
4319            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4320            for (int i=names.length-1; i>=0; i--) {
4321                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4322                boolean translateName = false;
4323                if (cur != null) {
4324                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4325                    final boolean targetIsInstantApp =
4326                            ps != null && ps.getInstantApp(callingUserId);
4327                    translateName = !targetIsInstantApp
4328                            || canViewInstantApps
4329                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4330                                    UserHandle.getAppId(callingUid), ps.appId);
4331                }
4332                out[i] = translateName ? cur : names[i];
4333            }
4334        }
4335        return out;
4336    }
4337
4338    @Override
4339    public int getPackageUid(String packageName, int flags, int userId) {
4340        if (!sUserManager.exists(userId)) return -1;
4341        final int callingUid = Binder.getCallingUid();
4342        flags = updateFlagsForPackage(flags, userId, packageName);
4343        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4344                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4345
4346        // reader
4347        synchronized (mPackages) {
4348            final PackageParser.Package p = mPackages.get(packageName);
4349            if (p != null && p.isMatch(flags)) {
4350                PackageSetting ps = (PackageSetting) p.mExtras;
4351                if (filterAppAccessLPr(ps, callingUid, userId)) {
4352                    return -1;
4353                }
4354                return UserHandle.getUid(userId, p.applicationInfo.uid);
4355            }
4356            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4357                final PackageSetting ps = mSettings.mPackages.get(packageName);
4358                if (ps != null && ps.isMatch(flags)
4359                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4360                    return UserHandle.getUid(userId, ps.appId);
4361                }
4362            }
4363        }
4364
4365        return -1;
4366    }
4367
4368    @Override
4369    public int[] getPackageGids(String packageName, int flags, int userId) {
4370        if (!sUserManager.exists(userId)) return null;
4371        final int callingUid = Binder.getCallingUid();
4372        flags = updateFlagsForPackage(flags, userId, packageName);
4373        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4374                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4375
4376        // reader
4377        synchronized (mPackages) {
4378            final PackageParser.Package p = mPackages.get(packageName);
4379            if (p != null && p.isMatch(flags)) {
4380                PackageSetting ps = (PackageSetting) p.mExtras;
4381                if (filterAppAccessLPr(ps, callingUid, userId)) {
4382                    return null;
4383                }
4384                // TODO: Shouldn't this be checking for package installed state for userId and
4385                // return null?
4386                return ps.getPermissionsState().computeGids(userId);
4387            }
4388            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4389                final PackageSetting ps = mSettings.mPackages.get(packageName);
4390                if (ps != null && ps.isMatch(flags)
4391                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4392                    return ps.getPermissionsState().computeGids(userId);
4393                }
4394            }
4395        }
4396
4397        return null;
4398    }
4399
4400    @Override
4401    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4402        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4403    }
4404
4405    @Override
4406    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4407            int flags) {
4408        final List<PermissionInfo> permissionList =
4409                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4410        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4411    }
4412
4413    @Override
4414    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4415        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4416    }
4417
4418    @Override
4419    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4420        final List<PermissionGroupInfo> permissionList =
4421                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4422        return (permissionList == null)
4423                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4424    }
4425
4426    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4427            int filterCallingUid, int userId) {
4428        if (!sUserManager.exists(userId)) return null;
4429        PackageSetting ps = mSettings.mPackages.get(packageName);
4430        if (ps != null) {
4431            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4432                return null;
4433            }
4434            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4435                return null;
4436            }
4437            if (ps.pkg == null) {
4438                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4439                if (pInfo != null) {
4440                    return pInfo.applicationInfo;
4441                }
4442                return null;
4443            }
4444            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4445                    ps.readUserState(userId), userId);
4446            if (ai != null) {
4447                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4448            }
4449            return ai;
4450        }
4451        return null;
4452    }
4453
4454    @Override
4455    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4456        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4457    }
4458
4459    /**
4460     * Important: The provided filterCallingUid is used exclusively to filter out applications
4461     * that can be seen based on user state. It's typically the original caller uid prior
4462     * to clearing. Because it can only be provided by trusted code, it's value can be
4463     * trusted and will be used as-is; unlike userId which will be validated by this method.
4464     */
4465    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4466            int filterCallingUid, int userId) {
4467        if (!sUserManager.exists(userId)) return null;
4468        flags = updateFlagsForApplication(flags, userId, packageName);
4469        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4470                false /* requireFullPermission */, false /* checkShell */, "get application info");
4471
4472        // writer
4473        synchronized (mPackages) {
4474            // Normalize package name to handle renamed packages and static libs
4475            packageName = resolveInternalPackageNameLPr(packageName,
4476                    PackageManager.VERSION_CODE_HIGHEST);
4477
4478            PackageParser.Package p = mPackages.get(packageName);
4479            if (DEBUG_PACKAGE_INFO) Log.v(
4480                    TAG, "getApplicationInfo " + packageName
4481                    + ": " + p);
4482            if (p != null) {
4483                PackageSetting ps = mSettings.mPackages.get(packageName);
4484                if (ps == null) return null;
4485                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4486                    return null;
4487                }
4488                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4489                    return null;
4490                }
4491                // Note: isEnabledLP() does not apply here - always return info
4492                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4493                        p, flags, ps.readUserState(userId), userId);
4494                if (ai != null) {
4495                    ai.packageName = resolveExternalPackageNameLPr(p);
4496                }
4497                return ai;
4498            }
4499            if ("android".equals(packageName)||"system".equals(packageName)) {
4500                return mAndroidApplication;
4501            }
4502            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4503                // Already generates the external package name
4504                return generateApplicationInfoFromSettingsLPw(packageName,
4505                        flags, filterCallingUid, userId);
4506            }
4507        }
4508        return null;
4509    }
4510
4511    private String normalizePackageNameLPr(String packageName) {
4512        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4513        return normalizedPackageName != null ? normalizedPackageName : packageName;
4514    }
4515
4516    @Override
4517    public void deletePreloadsFileCache() {
4518        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4519            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4520        }
4521        File dir = Environment.getDataPreloadsFileCacheDirectory();
4522        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4523        FileUtils.deleteContents(dir);
4524    }
4525
4526    @Override
4527    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4528            final int storageFlags, final IPackageDataObserver observer) {
4529        mContext.enforceCallingOrSelfPermission(
4530                android.Manifest.permission.CLEAR_APP_CACHE, null);
4531        mHandler.post(() -> {
4532            boolean success = false;
4533            try {
4534                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4535                success = true;
4536            } catch (IOException e) {
4537                Slog.w(TAG, e);
4538            }
4539            if (observer != null) {
4540                try {
4541                    observer.onRemoveCompleted(null, success);
4542                } catch (RemoteException e) {
4543                    Slog.w(TAG, e);
4544                }
4545            }
4546        });
4547    }
4548
4549    @Override
4550    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4551            final int storageFlags, final IntentSender pi) {
4552        mContext.enforceCallingOrSelfPermission(
4553                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4554        mHandler.post(() -> {
4555            boolean success = false;
4556            try {
4557                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4558                success = true;
4559            } catch (IOException e) {
4560                Slog.w(TAG, e);
4561            }
4562            if (pi != null) {
4563                try {
4564                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4565                } catch (SendIntentException e) {
4566                    Slog.w(TAG, e);
4567                }
4568            }
4569        });
4570    }
4571
4572    /**
4573     * Blocking call to clear various types of cached data across the system
4574     * until the requested bytes are available.
4575     */
4576    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4577        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4578        final File file = storage.findPathForUuid(volumeUuid);
4579        if (file.getUsableSpace() >= bytes) return;
4580
4581        if (ENABLE_FREE_CACHE_V2) {
4582            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4583                    volumeUuid);
4584            final boolean aggressive = (storageFlags
4585                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4586            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4587
4588            // 1. Pre-flight to determine if we have any chance to succeed
4589            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4590            if (internalVolume && (aggressive || SystemProperties
4591                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4592                deletePreloadsFileCache();
4593                if (file.getUsableSpace() >= bytes) return;
4594            }
4595
4596            // 3. Consider parsed APK data (aggressive only)
4597            if (internalVolume && aggressive) {
4598                FileUtils.deleteContents(mCacheDir);
4599                if (file.getUsableSpace() >= bytes) return;
4600            }
4601
4602            // 4. Consider cached app data (above quotas)
4603            try {
4604                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4605                        Installer.FLAG_FREE_CACHE_V2);
4606            } catch (InstallerException ignored) {
4607            }
4608            if (file.getUsableSpace() >= bytes) return;
4609
4610            // 5. Consider shared libraries with refcount=0 and age>min cache period
4611            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4612                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4613                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4614                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4615                return;
4616            }
4617
4618            // 6. Consider dexopt output (aggressive only)
4619            // TODO: Implement
4620
4621            // 7. Consider installed instant apps unused longer than min cache period
4622            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4623                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4624                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4625                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4626                return;
4627            }
4628
4629            // 8. Consider cached app data (below quotas)
4630            try {
4631                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4632                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4633            } catch (InstallerException ignored) {
4634            }
4635            if (file.getUsableSpace() >= bytes) return;
4636
4637            // 9. Consider DropBox entries
4638            // TODO: Implement
4639
4640            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4641            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4642                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4643                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4644                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4645                return;
4646            }
4647        } else {
4648            try {
4649                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4650            } catch (InstallerException ignored) {
4651            }
4652            if (file.getUsableSpace() >= bytes) return;
4653        }
4654
4655        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4656    }
4657
4658    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4659            throws IOException {
4660        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4661        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4662
4663        List<VersionedPackage> packagesToDelete = null;
4664        final long now = System.currentTimeMillis();
4665
4666        synchronized (mPackages) {
4667            final int[] allUsers = sUserManager.getUserIds();
4668            final int libCount = mSharedLibraries.size();
4669            for (int i = 0; i < libCount; i++) {
4670                final LongSparseArray<SharedLibraryEntry> versionedLib
4671                        = mSharedLibraries.valueAt(i);
4672                if (versionedLib == null) {
4673                    continue;
4674                }
4675                final int versionCount = versionedLib.size();
4676                for (int j = 0; j < versionCount; j++) {
4677                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4678                    // Skip packages that are not static shared libs.
4679                    if (!libInfo.isStatic()) {
4680                        break;
4681                    }
4682                    // Important: We skip static shared libs used for some user since
4683                    // in such a case we need to keep the APK on the device. The check for
4684                    // a lib being used for any user is performed by the uninstall call.
4685                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4686                    // Resolve the package name - we use synthetic package names internally
4687                    final String internalPackageName = resolveInternalPackageNameLPr(
4688                            declaringPackage.getPackageName(),
4689                            declaringPackage.getLongVersionCode());
4690                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4691                    // Skip unused static shared libs cached less than the min period
4692                    // to prevent pruning a lib needed by a subsequently installed package.
4693                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4694                        continue;
4695                    }
4696                    if (packagesToDelete == null) {
4697                        packagesToDelete = new ArrayList<>();
4698                    }
4699                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4700                            declaringPackage.getLongVersionCode()));
4701                }
4702            }
4703        }
4704
4705        if (packagesToDelete != null) {
4706            final int packageCount = packagesToDelete.size();
4707            for (int i = 0; i < packageCount; i++) {
4708                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4709                // Delete the package synchronously (will fail of the lib used for any user).
4710                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4711                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4712                                == PackageManager.DELETE_SUCCEEDED) {
4713                    if (volume.getUsableSpace() >= neededSpace) {
4714                        return true;
4715                    }
4716                }
4717            }
4718        }
4719
4720        return false;
4721    }
4722
4723    /**
4724     * Update given flags based on encryption status of current user.
4725     */
4726    private int updateFlags(int flags, int userId) {
4727        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4728                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4729            // Caller expressed an explicit opinion about what encryption
4730            // aware/unaware components they want to see, so fall through and
4731            // give them what they want
4732        } else {
4733            // Caller expressed no opinion, so match based on user state
4734            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4735                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4736            } else {
4737                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4738            }
4739        }
4740        return flags;
4741    }
4742
4743    private UserManagerInternal getUserManagerInternal() {
4744        if (mUserManagerInternal == null) {
4745            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4746        }
4747        return mUserManagerInternal;
4748    }
4749
4750    private ActivityManagerInternal getActivityManagerInternal() {
4751        if (mActivityManagerInternal == null) {
4752            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4753        }
4754        return mActivityManagerInternal;
4755    }
4756
4757
4758    private DeviceIdleController.LocalService getDeviceIdleController() {
4759        if (mDeviceIdleController == null) {
4760            mDeviceIdleController =
4761                    LocalServices.getService(DeviceIdleController.LocalService.class);
4762        }
4763        return mDeviceIdleController;
4764    }
4765
4766    /**
4767     * Update given flags when being used to request {@link PackageInfo}.
4768     */
4769    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4770        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4771        boolean triaged = true;
4772        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4773                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4774            // Caller is asking for component details, so they'd better be
4775            // asking for specific encryption matching behavior, or be triaged
4776            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4777                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4778                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4779                triaged = false;
4780            }
4781        }
4782        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4783                | PackageManager.MATCH_SYSTEM_ONLY
4784                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4785            triaged = false;
4786        }
4787        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4788            mPermissionManager.enforceCrossUserPermission(
4789                    Binder.getCallingUid(), userId, false, false,
4790                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4791                    + Debug.getCallers(5));
4792        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4793                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4794            // If the caller wants all packages and has a restricted profile associated with it,
4795            // then match all users. This is to make sure that launchers that need to access work
4796            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4797            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4798            flags |= PackageManager.MATCH_ANY_USER;
4799        }
4800        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4801            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4802                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4803        }
4804        return updateFlags(flags, userId);
4805    }
4806
4807    /**
4808     * Update given flags when being used to request {@link ApplicationInfo}.
4809     */
4810    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4811        return updateFlagsForPackage(flags, userId, cookie);
4812    }
4813
4814    /**
4815     * Update given flags when being used to request {@link ComponentInfo}.
4816     */
4817    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4818        if (cookie instanceof Intent) {
4819            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4820                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4821            }
4822        }
4823
4824        boolean triaged = true;
4825        // Caller is asking for component details, so they'd better be
4826        // asking for specific encryption matching behavior, or be triaged
4827        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4828                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4829                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4830            triaged = false;
4831        }
4832        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4833            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4834                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4835        }
4836
4837        return updateFlags(flags, userId);
4838    }
4839
4840    /**
4841     * Update given intent when being used to request {@link ResolveInfo}.
4842     */
4843    private Intent updateIntentForResolve(Intent intent) {
4844        if (intent.getSelector() != null) {
4845            intent = intent.getSelector();
4846        }
4847        if (DEBUG_PREFERRED) {
4848            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4849        }
4850        return intent;
4851    }
4852
4853    /**
4854     * Update given flags when being used to request {@link ResolveInfo}.
4855     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4856     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4857     * flag set. However, this flag is only honoured in three circumstances:
4858     * <ul>
4859     * <li>when called from a system process</li>
4860     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4861     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4862     * action and a {@code android.intent.category.BROWSABLE} category</li>
4863     * </ul>
4864     */
4865    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4866        return updateFlagsForResolve(flags, userId, intent, callingUid,
4867                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4868    }
4869    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4870            boolean wantInstantApps) {
4871        return updateFlagsForResolve(flags, userId, intent, callingUid,
4872                wantInstantApps, false /*onlyExposedExplicitly*/);
4873    }
4874    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4875            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4876        // Safe mode means we shouldn't match any third-party components
4877        if (mSafeMode) {
4878            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4879        }
4880        if (getInstantAppPackageName(callingUid) != null) {
4881            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4882            if (onlyExposedExplicitly) {
4883                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4884            }
4885            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4886            flags |= PackageManager.MATCH_INSTANT;
4887        } else {
4888            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4889            final boolean allowMatchInstant = wantInstantApps
4890                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4891            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4892                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4893            if (!allowMatchInstant) {
4894                flags &= ~PackageManager.MATCH_INSTANT;
4895            }
4896        }
4897        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4898    }
4899
4900    @Override
4901    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4902        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4903    }
4904
4905    /**
4906     * Important: The provided filterCallingUid is used exclusively to filter out activities
4907     * that can be seen based on user state. It's typically the original caller uid prior
4908     * to clearing. Because it can only be provided by trusted code, it's value can be
4909     * trusted and will be used as-is; unlike userId which will be validated by this method.
4910     */
4911    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4912            int filterCallingUid, int userId) {
4913        if (!sUserManager.exists(userId)) return null;
4914        flags = updateFlagsForComponent(flags, userId, component);
4915
4916        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4917            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4918                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4919        }
4920
4921        synchronized (mPackages) {
4922            PackageParser.Activity a = mActivities.mActivities.get(component);
4923
4924            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4925            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4926                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4927                if (ps == null) return null;
4928                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4929                    return null;
4930                }
4931                return PackageParser.generateActivityInfo(
4932                        a, flags, ps.readUserState(userId), userId);
4933            }
4934            if (mResolveComponentName.equals(component)) {
4935                return PackageParser.generateActivityInfo(
4936                        mResolveActivity, flags, new PackageUserState(), userId);
4937            }
4938        }
4939        return null;
4940    }
4941
4942    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4943        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4944            return false;
4945        }
4946        final long token = Binder.clearCallingIdentity();
4947        try {
4948            final int callingUserId = UserHandle.getUserId(callingUid);
4949            if (ActivityManager.getCurrentUser() != callingUserId) {
4950                return false;
4951            }
4952            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4953        } finally {
4954            Binder.restoreCallingIdentity(token);
4955        }
4956    }
4957
4958    @Override
4959    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4960            String resolvedType) {
4961        synchronized (mPackages) {
4962            if (component.equals(mResolveComponentName)) {
4963                // The resolver supports EVERYTHING!
4964                return true;
4965            }
4966            final int callingUid = Binder.getCallingUid();
4967            final int callingUserId = UserHandle.getUserId(callingUid);
4968            PackageParser.Activity a = mActivities.mActivities.get(component);
4969            if (a == null) {
4970                return false;
4971            }
4972            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4973            if (ps == null) {
4974                return false;
4975            }
4976            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4977                return false;
4978            }
4979            for (int i=0; i<a.intents.size(); i++) {
4980                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4981                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4982                    return true;
4983                }
4984            }
4985            return false;
4986        }
4987    }
4988
4989    @Override
4990    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4991        if (!sUserManager.exists(userId)) return null;
4992        final int callingUid = Binder.getCallingUid();
4993        flags = updateFlagsForComponent(flags, userId, component);
4994        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4995                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4996        synchronized (mPackages) {
4997            PackageParser.Activity a = mReceivers.mActivities.get(component);
4998            if (DEBUG_PACKAGE_INFO) Log.v(
4999                TAG, "getReceiverInfo " + component + ": " + a);
5000            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
5001                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5002                if (ps == null) return null;
5003                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
5004                    return null;
5005                }
5006                return PackageParser.generateActivityInfo(
5007                        a, flags, ps.readUserState(userId), userId);
5008            }
5009        }
5010        return null;
5011    }
5012
5013    @Override
5014    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
5015            int flags, int userId) {
5016        if (!sUserManager.exists(userId)) return null;
5017        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
5018        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5019            return null;
5020        }
5021
5022        flags = updateFlagsForPackage(flags, userId, null);
5023
5024        final boolean canSeeStaticLibraries =
5025                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5026                        == PERMISSION_GRANTED
5027                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5028                        == PERMISSION_GRANTED
5029                || canRequestPackageInstallsInternal(packageName,
5030                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5031                        false  /* throwIfPermNotDeclared*/)
5032                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5033                        == PERMISSION_GRANTED;
5034
5035        synchronized (mPackages) {
5036            List<SharedLibraryInfo> result = null;
5037
5038            final int libCount = mSharedLibraries.size();
5039            for (int i = 0; i < libCount; i++) {
5040                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5041                if (versionedLib == null) {
5042                    continue;
5043                }
5044
5045                final int versionCount = versionedLib.size();
5046                for (int j = 0; j < versionCount; j++) {
5047                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5048                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5049                        break;
5050                    }
5051                    final long identity = Binder.clearCallingIdentity();
5052                    try {
5053                        PackageInfo packageInfo = getPackageInfoVersioned(
5054                                libInfo.getDeclaringPackage(), flags
5055                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5056                        if (packageInfo == null) {
5057                            continue;
5058                        }
5059                    } finally {
5060                        Binder.restoreCallingIdentity(identity);
5061                    }
5062
5063                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5064                            libInfo.getLongVersion(), libInfo.getType(),
5065                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5066                            flags, userId));
5067
5068                    if (result == null) {
5069                        result = new ArrayList<>();
5070                    }
5071                    result.add(resLibInfo);
5072                }
5073            }
5074
5075            return result != null ? new ParceledListSlice<>(result) : null;
5076        }
5077    }
5078
5079    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5080            SharedLibraryInfo libInfo, int flags, int userId) {
5081        List<VersionedPackage> versionedPackages = null;
5082        final int packageCount = mSettings.mPackages.size();
5083        for (int i = 0; i < packageCount; i++) {
5084            PackageSetting ps = mSettings.mPackages.valueAt(i);
5085
5086            if (ps == null) {
5087                continue;
5088            }
5089
5090            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5091                continue;
5092            }
5093
5094            final String libName = libInfo.getName();
5095            if (libInfo.isStatic()) {
5096                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5097                if (libIdx < 0) {
5098                    continue;
5099                }
5100                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5101                    continue;
5102                }
5103                if (versionedPackages == null) {
5104                    versionedPackages = new ArrayList<>();
5105                }
5106                // If the dependent is a static shared lib, use the public package name
5107                String dependentPackageName = ps.name;
5108                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5109                    dependentPackageName = ps.pkg.manifestPackageName;
5110                }
5111                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5112            } else if (ps.pkg != null) {
5113                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5114                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5115                    if (versionedPackages == null) {
5116                        versionedPackages = new ArrayList<>();
5117                    }
5118                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5119                }
5120            }
5121        }
5122
5123        return versionedPackages;
5124    }
5125
5126    @Override
5127    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5128        if (!sUserManager.exists(userId)) return null;
5129        final int callingUid = Binder.getCallingUid();
5130        flags = updateFlagsForComponent(flags, userId, component);
5131        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5132                false /* requireFullPermission */, false /* checkShell */, "get service info");
5133        synchronized (mPackages) {
5134            PackageParser.Service s = mServices.mServices.get(component);
5135            if (DEBUG_PACKAGE_INFO) Log.v(
5136                TAG, "getServiceInfo " + component + ": " + s);
5137            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5138                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5139                if (ps == null) return null;
5140                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5141                    return null;
5142                }
5143                return PackageParser.generateServiceInfo(
5144                        s, flags, ps.readUserState(userId), userId);
5145            }
5146        }
5147        return null;
5148    }
5149
5150    @Override
5151    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5152        if (!sUserManager.exists(userId)) return null;
5153        final int callingUid = Binder.getCallingUid();
5154        flags = updateFlagsForComponent(flags, userId, component);
5155        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5156                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5157        synchronized (mPackages) {
5158            PackageParser.Provider p = mProviders.mProviders.get(component);
5159            if (DEBUG_PACKAGE_INFO) Log.v(
5160                TAG, "getProviderInfo " + component + ": " + p);
5161            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5162                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5163                if (ps == null) return null;
5164                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5165                    return null;
5166                }
5167                return PackageParser.generateProviderInfo(
5168                        p, flags, ps.readUserState(userId), userId);
5169            }
5170        }
5171        return null;
5172    }
5173
5174    @Override
5175    public String[] getSystemSharedLibraryNames() {
5176        // allow instant applications
5177        synchronized (mPackages) {
5178            Set<String> libs = null;
5179            final int libCount = mSharedLibraries.size();
5180            for (int i = 0; i < libCount; i++) {
5181                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5182                if (versionedLib == null) {
5183                    continue;
5184                }
5185                final int versionCount = versionedLib.size();
5186                for (int j = 0; j < versionCount; j++) {
5187                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5188                    if (!libEntry.info.isStatic()) {
5189                        if (libs == null) {
5190                            libs = new ArraySet<>();
5191                        }
5192                        libs.add(libEntry.info.getName());
5193                        break;
5194                    }
5195                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5196                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5197                            UserHandle.getUserId(Binder.getCallingUid()),
5198                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5199                        if (libs == null) {
5200                            libs = new ArraySet<>();
5201                        }
5202                        libs.add(libEntry.info.getName());
5203                        break;
5204                    }
5205                }
5206            }
5207
5208            if (libs != null) {
5209                String[] libsArray = new String[libs.size()];
5210                libs.toArray(libsArray);
5211                return libsArray;
5212            }
5213
5214            return null;
5215        }
5216    }
5217
5218    @Override
5219    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5220        // allow instant applications
5221        synchronized (mPackages) {
5222            return mServicesSystemSharedLibraryPackageName;
5223        }
5224    }
5225
5226    @Override
5227    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5228        // allow instant applications
5229        synchronized (mPackages) {
5230            return mSharedSystemSharedLibraryPackageName;
5231        }
5232    }
5233
5234    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5235        for (int i = userList.length - 1; i >= 0; --i) {
5236            final int userId = userList[i];
5237            // don't add instant app to the list of updates
5238            if (pkgSetting.getInstantApp(userId)) {
5239                continue;
5240            }
5241            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5242            if (changedPackages == null) {
5243                changedPackages = new SparseArray<>();
5244                mChangedPackages.put(userId, changedPackages);
5245            }
5246            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5247            if (sequenceNumbers == null) {
5248                sequenceNumbers = new HashMap<>();
5249                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5250            }
5251            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5252            if (sequenceNumber != null) {
5253                changedPackages.remove(sequenceNumber);
5254            }
5255            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5256            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5257        }
5258        mChangedPackagesSequenceNumber++;
5259    }
5260
5261    @Override
5262    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5263        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5264            return null;
5265        }
5266        synchronized (mPackages) {
5267            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5268                return null;
5269            }
5270            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5271            if (changedPackages == null) {
5272                return null;
5273            }
5274            final List<String> packageNames =
5275                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5276            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5277                final String packageName = changedPackages.get(i);
5278                if (packageName != null) {
5279                    packageNames.add(packageName);
5280                }
5281            }
5282            return packageNames.isEmpty()
5283                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5284        }
5285    }
5286
5287    @Override
5288    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5289        // allow instant applications
5290        ArrayList<FeatureInfo> res;
5291        synchronized (mAvailableFeatures) {
5292            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5293            res.addAll(mAvailableFeatures.values());
5294        }
5295        final FeatureInfo fi = new FeatureInfo();
5296        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5297                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5298        res.add(fi);
5299
5300        return new ParceledListSlice<>(res);
5301    }
5302
5303    @Override
5304    public boolean hasSystemFeature(String name, int version) {
5305        // allow instant applications
5306        synchronized (mAvailableFeatures) {
5307            final FeatureInfo feat = mAvailableFeatures.get(name);
5308            if (feat == null) {
5309                return false;
5310            } else {
5311                return feat.version >= version;
5312            }
5313        }
5314    }
5315
5316    @Override
5317    public int checkPermission(String permName, String pkgName, int userId) {
5318        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5319    }
5320
5321    @Override
5322    public int checkUidPermission(String permName, int uid) {
5323        synchronized (mPackages) {
5324            final String[] packageNames = getPackagesForUid(uid);
5325            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5326                    ? mPackages.get(packageNames[0])
5327                    : null;
5328            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5329        }
5330    }
5331
5332    @Override
5333    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5334        if (UserHandle.getCallingUserId() != userId) {
5335            mContext.enforceCallingPermission(
5336                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5337                    "isPermissionRevokedByPolicy for user " + userId);
5338        }
5339
5340        if (checkPermission(permission, packageName, userId)
5341                == PackageManager.PERMISSION_GRANTED) {
5342            return false;
5343        }
5344
5345        final int callingUid = Binder.getCallingUid();
5346        if (getInstantAppPackageName(callingUid) != null) {
5347            if (!isCallerSameApp(packageName, callingUid)) {
5348                return false;
5349            }
5350        } else {
5351            if (isInstantApp(packageName, userId)) {
5352                return false;
5353            }
5354        }
5355
5356        final long identity = Binder.clearCallingIdentity();
5357        try {
5358            final int flags = getPermissionFlags(permission, packageName, userId);
5359            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5360        } finally {
5361            Binder.restoreCallingIdentity(identity);
5362        }
5363    }
5364
5365    @Override
5366    public String getPermissionControllerPackageName() {
5367        synchronized (mPackages) {
5368            return mRequiredInstallerPackage;
5369        }
5370    }
5371
5372    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5373        return mPermissionManager.addDynamicPermission(
5374                info, async, getCallingUid(), new PermissionCallback() {
5375                    @Override
5376                    public void onPermissionChanged() {
5377                        if (!async) {
5378                            mSettings.writeLPr();
5379                        } else {
5380                            scheduleWriteSettingsLocked();
5381                        }
5382                    }
5383                });
5384    }
5385
5386    @Override
5387    public boolean addPermission(PermissionInfo info) {
5388        synchronized (mPackages) {
5389            return addDynamicPermission(info, false);
5390        }
5391    }
5392
5393    @Override
5394    public boolean addPermissionAsync(PermissionInfo info) {
5395        synchronized (mPackages) {
5396            return addDynamicPermission(info, true);
5397        }
5398    }
5399
5400    @Override
5401    public void removePermission(String permName) {
5402        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5403    }
5404
5405    @Override
5406    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5407        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5408                getCallingUid(), userId, mPermissionCallback);
5409    }
5410
5411    @Override
5412    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5413        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5414                getCallingUid(), userId, mPermissionCallback);
5415    }
5416
5417    @Override
5418    public void resetRuntimePermissions() {
5419        mContext.enforceCallingOrSelfPermission(
5420                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5421                "revokeRuntimePermission");
5422
5423        int callingUid = Binder.getCallingUid();
5424        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5425            mContext.enforceCallingOrSelfPermission(
5426                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5427                    "resetRuntimePermissions");
5428        }
5429
5430        synchronized (mPackages) {
5431            mPermissionManager.updateAllPermissions(
5432                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5433                    mPermissionCallback);
5434            for (int userId : UserManagerService.getInstance().getUserIds()) {
5435                final int packageCount = mPackages.size();
5436                for (int i = 0; i < packageCount; i++) {
5437                    PackageParser.Package pkg = mPackages.valueAt(i);
5438                    if (!(pkg.mExtras instanceof PackageSetting)) {
5439                        continue;
5440                    }
5441                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5442                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5443                }
5444            }
5445        }
5446    }
5447
5448    @Override
5449    public int getPermissionFlags(String permName, String packageName, int userId) {
5450        return mPermissionManager.getPermissionFlags(
5451                permName, packageName, getCallingUid(), userId);
5452    }
5453
5454    @Override
5455    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5456            int flagValues, int userId) {
5457        mPermissionManager.updatePermissionFlags(
5458                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5459                mPermissionCallback);
5460    }
5461
5462    /**
5463     * Update the permission flags for all packages and runtime permissions of a user in order
5464     * to allow device or profile owner to remove POLICY_FIXED.
5465     */
5466    @Override
5467    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5468        synchronized (mPackages) {
5469            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5470                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5471                    mPermissionCallback);
5472            if (changed) {
5473                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5474            }
5475        }
5476    }
5477
5478    @Override
5479    public boolean shouldShowRequestPermissionRationale(String permissionName,
5480            String packageName, int userId) {
5481        if (UserHandle.getCallingUserId() != userId) {
5482            mContext.enforceCallingPermission(
5483                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5484                    "canShowRequestPermissionRationale for user " + userId);
5485        }
5486
5487        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5488        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5489            return false;
5490        }
5491
5492        if (checkPermission(permissionName, packageName, userId)
5493                == PackageManager.PERMISSION_GRANTED) {
5494            return false;
5495        }
5496
5497        final int flags;
5498
5499        final long identity = Binder.clearCallingIdentity();
5500        try {
5501            flags = getPermissionFlags(permissionName,
5502                    packageName, userId);
5503        } finally {
5504            Binder.restoreCallingIdentity(identity);
5505        }
5506
5507        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5508                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5509                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5510
5511        if ((flags & fixedFlags) != 0) {
5512            return false;
5513        }
5514
5515        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5516    }
5517
5518    @Override
5519    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5520        mContext.enforceCallingOrSelfPermission(
5521                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5522                "addOnPermissionsChangeListener");
5523
5524        synchronized (mPackages) {
5525            mOnPermissionChangeListeners.addListenerLocked(listener);
5526        }
5527    }
5528
5529    @Override
5530    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5531        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5532            throw new SecurityException("Instant applications don't have access to this method");
5533        }
5534        synchronized (mPackages) {
5535            mOnPermissionChangeListeners.removeListenerLocked(listener);
5536        }
5537    }
5538
5539    @Override
5540    public boolean isProtectedBroadcast(String actionName) {
5541        // allow instant applications
5542        synchronized (mProtectedBroadcasts) {
5543            if (mProtectedBroadcasts.contains(actionName)) {
5544                return true;
5545            } else if (actionName != null) {
5546                // TODO: remove these terrible hacks
5547                if (actionName.startsWith("android.net.netmon.lingerExpired")
5548                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5549                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5550                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5551                    return true;
5552                }
5553            }
5554        }
5555        return false;
5556    }
5557
5558    @Override
5559    public int checkSignatures(String pkg1, String pkg2) {
5560        synchronized (mPackages) {
5561            final PackageParser.Package p1 = mPackages.get(pkg1);
5562            final PackageParser.Package p2 = mPackages.get(pkg2);
5563            if (p1 == null || p1.mExtras == null
5564                    || p2 == null || p2.mExtras == null) {
5565                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5566            }
5567            final int callingUid = Binder.getCallingUid();
5568            final int callingUserId = UserHandle.getUserId(callingUid);
5569            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5570            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5571            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5572                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5573                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5574            }
5575            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5576        }
5577    }
5578
5579    @Override
5580    public int checkUidSignatures(int uid1, int uid2) {
5581        final int callingUid = Binder.getCallingUid();
5582        final int callingUserId = UserHandle.getUserId(callingUid);
5583        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5584        // Map to base uids.
5585        uid1 = UserHandle.getAppId(uid1);
5586        uid2 = UserHandle.getAppId(uid2);
5587        // reader
5588        synchronized (mPackages) {
5589            Signature[] s1;
5590            Signature[] s2;
5591            Object obj = mSettings.getUserIdLPr(uid1);
5592            if (obj != null) {
5593                if (obj instanceof SharedUserSetting) {
5594                    if (isCallerInstantApp) {
5595                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5596                    }
5597                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5598                } else if (obj instanceof PackageSetting) {
5599                    final PackageSetting ps = (PackageSetting) obj;
5600                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5601                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5602                    }
5603                    s1 = ps.signatures.mSigningDetails.signatures;
5604                } else {
5605                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5606                }
5607            } else {
5608                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5609            }
5610            obj = mSettings.getUserIdLPr(uid2);
5611            if (obj != null) {
5612                if (obj instanceof SharedUserSetting) {
5613                    if (isCallerInstantApp) {
5614                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5615                    }
5616                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5617                } else if (obj instanceof PackageSetting) {
5618                    final PackageSetting ps = (PackageSetting) obj;
5619                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5620                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5621                    }
5622                    s2 = ps.signatures.mSigningDetails.signatures;
5623                } else {
5624                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5625                }
5626            } else {
5627                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5628            }
5629            return compareSignatures(s1, s2);
5630        }
5631    }
5632
5633    @Override
5634    public boolean hasSigningCertificate(
5635            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5636
5637        synchronized (mPackages) {
5638            final PackageParser.Package p = mPackages.get(packageName);
5639            if (p == null || p.mExtras == null) {
5640                return false;
5641            }
5642            final int callingUid = Binder.getCallingUid();
5643            final int callingUserId = UserHandle.getUserId(callingUid);
5644            final PackageSetting ps = (PackageSetting) p.mExtras;
5645            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5646                return false;
5647            }
5648            switch (type) {
5649                case CERT_INPUT_RAW_X509:
5650                    return p.mSigningDetails.hasCertificate(certificate);
5651                case CERT_INPUT_SHA256:
5652                    return p.mSigningDetails.hasSha256Certificate(certificate);
5653                default:
5654                    return false;
5655            }
5656        }
5657    }
5658
5659    @Override
5660    public boolean hasUidSigningCertificate(
5661            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5662        final int callingUid = Binder.getCallingUid();
5663        final int callingUserId = UserHandle.getUserId(callingUid);
5664        // Map to base uids.
5665        uid = UserHandle.getAppId(uid);
5666        // reader
5667        synchronized (mPackages) {
5668            final PackageParser.SigningDetails signingDetails;
5669            final Object obj = mSettings.getUserIdLPr(uid);
5670            if (obj != null) {
5671                if (obj instanceof SharedUserSetting) {
5672                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5673                    if (isCallerInstantApp) {
5674                        return false;
5675                    }
5676                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5677                } else if (obj instanceof PackageSetting) {
5678                    final PackageSetting ps = (PackageSetting) obj;
5679                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5680                        return false;
5681                    }
5682                    signingDetails = ps.signatures.mSigningDetails;
5683                } else {
5684                    return false;
5685                }
5686            } else {
5687                return false;
5688            }
5689            switch (type) {
5690                case CERT_INPUT_RAW_X509:
5691                    return signingDetails.hasCertificate(certificate);
5692                case CERT_INPUT_SHA256:
5693                    return signingDetails.hasSha256Certificate(certificate);
5694                default:
5695                    return false;
5696            }
5697        }
5698    }
5699
5700    /**
5701     * This method should typically only be used when granting or revoking
5702     * permissions, since the app may immediately restart after this call.
5703     * <p>
5704     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5705     * guard your work against the app being relaunched.
5706     */
5707    private void killUid(int appId, int userId, String reason) {
5708        final long identity = Binder.clearCallingIdentity();
5709        try {
5710            IActivityManager am = ActivityManager.getService();
5711            if (am != null) {
5712                try {
5713                    am.killUid(appId, userId, reason);
5714                } catch (RemoteException e) {
5715                    /* ignore - same process */
5716                }
5717            }
5718        } finally {
5719            Binder.restoreCallingIdentity(identity);
5720        }
5721    }
5722
5723    /**
5724     * If the database version for this type of package (internal storage or
5725     * external storage) is less than the version where package signatures
5726     * were updated, return true.
5727     */
5728    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5729        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5730        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5731    }
5732
5733    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5734        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5735        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5736    }
5737
5738    @Override
5739    public List<String> getAllPackages() {
5740        final int callingUid = Binder.getCallingUid();
5741        final int callingUserId = UserHandle.getUserId(callingUid);
5742        synchronized (mPackages) {
5743            if (canViewInstantApps(callingUid, callingUserId)) {
5744                return new ArrayList<String>(mPackages.keySet());
5745            }
5746            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5747            final List<String> result = new ArrayList<>();
5748            if (instantAppPkgName != null) {
5749                // caller is an instant application; filter unexposed applications
5750                for (PackageParser.Package pkg : mPackages.values()) {
5751                    if (!pkg.visibleToInstantApps) {
5752                        continue;
5753                    }
5754                    result.add(pkg.packageName);
5755                }
5756            } else {
5757                // caller is a normal application; filter instant applications
5758                for (PackageParser.Package pkg : mPackages.values()) {
5759                    final PackageSetting ps =
5760                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5761                    if (ps != null
5762                            && ps.getInstantApp(callingUserId)
5763                            && !mInstantAppRegistry.isInstantAccessGranted(
5764                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5765                        continue;
5766                    }
5767                    result.add(pkg.packageName);
5768                }
5769            }
5770            return result;
5771        }
5772    }
5773
5774    @Override
5775    public String[] getPackagesForUid(int uid) {
5776        final int callingUid = Binder.getCallingUid();
5777        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5778        final int userId = UserHandle.getUserId(uid);
5779        uid = UserHandle.getAppId(uid);
5780        // reader
5781        synchronized (mPackages) {
5782            Object obj = mSettings.getUserIdLPr(uid);
5783            if (obj instanceof SharedUserSetting) {
5784                if (isCallerInstantApp) {
5785                    return null;
5786                }
5787                final SharedUserSetting sus = (SharedUserSetting) obj;
5788                final int N = sus.packages.size();
5789                String[] res = new String[N];
5790                final Iterator<PackageSetting> it = sus.packages.iterator();
5791                int i = 0;
5792                while (it.hasNext()) {
5793                    PackageSetting ps = it.next();
5794                    if (ps.getInstalled(userId)) {
5795                        res[i++] = ps.name;
5796                    } else {
5797                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5798                    }
5799                }
5800                return res;
5801            } else if (obj instanceof PackageSetting) {
5802                final PackageSetting ps = (PackageSetting) obj;
5803                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5804                    return new String[]{ps.name};
5805                }
5806            }
5807        }
5808        return null;
5809    }
5810
5811    @Override
5812    public String getNameForUid(int uid) {
5813        final int callingUid = Binder.getCallingUid();
5814        if (getInstantAppPackageName(callingUid) != null) {
5815            return null;
5816        }
5817        synchronized (mPackages) {
5818            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5819            if (obj instanceof SharedUserSetting) {
5820                final SharedUserSetting sus = (SharedUserSetting) obj;
5821                return sus.name + ":" + sus.userId;
5822            } else if (obj instanceof PackageSetting) {
5823                final PackageSetting ps = (PackageSetting) obj;
5824                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5825                    return null;
5826                }
5827                return ps.name;
5828            }
5829            return null;
5830        }
5831    }
5832
5833    @Override
5834    public String[] getNamesForUids(int[] uids) {
5835        if (uids == null || uids.length == 0) {
5836            return null;
5837        }
5838        final int callingUid = Binder.getCallingUid();
5839        if (getInstantAppPackageName(callingUid) != null) {
5840            return null;
5841        }
5842        final String[] names = new String[uids.length];
5843        synchronized (mPackages) {
5844            for (int i = uids.length - 1; i >= 0; i--) {
5845                final int uid = uids[i];
5846                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5847                if (obj instanceof SharedUserSetting) {
5848                    final SharedUserSetting sus = (SharedUserSetting) obj;
5849                    names[i] = "shared:" + sus.name;
5850                } else if (obj instanceof PackageSetting) {
5851                    final PackageSetting ps = (PackageSetting) obj;
5852                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5853                        names[i] = null;
5854                    } else {
5855                        names[i] = ps.name;
5856                    }
5857                } else {
5858                    names[i] = null;
5859                }
5860            }
5861        }
5862        return names;
5863    }
5864
5865    @Override
5866    public int getUidForSharedUser(String sharedUserName) {
5867        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5868            return -1;
5869        }
5870        if (sharedUserName == null) {
5871            return -1;
5872        }
5873        // reader
5874        synchronized (mPackages) {
5875            SharedUserSetting suid;
5876            try {
5877                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5878                if (suid != null) {
5879                    return suid.userId;
5880                }
5881            } catch (PackageManagerException ignore) {
5882                // can't happen, but, still need to catch it
5883            }
5884            return -1;
5885        }
5886    }
5887
5888    @Override
5889    public int getFlagsForUid(int uid) {
5890        final int callingUid = Binder.getCallingUid();
5891        if (getInstantAppPackageName(callingUid) != null) {
5892            return 0;
5893        }
5894        synchronized (mPackages) {
5895            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5896            if (obj instanceof SharedUserSetting) {
5897                final SharedUserSetting sus = (SharedUserSetting) obj;
5898                return sus.pkgFlags;
5899            } else if (obj instanceof PackageSetting) {
5900                final PackageSetting ps = (PackageSetting) obj;
5901                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5902                    return 0;
5903                }
5904                return ps.pkgFlags;
5905            }
5906        }
5907        return 0;
5908    }
5909
5910    @Override
5911    public int getPrivateFlagsForUid(int uid) {
5912        final int callingUid = Binder.getCallingUid();
5913        if (getInstantAppPackageName(callingUid) != null) {
5914            return 0;
5915        }
5916        synchronized (mPackages) {
5917            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5918            if (obj instanceof SharedUserSetting) {
5919                final SharedUserSetting sus = (SharedUserSetting) obj;
5920                return sus.pkgPrivateFlags;
5921            } else if (obj instanceof PackageSetting) {
5922                final PackageSetting ps = (PackageSetting) obj;
5923                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5924                    return 0;
5925                }
5926                return ps.pkgPrivateFlags;
5927            }
5928        }
5929        return 0;
5930    }
5931
5932    @Override
5933    public boolean isUidPrivileged(int uid) {
5934        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5935            return false;
5936        }
5937        uid = UserHandle.getAppId(uid);
5938        // reader
5939        synchronized (mPackages) {
5940            Object obj = mSettings.getUserIdLPr(uid);
5941            if (obj instanceof SharedUserSetting) {
5942                final SharedUserSetting sus = (SharedUserSetting) obj;
5943                final Iterator<PackageSetting> it = sus.packages.iterator();
5944                while (it.hasNext()) {
5945                    if (it.next().isPrivileged()) {
5946                        return true;
5947                    }
5948                }
5949            } else if (obj instanceof PackageSetting) {
5950                final PackageSetting ps = (PackageSetting) obj;
5951                return ps.isPrivileged();
5952            }
5953        }
5954        return false;
5955    }
5956
5957    @Override
5958    public String[] getAppOpPermissionPackages(String permName) {
5959        return mPermissionManager.getAppOpPermissionPackages(permName);
5960    }
5961
5962    @Override
5963    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5964            int flags, int userId) {
5965        return resolveIntentInternal(intent, resolvedType, flags, userId, false,
5966                Binder.getCallingUid());
5967    }
5968
5969    /**
5970     * Normally instant apps can only be resolved when they're visible to the caller.
5971     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5972     * since we need to allow the system to start any installed application.
5973     */
5974    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5975            int flags, int userId, boolean resolveForStart, int filterCallingUid) {
5976        try {
5977            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5978
5979            if (!sUserManager.exists(userId)) return null;
5980            final int callingUid = Binder.getCallingUid();
5981            flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
5982            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5983                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5984
5985            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5986            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5987                    flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5988            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5989
5990            final ResolveInfo bestChoice =
5991                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5992            return bestChoice;
5993        } finally {
5994            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5995        }
5996    }
5997
5998    @Override
5999    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6000        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6001            throw new SecurityException(
6002                    "findPersistentPreferredActivity can only be run by the system");
6003        }
6004        if (!sUserManager.exists(userId)) {
6005            return null;
6006        }
6007        final int callingUid = Binder.getCallingUid();
6008        intent = updateIntentForResolve(intent);
6009        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6010        final int flags = updateFlagsForResolve(
6011                0, userId, intent, callingUid, false /*includeInstantApps*/);
6012        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6013                userId);
6014        synchronized (mPackages) {
6015            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6016                    userId);
6017        }
6018    }
6019
6020    @Override
6021    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6022            IntentFilter filter, int match, ComponentName activity) {
6023        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6024            return;
6025        }
6026        final int userId = UserHandle.getCallingUserId();
6027        if (DEBUG_PREFERRED) {
6028            Log.v(TAG, "setLastChosenActivity intent=" + intent
6029                + " resolvedType=" + resolvedType
6030                + " flags=" + flags
6031                + " filter=" + filter
6032                + " match=" + match
6033                + " activity=" + activity);
6034            filter.dump(new PrintStreamPrinter(System.out), "    ");
6035        }
6036        intent.setComponent(null);
6037        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6038                userId);
6039        // Find any earlier preferred or last chosen entries and nuke them
6040        findPreferredActivity(intent, resolvedType,
6041                flags, query, 0, false, true, false, userId);
6042        // Add the new activity as the last chosen for this filter
6043        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6044                "Setting last chosen");
6045    }
6046
6047    @Override
6048    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6049        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6050            return null;
6051        }
6052        final int userId = UserHandle.getCallingUserId();
6053        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6054        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6055                userId);
6056        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6057                false, false, false, userId);
6058    }
6059
6060    /**
6061     * Returns whether or not instant apps have been disabled remotely.
6062     */
6063    private boolean areWebInstantAppsDisabled() {
6064        return mWebInstantAppsDisabled;
6065    }
6066
6067    private boolean isInstantAppResolutionAllowed(
6068            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6069            boolean skipPackageCheck) {
6070        if (mInstantAppResolverConnection == null) {
6071            return false;
6072        }
6073        if (mInstantAppInstallerActivity == null) {
6074            return false;
6075        }
6076        if (intent.getComponent() != null) {
6077            return false;
6078        }
6079        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6080            return false;
6081        }
6082        if (!skipPackageCheck && intent.getPackage() != null) {
6083            return false;
6084        }
6085        if (!intent.isWebIntent()) {
6086            // for non web intents, we should not resolve externally if an app already exists to
6087            // handle it or if the caller didn't explicitly request it.
6088            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6089                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6090                return false;
6091            }
6092        } else {
6093            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6094                return false;
6095            } else if (areWebInstantAppsDisabled()) {
6096                return false;
6097            }
6098        }
6099        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6100        // Or if there's already an ephemeral app installed that handles the action
6101        synchronized (mPackages) {
6102            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6103            for (int n = 0; n < count; n++) {
6104                final ResolveInfo info = resolvedActivities.get(n);
6105                final String packageName = info.activityInfo.packageName;
6106                final PackageSetting ps = mSettings.mPackages.get(packageName);
6107                if (ps != null) {
6108                    // only check domain verification status if the app is not a browser
6109                    if (!info.handleAllWebDataURI) {
6110                        // Try to get the status from User settings first
6111                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6112                        final int status = (int) (packedStatus >> 32);
6113                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6114                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6115                            if (DEBUG_INSTANT) {
6116                                Slog.v(TAG, "DENY instant app;"
6117                                    + " pkg: " + packageName + ", status: " + status);
6118                            }
6119                            return false;
6120                        }
6121                    }
6122                    if (ps.getInstantApp(userId)) {
6123                        if (DEBUG_INSTANT) {
6124                            Slog.v(TAG, "DENY instant app installed;"
6125                                    + " pkg: " + packageName);
6126                        }
6127                        return false;
6128                    }
6129                }
6130            }
6131        }
6132        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6133        return true;
6134    }
6135
6136    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6137            Intent origIntent, String resolvedType, String callingPackage,
6138            Bundle verificationBundle, int userId) {
6139        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6140                new InstantAppRequest(responseObj, origIntent, resolvedType,
6141                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6142        mHandler.sendMessage(msg);
6143    }
6144
6145    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6146            int flags, List<ResolveInfo> query, int userId) {
6147        if (query != null) {
6148            final int N = query.size();
6149            if (N == 1) {
6150                return query.get(0);
6151            } else if (N > 1) {
6152                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6153                // If there is more than one activity with the same priority,
6154                // then let the user decide between them.
6155                ResolveInfo r0 = query.get(0);
6156                ResolveInfo r1 = query.get(1);
6157                if (DEBUG_INTENT_MATCHING || debug) {
6158                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6159                            + r1.activityInfo.name + "=" + r1.priority);
6160                }
6161                // If the first activity has a higher priority, or a different
6162                // default, then it is always desirable to pick it.
6163                if (r0.priority != r1.priority
6164                        || r0.preferredOrder != r1.preferredOrder
6165                        || r0.isDefault != r1.isDefault) {
6166                    return query.get(0);
6167                }
6168                // If we have saved a preference for a preferred activity for
6169                // this Intent, use that.
6170                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6171                        flags, query, r0.priority, true, false, debug, userId);
6172                if (ri != null) {
6173                    return ri;
6174                }
6175                // If we have an ephemeral app, use it
6176                for (int i = 0; i < N; i++) {
6177                    ri = query.get(i);
6178                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6179                        final String packageName = ri.activityInfo.packageName;
6180                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6181                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6182                        final int status = (int)(packedStatus >> 32);
6183                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6184                            return ri;
6185                        }
6186                    }
6187                }
6188                ri = new ResolveInfo(mResolveInfo);
6189                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6190                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6191                // If all of the options come from the same package, show the application's
6192                // label and icon instead of the generic resolver's.
6193                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6194                // and then throw away the ResolveInfo itself, meaning that the caller loses
6195                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6196                // a fallback for this case; we only set the target package's resources on
6197                // the ResolveInfo, not the ActivityInfo.
6198                final String intentPackage = intent.getPackage();
6199                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6200                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6201                    ri.resolvePackageName = intentPackage;
6202                    if (userNeedsBadging(userId)) {
6203                        ri.noResourceId = true;
6204                    } else {
6205                        ri.icon = appi.icon;
6206                    }
6207                    ri.iconResourceId = appi.icon;
6208                    ri.labelRes = appi.labelRes;
6209                }
6210                ri.activityInfo.applicationInfo = new ApplicationInfo(
6211                        ri.activityInfo.applicationInfo);
6212                if (userId != 0) {
6213                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6214                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6215                }
6216                // Make sure that the resolver is displayable in car mode
6217                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6218                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6219                return ri;
6220            }
6221        }
6222        return null;
6223    }
6224
6225    /**
6226     * Return true if the given list is not empty and all of its contents have
6227     * an activityInfo with the given package name.
6228     */
6229    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6230        if (ArrayUtils.isEmpty(list)) {
6231            return false;
6232        }
6233        for (int i = 0, N = list.size(); i < N; i++) {
6234            final ResolveInfo ri = list.get(i);
6235            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6236            if (ai == null || !packageName.equals(ai.packageName)) {
6237                return false;
6238            }
6239        }
6240        return true;
6241    }
6242
6243    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6244            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6245        final int N = query.size();
6246        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6247                .get(userId);
6248        // Get the list of persistent preferred activities that handle the intent
6249        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6250        List<PersistentPreferredActivity> pprefs = ppir != null
6251                ? ppir.queryIntent(intent, resolvedType,
6252                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6253                        userId)
6254                : null;
6255        if (pprefs != null && pprefs.size() > 0) {
6256            final int M = pprefs.size();
6257            for (int i=0; i<M; i++) {
6258                final PersistentPreferredActivity ppa = pprefs.get(i);
6259                if (DEBUG_PREFERRED || debug) {
6260                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6261                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6262                            + "\n  component=" + ppa.mComponent);
6263                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6264                }
6265                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6266                        flags | MATCH_DISABLED_COMPONENTS, userId);
6267                if (DEBUG_PREFERRED || debug) {
6268                    Slog.v(TAG, "Found persistent preferred activity:");
6269                    if (ai != null) {
6270                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6271                    } else {
6272                        Slog.v(TAG, "  null");
6273                    }
6274                }
6275                if (ai == null) {
6276                    // This previously registered persistent preferred activity
6277                    // component is no longer known. Ignore it and do NOT remove it.
6278                    continue;
6279                }
6280                for (int j=0; j<N; j++) {
6281                    final ResolveInfo ri = query.get(j);
6282                    if (!ri.activityInfo.applicationInfo.packageName
6283                            .equals(ai.applicationInfo.packageName)) {
6284                        continue;
6285                    }
6286                    if (!ri.activityInfo.name.equals(ai.name)) {
6287                        continue;
6288                    }
6289                    //  Found a persistent preference that can handle the intent.
6290                    if (DEBUG_PREFERRED || debug) {
6291                        Slog.v(TAG, "Returning persistent preferred activity: " +
6292                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6293                    }
6294                    return ri;
6295                }
6296            }
6297        }
6298        return null;
6299    }
6300
6301    // TODO: handle preferred activities missing while user has amnesia
6302    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6303            List<ResolveInfo> query, int priority, boolean always,
6304            boolean removeMatches, boolean debug, int userId) {
6305        if (!sUserManager.exists(userId)) return null;
6306        final int callingUid = Binder.getCallingUid();
6307        flags = updateFlagsForResolve(
6308                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6309        intent = updateIntentForResolve(intent);
6310        // writer
6311        synchronized (mPackages) {
6312            // Try to find a matching persistent preferred activity.
6313            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6314                    debug, userId);
6315
6316            // If a persistent preferred activity matched, use it.
6317            if (pri != null) {
6318                return pri;
6319            }
6320
6321            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6322            // Get the list of preferred activities that handle the intent
6323            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6324            List<PreferredActivity> prefs = pir != null
6325                    ? pir.queryIntent(intent, resolvedType,
6326                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6327                            userId)
6328                    : null;
6329            if (prefs != null && prefs.size() > 0) {
6330                boolean changed = false;
6331                try {
6332                    // First figure out how good the original match set is.
6333                    // We will only allow preferred activities that came
6334                    // from the same match quality.
6335                    int match = 0;
6336
6337                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6338
6339                    final int N = query.size();
6340                    for (int j=0; j<N; j++) {
6341                        final ResolveInfo ri = query.get(j);
6342                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6343                                + ": 0x" + Integer.toHexString(match));
6344                        if (ri.match > match) {
6345                            match = ri.match;
6346                        }
6347                    }
6348
6349                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6350                            + Integer.toHexString(match));
6351
6352                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6353                    final int M = prefs.size();
6354                    for (int i=0; i<M; i++) {
6355                        final PreferredActivity pa = prefs.get(i);
6356                        if (DEBUG_PREFERRED || debug) {
6357                            Slog.v(TAG, "Checking PreferredActivity ds="
6358                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6359                                    + "\n  component=" + pa.mPref.mComponent);
6360                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6361                        }
6362                        if (pa.mPref.mMatch != match) {
6363                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6364                                    + Integer.toHexString(pa.mPref.mMatch));
6365                            continue;
6366                        }
6367                        // If it's not an "always" type preferred activity and that's what we're
6368                        // looking for, skip it.
6369                        if (always && !pa.mPref.mAlways) {
6370                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6371                            continue;
6372                        }
6373                        final ActivityInfo ai = getActivityInfo(
6374                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6375                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6376                                userId);
6377                        if (DEBUG_PREFERRED || debug) {
6378                            Slog.v(TAG, "Found preferred activity:");
6379                            if (ai != null) {
6380                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6381                            } else {
6382                                Slog.v(TAG, "  null");
6383                            }
6384                        }
6385                        if (ai == null) {
6386                            // This previously registered preferred activity
6387                            // component is no longer known.  Most likely an update
6388                            // to the app was installed and in the new version this
6389                            // component no longer exists.  Clean it up by removing
6390                            // it from the preferred activities list, and skip it.
6391                            Slog.w(TAG, "Removing dangling preferred activity: "
6392                                    + pa.mPref.mComponent);
6393                            pir.removeFilter(pa);
6394                            changed = true;
6395                            continue;
6396                        }
6397                        for (int j=0; j<N; j++) {
6398                            final ResolveInfo ri = query.get(j);
6399                            if (!ri.activityInfo.applicationInfo.packageName
6400                                    .equals(ai.applicationInfo.packageName)) {
6401                                continue;
6402                            }
6403                            if (!ri.activityInfo.name.equals(ai.name)) {
6404                                continue;
6405                            }
6406
6407                            if (removeMatches) {
6408                                pir.removeFilter(pa);
6409                                changed = true;
6410                                if (DEBUG_PREFERRED) {
6411                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6412                                }
6413                                break;
6414                            }
6415
6416                            // Okay we found a previously set preferred or last chosen app.
6417                            // If the result set is different from when this
6418                            // was created, and is not a subset of the preferred set, we need to
6419                            // clear it and re-ask the user their preference, if we're looking for
6420                            // an "always" type entry.
6421                            if (always && !pa.mPref.sameSet(query)) {
6422                                if (pa.mPref.isSuperset(query)) {
6423                                    // some components of the set are no longer present in
6424                                    // the query, but the preferred activity can still be reused
6425                                    if (DEBUG_PREFERRED) {
6426                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6427                                                + " still valid as only non-preferred components"
6428                                                + " were removed for " + intent + " type "
6429                                                + resolvedType);
6430                                    }
6431                                    // remove obsolete components and re-add the up-to-date filter
6432                                    PreferredActivity freshPa = new PreferredActivity(pa,
6433                                            pa.mPref.mMatch,
6434                                            pa.mPref.discardObsoleteComponents(query),
6435                                            pa.mPref.mComponent,
6436                                            pa.mPref.mAlways);
6437                                    pir.removeFilter(pa);
6438                                    pir.addFilter(freshPa);
6439                                    changed = true;
6440                                } else {
6441                                    Slog.i(TAG,
6442                                            "Result set changed, dropping preferred activity for "
6443                                                    + intent + " type " + resolvedType);
6444                                    if (DEBUG_PREFERRED) {
6445                                        Slog.v(TAG, "Removing preferred activity since set changed "
6446                                                + pa.mPref.mComponent);
6447                                    }
6448                                    pir.removeFilter(pa);
6449                                    // Re-add the filter as a "last chosen" entry (!always)
6450                                    PreferredActivity lastChosen = new PreferredActivity(
6451                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6452                                    pir.addFilter(lastChosen);
6453                                    changed = true;
6454                                    return null;
6455                                }
6456                            }
6457
6458                            // Yay! Either the set matched or we're looking for the last chosen
6459                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6460                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6461                            return ri;
6462                        }
6463                    }
6464                } finally {
6465                    if (changed) {
6466                        if (DEBUG_PREFERRED) {
6467                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6468                        }
6469                        scheduleWritePackageRestrictionsLocked(userId);
6470                    }
6471                }
6472            }
6473        }
6474        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6475        return null;
6476    }
6477
6478    /*
6479     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6480     */
6481    @Override
6482    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6483            int targetUserId) {
6484        mContext.enforceCallingOrSelfPermission(
6485                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6486        List<CrossProfileIntentFilter> matches =
6487                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6488        if (matches != null) {
6489            int size = matches.size();
6490            for (int i = 0; i < size; i++) {
6491                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6492            }
6493        }
6494        if (intent.hasWebURI()) {
6495            // cross-profile app linking works only towards the parent.
6496            final int callingUid = Binder.getCallingUid();
6497            final UserInfo parent = getProfileParent(sourceUserId);
6498            synchronized(mPackages) {
6499                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6500                        false /*includeInstantApps*/);
6501                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6502                        intent, resolvedType, flags, sourceUserId, parent.id);
6503                return xpDomainInfo != null;
6504            }
6505        }
6506        return false;
6507    }
6508
6509    private UserInfo getProfileParent(int userId) {
6510        final long identity = Binder.clearCallingIdentity();
6511        try {
6512            return sUserManager.getProfileParent(userId);
6513        } finally {
6514            Binder.restoreCallingIdentity(identity);
6515        }
6516    }
6517
6518    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6519            String resolvedType, int userId) {
6520        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6521        if (resolver != null) {
6522            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6523        }
6524        return null;
6525    }
6526
6527    @Override
6528    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6529            String resolvedType, int flags, int userId) {
6530        try {
6531            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6532
6533            return new ParceledListSlice<>(
6534                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6535        } finally {
6536            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6537        }
6538    }
6539
6540    /**
6541     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6542     * instant, returns {@code null}.
6543     */
6544    private String getInstantAppPackageName(int callingUid) {
6545        synchronized (mPackages) {
6546            // If the caller is an isolated app use the owner's uid for the lookup.
6547            if (Process.isIsolated(callingUid)) {
6548                callingUid = mIsolatedOwners.get(callingUid);
6549            }
6550            final int appId = UserHandle.getAppId(callingUid);
6551            final Object obj = mSettings.getUserIdLPr(appId);
6552            if (obj instanceof PackageSetting) {
6553                final PackageSetting ps = (PackageSetting) obj;
6554                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6555                return isInstantApp ? ps.pkg.packageName : null;
6556            }
6557        }
6558        return null;
6559    }
6560
6561    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6562            String resolvedType, int flags, int userId) {
6563        return queryIntentActivitiesInternal(
6564                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6565                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6566    }
6567
6568    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6569            String resolvedType, int flags, int filterCallingUid, int userId,
6570            boolean resolveForStart, boolean allowDynamicSplits) {
6571        if (!sUserManager.exists(userId)) return Collections.emptyList();
6572        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6573        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6574                false /* requireFullPermission */, false /* checkShell */,
6575                "query intent activities");
6576        final String pkgName = intent.getPackage();
6577        ComponentName comp = intent.getComponent();
6578        if (comp == null) {
6579            if (intent.getSelector() != null) {
6580                intent = intent.getSelector();
6581                comp = intent.getComponent();
6582            }
6583        }
6584
6585        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6586                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6587        if (comp != null) {
6588            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6589            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6590            if (ai != null) {
6591                // When specifying an explicit component, we prevent the activity from being
6592                // used when either 1) the calling package is normal and the activity is within
6593                // an ephemeral application or 2) the calling package is ephemeral and the
6594                // activity is not visible to ephemeral applications.
6595                final boolean matchInstantApp =
6596                        (flags & PackageManager.MATCH_INSTANT) != 0;
6597                final boolean matchVisibleToInstantAppOnly =
6598                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6599                final boolean matchExplicitlyVisibleOnly =
6600                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6601                final boolean isCallerInstantApp =
6602                        instantAppPkgName != null;
6603                final boolean isTargetSameInstantApp =
6604                        comp.getPackageName().equals(instantAppPkgName);
6605                final boolean isTargetInstantApp =
6606                        (ai.applicationInfo.privateFlags
6607                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6608                final boolean isTargetVisibleToInstantApp =
6609                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6610                final boolean isTargetExplicitlyVisibleToInstantApp =
6611                        isTargetVisibleToInstantApp
6612                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6613                final boolean isTargetHiddenFromInstantApp =
6614                        !isTargetVisibleToInstantApp
6615                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6616                final boolean blockResolution =
6617                        !isTargetSameInstantApp
6618                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6619                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6620                                        && isTargetHiddenFromInstantApp));
6621                if (!blockResolution) {
6622                    final ResolveInfo ri = new ResolveInfo();
6623                    ri.activityInfo = ai;
6624                    list.add(ri);
6625                }
6626            }
6627            return applyPostResolutionFilter(
6628                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6629        }
6630
6631        // reader
6632        boolean sortResult = false;
6633        boolean addInstant = false;
6634        List<ResolveInfo> result;
6635        synchronized (mPackages) {
6636            if (pkgName == null) {
6637                List<CrossProfileIntentFilter> matchingFilters =
6638                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6639                // Check for results that need to skip the current profile.
6640                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6641                        resolvedType, flags, userId);
6642                if (xpResolveInfo != null) {
6643                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6644                    xpResult.add(xpResolveInfo);
6645                    return applyPostResolutionFilter(
6646                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6647                            allowDynamicSplits, filterCallingUid, userId, intent);
6648                }
6649
6650                // Check for results in the current profile.
6651                result = filterIfNotSystemUser(mActivities.queryIntent(
6652                        intent, resolvedType, flags, userId), userId);
6653                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6654                        false /*skipPackageCheck*/);
6655                // Check for cross profile results.
6656                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6657                xpResolveInfo = queryCrossProfileIntents(
6658                        matchingFilters, intent, resolvedType, flags, userId,
6659                        hasNonNegativePriorityResult);
6660                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6661                    boolean isVisibleToUser = filterIfNotSystemUser(
6662                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6663                    if (isVisibleToUser) {
6664                        result.add(xpResolveInfo);
6665                        sortResult = true;
6666                    }
6667                }
6668                if (intent.hasWebURI()) {
6669                    CrossProfileDomainInfo xpDomainInfo = null;
6670                    final UserInfo parent = getProfileParent(userId);
6671                    if (parent != null) {
6672                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6673                                flags, userId, parent.id);
6674                    }
6675                    if (xpDomainInfo != null) {
6676                        if (xpResolveInfo != null) {
6677                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6678                            // in the result.
6679                            result.remove(xpResolveInfo);
6680                        }
6681                        if (result.size() == 0 && !addInstant) {
6682                            // No result in current profile, but found candidate in parent user.
6683                            // And we are not going to add emphemeral app, so we can return the
6684                            // result straight away.
6685                            result.add(xpDomainInfo.resolveInfo);
6686                            return applyPostResolutionFilter(result, instantAppPkgName,
6687                                    allowDynamicSplits, filterCallingUid, userId, intent);
6688                        }
6689                    } else if (result.size() <= 1 && !addInstant) {
6690                        // No result in parent user and <= 1 result in current profile, and we
6691                        // are not going to add emphemeral app, so we can return the result without
6692                        // further processing.
6693                        return applyPostResolutionFilter(result, instantAppPkgName,
6694                                allowDynamicSplits, filterCallingUid, userId, intent);
6695                    }
6696                    // We have more than one candidate (combining results from current and parent
6697                    // profile), so we need filtering and sorting.
6698                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6699                            intent, flags, result, xpDomainInfo, userId);
6700                    sortResult = true;
6701                }
6702            } else {
6703                final PackageParser.Package pkg = mPackages.get(pkgName);
6704                result = null;
6705                if (pkg != null) {
6706                    result = filterIfNotSystemUser(
6707                            mActivities.queryIntentForPackage(
6708                                    intent, resolvedType, flags, pkg.activities, userId),
6709                            userId);
6710                }
6711                if (result == null || result.size() == 0) {
6712                    // the caller wants to resolve for a particular package; however, there
6713                    // were no installed results, so, try to find an ephemeral result
6714                    addInstant = isInstantAppResolutionAllowed(
6715                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6716                    if (result == null) {
6717                        result = new ArrayList<>();
6718                    }
6719                }
6720            }
6721        }
6722        if (addInstant) {
6723            result = maybeAddInstantAppInstaller(
6724                    result, intent, resolvedType, flags, userId, resolveForStart);
6725        }
6726        if (sortResult) {
6727            Collections.sort(result, mResolvePrioritySorter);
6728        }
6729        return applyPostResolutionFilter(
6730                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6731    }
6732
6733    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6734            String resolvedType, int flags, int userId, boolean resolveForStart) {
6735        // first, check to see if we've got an instant app already installed
6736        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6737        ResolveInfo localInstantApp = null;
6738        boolean blockResolution = false;
6739        if (!alreadyResolvedLocally) {
6740            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6741                    flags
6742                        | PackageManager.GET_RESOLVED_FILTER
6743                        | PackageManager.MATCH_INSTANT
6744                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6745                    userId);
6746            for (int i = instantApps.size() - 1; i >= 0; --i) {
6747                final ResolveInfo info = instantApps.get(i);
6748                final String packageName = info.activityInfo.packageName;
6749                final PackageSetting ps = mSettings.mPackages.get(packageName);
6750                if (ps.getInstantApp(userId)) {
6751                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6752                    final int status = (int)(packedStatus >> 32);
6753                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6754                        // there's a local instant application installed, but, the user has
6755                        // chosen to never use it; skip resolution and don't acknowledge
6756                        // an instant application is even available
6757                        if (DEBUG_INSTANT) {
6758                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6759                        }
6760                        blockResolution = true;
6761                        break;
6762                    } else {
6763                        // we have a locally installed instant application; skip resolution
6764                        // but acknowledge there's an instant application available
6765                        if (DEBUG_INSTANT) {
6766                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6767                        }
6768                        localInstantApp = info;
6769                        break;
6770                    }
6771                }
6772            }
6773        }
6774        // no app installed, let's see if one's available
6775        AuxiliaryResolveInfo auxiliaryResponse = null;
6776        if (!blockResolution) {
6777            if (localInstantApp == null) {
6778                // we don't have an instant app locally, resolve externally
6779                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6780                final InstantAppRequest requestObject = new InstantAppRequest(
6781                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6782                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6783                        resolveForStart);
6784                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6785                        mInstantAppResolverConnection, requestObject);
6786                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6787            } else {
6788                // we have an instant application locally, but, we can't admit that since
6789                // callers shouldn't be able to determine prior browsing. create a dummy
6790                // auxiliary response so the downstream code behaves as if there's an
6791                // instant application available externally. when it comes time to start
6792                // the instant application, we'll do the right thing.
6793                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6794                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6795                                        ai.packageName, ai.longVersionCode, null /* splitName */);
6796            }
6797        }
6798        if (intent.isWebIntent() && auxiliaryResponse == null) {
6799            return result;
6800        }
6801        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6802        if (ps == null
6803                || ps.getUserState().get(userId) == null
6804                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6805            return result;
6806        }
6807        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6808        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6809                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6810        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6811                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6812        // add a non-generic filter
6813        ephemeralInstaller.filter = new IntentFilter();
6814        if (intent.getAction() != null) {
6815            ephemeralInstaller.filter.addAction(intent.getAction());
6816        }
6817        if (intent.getData() != null && intent.getData().getPath() != null) {
6818            ephemeralInstaller.filter.addDataPath(
6819                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6820        }
6821        ephemeralInstaller.isInstantAppAvailable = true;
6822        // make sure this resolver is the default
6823        ephemeralInstaller.isDefault = true;
6824        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6825        if (DEBUG_INSTANT) {
6826            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6827        }
6828
6829        result.add(ephemeralInstaller);
6830        return result;
6831    }
6832
6833    private static class CrossProfileDomainInfo {
6834        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6835        ResolveInfo resolveInfo;
6836        /* Best domain verification status of the activities found in the other profile */
6837        int bestDomainVerificationStatus;
6838    }
6839
6840    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6841            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6842        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6843                sourceUserId)) {
6844            return null;
6845        }
6846        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6847                resolvedType, flags, parentUserId);
6848
6849        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6850            return null;
6851        }
6852        CrossProfileDomainInfo result = null;
6853        int size = resultTargetUser.size();
6854        for (int i = 0; i < size; i++) {
6855            ResolveInfo riTargetUser = resultTargetUser.get(i);
6856            // Intent filter verification is only for filters that specify a host. So don't return
6857            // those that handle all web uris.
6858            if (riTargetUser.handleAllWebDataURI) {
6859                continue;
6860            }
6861            String packageName = riTargetUser.activityInfo.packageName;
6862            PackageSetting ps = mSettings.mPackages.get(packageName);
6863            if (ps == null) {
6864                continue;
6865            }
6866            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6867            int status = (int)(verificationState >> 32);
6868            if (result == null) {
6869                result = new CrossProfileDomainInfo();
6870                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6871                        sourceUserId, parentUserId);
6872                result.bestDomainVerificationStatus = status;
6873            } else {
6874                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6875                        result.bestDomainVerificationStatus);
6876            }
6877        }
6878        // Don't consider matches with status NEVER across profiles.
6879        if (result != null && result.bestDomainVerificationStatus
6880                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6881            return null;
6882        }
6883        return result;
6884    }
6885
6886    /**
6887     * Verification statuses are ordered from the worse to the best, except for
6888     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6889     */
6890    private int bestDomainVerificationStatus(int status1, int status2) {
6891        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6892            return status2;
6893        }
6894        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6895            return status1;
6896        }
6897        return (int) MathUtils.max(status1, status2);
6898    }
6899
6900    private boolean isUserEnabled(int userId) {
6901        long callingId = Binder.clearCallingIdentity();
6902        try {
6903            UserInfo userInfo = sUserManager.getUserInfo(userId);
6904            return userInfo != null && userInfo.isEnabled();
6905        } finally {
6906            Binder.restoreCallingIdentity(callingId);
6907        }
6908    }
6909
6910    /**
6911     * Filter out activities with systemUserOnly flag set, when current user is not System.
6912     *
6913     * @return filtered list
6914     */
6915    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6916        if (userId == UserHandle.USER_SYSTEM) {
6917            return resolveInfos;
6918        }
6919        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6920            ResolveInfo info = resolveInfos.get(i);
6921            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6922                resolveInfos.remove(i);
6923            }
6924        }
6925        return resolveInfos;
6926    }
6927
6928    /**
6929     * Filters out ephemeral activities.
6930     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6931     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6932     *
6933     * @param resolveInfos The pre-filtered list of resolved activities
6934     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6935     *          is performed.
6936     * @param intent
6937     * @return A filtered list of resolved activities.
6938     */
6939    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6940            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6941            Intent intent) {
6942        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6943        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6944            final ResolveInfo info = resolveInfos.get(i);
6945            // remove locally resolved instant app web results when disabled
6946            if (info.isInstantAppAvailable && blockInstant) {
6947                resolveInfos.remove(i);
6948                continue;
6949            }
6950            // allow activities that are defined in the provided package
6951            if (allowDynamicSplits
6952                    && info.activityInfo != null
6953                    && info.activityInfo.splitName != null
6954                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6955                            info.activityInfo.splitName)) {
6956                if (mInstantAppInstallerActivity == null) {
6957                    if (DEBUG_INSTALL) {
6958                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6959                    }
6960                    resolveInfos.remove(i);
6961                    continue;
6962                }
6963                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6964                    resolveInfos.remove(i);
6965                    continue;
6966                }
6967                // requested activity is defined in a split that hasn't been installed yet.
6968                // add the installer to the resolve list
6969                if (DEBUG_INSTALL) {
6970                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6971                }
6972                final ResolveInfo installerInfo = new ResolveInfo(
6973                        mInstantAppInstallerInfo);
6974                final ComponentName installFailureActivity = findInstallFailureActivity(
6975                        info.activityInfo.packageName,  filterCallingUid, userId);
6976                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6977                        installFailureActivity,
6978                        info.activityInfo.packageName,
6979                        info.activityInfo.applicationInfo.longVersionCode,
6980                        info.activityInfo.splitName);
6981                // add a non-generic filter
6982                installerInfo.filter = new IntentFilter();
6983
6984                // This resolve info may appear in the chooser UI, so let us make it
6985                // look as the one it replaces as far as the user is concerned which
6986                // requires loading the correct label and icon for the resolve info.
6987                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6988                installerInfo.labelRes = info.resolveLabelResId();
6989                installerInfo.icon = info.resolveIconResId();
6990                installerInfo.isInstantAppAvailable = true;
6991                resolveInfos.set(i, installerInfo);
6992                continue;
6993            }
6994            // caller is a full app, don't need to apply any other filtering
6995            if (ephemeralPkgName == null) {
6996                continue;
6997            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6998                // caller is same app; don't need to apply any other filtering
6999                continue;
7000            }
7001            // allow activities that have been explicitly exposed to ephemeral apps
7002            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7003            if (!isEphemeralApp
7004                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7005                continue;
7006            }
7007            resolveInfos.remove(i);
7008        }
7009        return resolveInfos;
7010    }
7011
7012    /**
7013     * Returns the activity component that can handle install failures.
7014     * <p>By default, the instant application installer handles failures. However, an
7015     * application may want to handle failures on its own. Applications do this by
7016     * creating an activity with an intent filter that handles the action
7017     * {@link Intent#ACTION_INSTALL_FAILURE}.
7018     */
7019    private @Nullable ComponentName findInstallFailureActivity(
7020            String packageName, int filterCallingUid, int userId) {
7021        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7022        failureActivityIntent.setPackage(packageName);
7023        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7024        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7025                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7026                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7027        final int NR = result.size();
7028        if (NR > 0) {
7029            for (int i = 0; i < NR; i++) {
7030                final ResolveInfo info = result.get(i);
7031                if (info.activityInfo.splitName != null) {
7032                    continue;
7033                }
7034                return new ComponentName(packageName, info.activityInfo.name);
7035            }
7036        }
7037        return null;
7038    }
7039
7040    /**
7041     * @param resolveInfos list of resolve infos in descending priority order
7042     * @return if the list contains a resolve info with non-negative priority
7043     */
7044    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7045        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7046    }
7047
7048    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7049            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7050            int userId) {
7051        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7052
7053        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7054            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7055                    candidates.size());
7056        }
7057
7058        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7059        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7060        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7061        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7062        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7063        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7064
7065        synchronized (mPackages) {
7066            final int count = candidates.size();
7067            // First, try to use linked apps. Partition the candidates into four lists:
7068            // one for the final results, one for the "do not use ever", one for "undefined status"
7069            // and finally one for "browser app type".
7070            for (int n=0; n<count; n++) {
7071                ResolveInfo info = candidates.get(n);
7072                String packageName = info.activityInfo.packageName;
7073                PackageSetting ps = mSettings.mPackages.get(packageName);
7074                if (ps != null) {
7075                    // Add to the special match all list (Browser use case)
7076                    if (info.handleAllWebDataURI) {
7077                        matchAllList.add(info);
7078                        continue;
7079                    }
7080                    // Try to get the status from User settings first
7081                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7082                    int status = (int)(packedStatus >> 32);
7083                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7084                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7085                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7086                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7087                                    + " : linkgen=" + linkGeneration);
7088                        }
7089                        // Use link-enabled generation as preferredOrder, i.e.
7090                        // prefer newly-enabled over earlier-enabled.
7091                        info.preferredOrder = linkGeneration;
7092                        alwaysList.add(info);
7093                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7094                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7095                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7096                        }
7097                        neverList.add(info);
7098                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7099                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7100                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7101                        }
7102                        alwaysAskList.add(info);
7103                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7104                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7105                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7106                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7107                        }
7108                        undefinedList.add(info);
7109                    }
7110                }
7111            }
7112
7113            // We'll want to include browser possibilities in a few cases
7114            boolean includeBrowser = false;
7115
7116            // First try to add the "always" resolution(s) for the current user, if any
7117            if (alwaysList.size() > 0) {
7118                result.addAll(alwaysList);
7119            } else {
7120                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7121                result.addAll(undefinedList);
7122                // Maybe add one for the other profile.
7123                if (xpDomainInfo != null && (
7124                        xpDomainInfo.bestDomainVerificationStatus
7125                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7126                    result.add(xpDomainInfo.resolveInfo);
7127                }
7128                includeBrowser = true;
7129            }
7130
7131            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7132            // If there were 'always' entries their preferred order has been set, so we also
7133            // back that off to make the alternatives equivalent
7134            if (alwaysAskList.size() > 0) {
7135                for (ResolveInfo i : result) {
7136                    i.preferredOrder = 0;
7137                }
7138                result.addAll(alwaysAskList);
7139                includeBrowser = true;
7140            }
7141
7142            if (includeBrowser) {
7143                // Also add browsers (all of them or only the default one)
7144                if (DEBUG_DOMAIN_VERIFICATION) {
7145                    Slog.v(TAG, "   ...including browsers in candidate set");
7146                }
7147                if ((matchFlags & MATCH_ALL) != 0) {
7148                    result.addAll(matchAllList);
7149                } else {
7150                    // Browser/generic handling case.  If there's a default browser, go straight
7151                    // to that (but only if there is no other higher-priority match).
7152                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7153                    int maxMatchPrio = 0;
7154                    ResolveInfo defaultBrowserMatch = null;
7155                    final int numCandidates = matchAllList.size();
7156                    for (int n = 0; n < numCandidates; n++) {
7157                        ResolveInfo info = matchAllList.get(n);
7158                        // track the highest overall match priority...
7159                        if (info.priority > maxMatchPrio) {
7160                            maxMatchPrio = info.priority;
7161                        }
7162                        // ...and the highest-priority default browser match
7163                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7164                            if (defaultBrowserMatch == null
7165                                    || (defaultBrowserMatch.priority < info.priority)) {
7166                                if (debug) {
7167                                    Slog.v(TAG, "Considering default browser match " + info);
7168                                }
7169                                defaultBrowserMatch = info;
7170                            }
7171                        }
7172                    }
7173                    if (defaultBrowserMatch != null
7174                            && defaultBrowserMatch.priority >= maxMatchPrio
7175                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7176                    {
7177                        if (debug) {
7178                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7179                        }
7180                        result.add(defaultBrowserMatch);
7181                    } else {
7182                        result.addAll(matchAllList);
7183                    }
7184                }
7185
7186                // If there is nothing selected, add all candidates and remove the ones that the user
7187                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7188                if (result.size() == 0) {
7189                    result.addAll(candidates);
7190                    result.removeAll(neverList);
7191                }
7192            }
7193        }
7194        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7195            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7196                    result.size());
7197            for (ResolveInfo info : result) {
7198                Slog.v(TAG, "  + " + info.activityInfo);
7199            }
7200        }
7201        return result;
7202    }
7203
7204    // Returns a packed value as a long:
7205    //
7206    // high 'int'-sized word: link status: undefined/ask/never/always.
7207    // low 'int'-sized word: relative priority among 'always' results.
7208    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7209        long result = ps.getDomainVerificationStatusForUser(userId);
7210        // if none available, get the master status
7211        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7212            if (ps.getIntentFilterVerificationInfo() != null) {
7213                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7214            }
7215        }
7216        return result;
7217    }
7218
7219    private ResolveInfo querySkipCurrentProfileIntents(
7220            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7221            int flags, int sourceUserId) {
7222        if (matchingFilters != null) {
7223            int size = matchingFilters.size();
7224            for (int i = 0; i < size; i ++) {
7225                CrossProfileIntentFilter filter = matchingFilters.get(i);
7226                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7227                    // Checking if there are activities in the target user that can handle the
7228                    // intent.
7229                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7230                            resolvedType, flags, sourceUserId);
7231                    if (resolveInfo != null) {
7232                        return resolveInfo;
7233                    }
7234                }
7235            }
7236        }
7237        return null;
7238    }
7239
7240    // Return matching ResolveInfo in target user if any.
7241    private ResolveInfo queryCrossProfileIntents(
7242            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7243            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7244        if (matchingFilters != null) {
7245            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7246            // match the same intent. For performance reasons, it is better not to
7247            // run queryIntent twice for the same userId
7248            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7249            int size = matchingFilters.size();
7250            for (int i = 0; i < size; i++) {
7251                CrossProfileIntentFilter filter = matchingFilters.get(i);
7252                int targetUserId = filter.getTargetUserId();
7253                boolean skipCurrentProfile =
7254                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7255                boolean skipCurrentProfileIfNoMatchFound =
7256                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7257                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7258                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7259                    // Checking if there are activities in the target user that can handle the
7260                    // intent.
7261                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7262                            resolvedType, flags, sourceUserId);
7263                    if (resolveInfo != null) return resolveInfo;
7264                    alreadyTriedUserIds.put(targetUserId, true);
7265                }
7266            }
7267        }
7268        return null;
7269    }
7270
7271    /**
7272     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7273     * will forward the intent to the filter's target user.
7274     * Otherwise, returns null.
7275     */
7276    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7277            String resolvedType, int flags, int sourceUserId) {
7278        int targetUserId = filter.getTargetUserId();
7279        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7280                resolvedType, flags, targetUserId);
7281        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7282            // If all the matches in the target profile are suspended, return null.
7283            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7284                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7285                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7286                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7287                            targetUserId);
7288                }
7289            }
7290        }
7291        return null;
7292    }
7293
7294    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7295            int sourceUserId, int targetUserId) {
7296        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7297        long ident = Binder.clearCallingIdentity();
7298        boolean targetIsProfile;
7299        try {
7300            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7301        } finally {
7302            Binder.restoreCallingIdentity(ident);
7303        }
7304        String className;
7305        if (targetIsProfile) {
7306            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7307        } else {
7308            className = FORWARD_INTENT_TO_PARENT;
7309        }
7310        ComponentName forwardingActivityComponentName = new ComponentName(
7311                mAndroidApplication.packageName, className);
7312        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7313                sourceUserId);
7314        if (!targetIsProfile) {
7315            forwardingActivityInfo.showUserIcon = targetUserId;
7316            forwardingResolveInfo.noResourceId = true;
7317        }
7318        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7319        forwardingResolveInfo.priority = 0;
7320        forwardingResolveInfo.preferredOrder = 0;
7321        forwardingResolveInfo.match = 0;
7322        forwardingResolveInfo.isDefault = true;
7323        forwardingResolveInfo.filter = filter;
7324        forwardingResolveInfo.targetUserId = targetUserId;
7325        return forwardingResolveInfo;
7326    }
7327
7328    @Override
7329    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7330            Intent[] specifics, String[] specificTypes, Intent intent,
7331            String resolvedType, int flags, int userId) {
7332        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7333                specificTypes, intent, resolvedType, flags, userId));
7334    }
7335
7336    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7337            Intent[] specifics, String[] specificTypes, Intent intent,
7338            String resolvedType, int flags, int userId) {
7339        if (!sUserManager.exists(userId)) return Collections.emptyList();
7340        final int callingUid = Binder.getCallingUid();
7341        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7342                false /*includeInstantApps*/);
7343        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7344                false /*requireFullPermission*/, false /*checkShell*/,
7345                "query intent activity options");
7346        final String resultsAction = intent.getAction();
7347
7348        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7349                | PackageManager.GET_RESOLVED_FILTER, userId);
7350
7351        if (DEBUG_INTENT_MATCHING) {
7352            Log.v(TAG, "Query " + intent + ": " + results);
7353        }
7354
7355        int specificsPos = 0;
7356        int N;
7357
7358        // todo: note that the algorithm used here is O(N^2).  This
7359        // isn't a problem in our current environment, but if we start running
7360        // into situations where we have more than 5 or 10 matches then this
7361        // should probably be changed to something smarter...
7362
7363        // First we go through and resolve each of the specific items
7364        // that were supplied, taking care of removing any corresponding
7365        // duplicate items in the generic resolve list.
7366        if (specifics != null) {
7367            for (int i=0; i<specifics.length; i++) {
7368                final Intent sintent = specifics[i];
7369                if (sintent == null) {
7370                    continue;
7371                }
7372
7373                if (DEBUG_INTENT_MATCHING) {
7374                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7375                }
7376
7377                String action = sintent.getAction();
7378                if (resultsAction != null && resultsAction.equals(action)) {
7379                    // If this action was explicitly requested, then don't
7380                    // remove things that have it.
7381                    action = null;
7382                }
7383
7384                ResolveInfo ri = null;
7385                ActivityInfo ai = null;
7386
7387                ComponentName comp = sintent.getComponent();
7388                if (comp == null) {
7389                    ri = resolveIntent(
7390                        sintent,
7391                        specificTypes != null ? specificTypes[i] : null,
7392                            flags, userId);
7393                    if (ri == null) {
7394                        continue;
7395                    }
7396                    if (ri == mResolveInfo) {
7397                        // ACK!  Must do something better with this.
7398                    }
7399                    ai = ri.activityInfo;
7400                    comp = new ComponentName(ai.applicationInfo.packageName,
7401                            ai.name);
7402                } else {
7403                    ai = getActivityInfo(comp, flags, userId);
7404                    if (ai == null) {
7405                        continue;
7406                    }
7407                }
7408
7409                // Look for any generic query activities that are duplicates
7410                // of this specific one, and remove them from the results.
7411                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7412                N = results.size();
7413                int j;
7414                for (j=specificsPos; j<N; j++) {
7415                    ResolveInfo sri = results.get(j);
7416                    if ((sri.activityInfo.name.equals(comp.getClassName())
7417                            && sri.activityInfo.applicationInfo.packageName.equals(
7418                                    comp.getPackageName()))
7419                        || (action != null && sri.filter.matchAction(action))) {
7420                        results.remove(j);
7421                        if (DEBUG_INTENT_MATCHING) Log.v(
7422                            TAG, "Removing duplicate item from " + j
7423                            + " due to specific " + specificsPos);
7424                        if (ri == null) {
7425                            ri = sri;
7426                        }
7427                        j--;
7428                        N--;
7429                    }
7430                }
7431
7432                // Add this specific item to its proper place.
7433                if (ri == null) {
7434                    ri = new ResolveInfo();
7435                    ri.activityInfo = ai;
7436                }
7437                results.add(specificsPos, ri);
7438                ri.specificIndex = i;
7439                specificsPos++;
7440            }
7441        }
7442
7443        // Now we go through the remaining generic results and remove any
7444        // duplicate actions that are found here.
7445        N = results.size();
7446        for (int i=specificsPos; i<N-1; i++) {
7447            final ResolveInfo rii = results.get(i);
7448            if (rii.filter == null) {
7449                continue;
7450            }
7451
7452            // Iterate over all of the actions of this result's intent
7453            // filter...  typically this should be just one.
7454            final Iterator<String> it = rii.filter.actionsIterator();
7455            if (it == null) {
7456                continue;
7457            }
7458            while (it.hasNext()) {
7459                final String action = it.next();
7460                if (resultsAction != null && resultsAction.equals(action)) {
7461                    // If this action was explicitly requested, then don't
7462                    // remove things that have it.
7463                    continue;
7464                }
7465                for (int j=i+1; j<N; j++) {
7466                    final ResolveInfo rij = results.get(j);
7467                    if (rij.filter != null && rij.filter.hasAction(action)) {
7468                        results.remove(j);
7469                        if (DEBUG_INTENT_MATCHING) Log.v(
7470                            TAG, "Removing duplicate item from " + j
7471                            + " due to action " + action + " at " + i);
7472                        j--;
7473                        N--;
7474                    }
7475                }
7476            }
7477
7478            // If the caller didn't request filter information, drop it now
7479            // so we don't have to marshall/unmarshall it.
7480            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7481                rii.filter = null;
7482            }
7483        }
7484
7485        // Filter out the caller activity if so requested.
7486        if (caller != null) {
7487            N = results.size();
7488            for (int i=0; i<N; i++) {
7489                ActivityInfo ainfo = results.get(i).activityInfo;
7490                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7491                        && caller.getClassName().equals(ainfo.name)) {
7492                    results.remove(i);
7493                    break;
7494                }
7495            }
7496        }
7497
7498        // If the caller didn't request filter information,
7499        // drop them now so we don't have to
7500        // marshall/unmarshall it.
7501        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7502            N = results.size();
7503            for (int i=0; i<N; i++) {
7504                results.get(i).filter = null;
7505            }
7506        }
7507
7508        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7509        return results;
7510    }
7511
7512    @Override
7513    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7514            String resolvedType, int flags, int userId) {
7515        return new ParceledListSlice<>(
7516                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7517                        false /*allowDynamicSplits*/));
7518    }
7519
7520    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7521            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7522        if (!sUserManager.exists(userId)) return Collections.emptyList();
7523        final int callingUid = Binder.getCallingUid();
7524        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7525                false /*requireFullPermission*/, false /*checkShell*/,
7526                "query intent receivers");
7527        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7528        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7529                false /*includeInstantApps*/);
7530        ComponentName comp = intent.getComponent();
7531        if (comp == null) {
7532            if (intent.getSelector() != null) {
7533                intent = intent.getSelector();
7534                comp = intent.getComponent();
7535            }
7536        }
7537        if (comp != null) {
7538            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7539            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7540            if (ai != null) {
7541                // When specifying an explicit component, we prevent the activity from being
7542                // used when either 1) the calling package is normal and the activity is within
7543                // an instant application or 2) the calling package is ephemeral and the
7544                // activity is not visible to instant applications.
7545                final boolean matchInstantApp =
7546                        (flags & PackageManager.MATCH_INSTANT) != 0;
7547                final boolean matchVisibleToInstantAppOnly =
7548                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7549                final boolean matchExplicitlyVisibleOnly =
7550                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7551                final boolean isCallerInstantApp =
7552                        instantAppPkgName != null;
7553                final boolean isTargetSameInstantApp =
7554                        comp.getPackageName().equals(instantAppPkgName);
7555                final boolean isTargetInstantApp =
7556                        (ai.applicationInfo.privateFlags
7557                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7558                final boolean isTargetVisibleToInstantApp =
7559                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7560                final boolean isTargetExplicitlyVisibleToInstantApp =
7561                        isTargetVisibleToInstantApp
7562                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7563                final boolean isTargetHiddenFromInstantApp =
7564                        !isTargetVisibleToInstantApp
7565                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7566                final boolean blockResolution =
7567                        !isTargetSameInstantApp
7568                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7569                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7570                                        && isTargetHiddenFromInstantApp));
7571                if (!blockResolution) {
7572                    ResolveInfo ri = new ResolveInfo();
7573                    ri.activityInfo = ai;
7574                    list.add(ri);
7575                }
7576            }
7577            return applyPostResolutionFilter(
7578                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7579        }
7580
7581        // reader
7582        synchronized (mPackages) {
7583            String pkgName = intent.getPackage();
7584            if (pkgName == null) {
7585                final List<ResolveInfo> result =
7586                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7587                return applyPostResolutionFilter(
7588                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7589            }
7590            final PackageParser.Package pkg = mPackages.get(pkgName);
7591            if (pkg != null) {
7592                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7593                        intent, resolvedType, flags, pkg.receivers, userId);
7594                return applyPostResolutionFilter(
7595                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7596            }
7597            return Collections.emptyList();
7598        }
7599    }
7600
7601    @Override
7602    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7603        final int callingUid = Binder.getCallingUid();
7604        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7605    }
7606
7607    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7608            int userId, int callingUid) {
7609        if (!sUserManager.exists(userId)) return null;
7610        flags = updateFlagsForResolve(
7611                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7612        List<ResolveInfo> query = queryIntentServicesInternal(
7613                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7614        if (query != null) {
7615            if (query.size() >= 1) {
7616                // If there is more than one service with the same priority,
7617                // just arbitrarily pick the first one.
7618                return query.get(0);
7619            }
7620        }
7621        return null;
7622    }
7623
7624    @Override
7625    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7626            String resolvedType, int flags, int userId) {
7627        final int callingUid = Binder.getCallingUid();
7628        return new ParceledListSlice<>(queryIntentServicesInternal(
7629                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7630    }
7631
7632    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7633            String resolvedType, int flags, int userId, int callingUid,
7634            boolean includeInstantApps) {
7635        if (!sUserManager.exists(userId)) return Collections.emptyList();
7636        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7637                false /*requireFullPermission*/, false /*checkShell*/,
7638                "query intent receivers");
7639        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7640        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7641        ComponentName comp = intent.getComponent();
7642        if (comp == null) {
7643            if (intent.getSelector() != null) {
7644                intent = intent.getSelector();
7645                comp = intent.getComponent();
7646            }
7647        }
7648        if (comp != null) {
7649            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7650            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7651            if (si != null) {
7652                // When specifying an explicit component, we prevent the service from being
7653                // used when either 1) the service is in an instant application and the
7654                // caller is not the same instant application or 2) the calling package is
7655                // ephemeral and the activity is not visible to ephemeral applications.
7656                final boolean matchInstantApp =
7657                        (flags & PackageManager.MATCH_INSTANT) != 0;
7658                final boolean matchVisibleToInstantAppOnly =
7659                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7660                final boolean isCallerInstantApp =
7661                        instantAppPkgName != null;
7662                final boolean isTargetSameInstantApp =
7663                        comp.getPackageName().equals(instantAppPkgName);
7664                final boolean isTargetInstantApp =
7665                        (si.applicationInfo.privateFlags
7666                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7667                final boolean isTargetHiddenFromInstantApp =
7668                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7669                final boolean blockResolution =
7670                        !isTargetSameInstantApp
7671                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7672                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7673                                        && isTargetHiddenFromInstantApp));
7674                if (!blockResolution) {
7675                    final ResolveInfo ri = new ResolveInfo();
7676                    ri.serviceInfo = si;
7677                    list.add(ri);
7678                }
7679            }
7680            return list;
7681        }
7682
7683        // reader
7684        synchronized (mPackages) {
7685            String pkgName = intent.getPackage();
7686            if (pkgName == null) {
7687                return applyPostServiceResolutionFilter(
7688                        mServices.queryIntent(intent, resolvedType, flags, userId),
7689                        instantAppPkgName);
7690            }
7691            final PackageParser.Package pkg = mPackages.get(pkgName);
7692            if (pkg != null) {
7693                return applyPostServiceResolutionFilter(
7694                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7695                                userId),
7696                        instantAppPkgName);
7697            }
7698            return Collections.emptyList();
7699        }
7700    }
7701
7702    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7703            String instantAppPkgName) {
7704        if (instantAppPkgName == null) {
7705            return resolveInfos;
7706        }
7707        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7708            final ResolveInfo info = resolveInfos.get(i);
7709            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7710            // allow services that are defined in the provided package
7711            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7712                if (info.serviceInfo.splitName != null
7713                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7714                                info.serviceInfo.splitName)) {
7715                    // requested service is defined in a split that hasn't been installed yet.
7716                    // add the installer to the resolve list
7717                    if (DEBUG_INSTANT) {
7718                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7719                    }
7720                    final ResolveInfo installerInfo = new ResolveInfo(
7721                            mInstantAppInstallerInfo);
7722                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7723                            null /* installFailureActivity */,
7724                            info.serviceInfo.packageName,
7725                            info.serviceInfo.applicationInfo.longVersionCode,
7726                            info.serviceInfo.splitName);
7727                    // add a non-generic filter
7728                    installerInfo.filter = new IntentFilter();
7729                    // load resources from the correct package
7730                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7731                    resolveInfos.set(i, installerInfo);
7732                }
7733                continue;
7734            }
7735            // allow services that have been explicitly exposed to ephemeral apps
7736            if (!isEphemeralApp
7737                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7738                continue;
7739            }
7740            resolveInfos.remove(i);
7741        }
7742        return resolveInfos;
7743    }
7744
7745    @Override
7746    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7747            String resolvedType, int flags, int userId) {
7748        return new ParceledListSlice<>(
7749                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7750    }
7751
7752    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7753            Intent intent, String resolvedType, int flags, int userId) {
7754        if (!sUserManager.exists(userId)) return Collections.emptyList();
7755        final int callingUid = Binder.getCallingUid();
7756        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7757        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7758                false /*includeInstantApps*/);
7759        ComponentName comp = intent.getComponent();
7760        if (comp == null) {
7761            if (intent.getSelector() != null) {
7762                intent = intent.getSelector();
7763                comp = intent.getComponent();
7764            }
7765        }
7766        if (comp != null) {
7767            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7768            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7769            if (pi != null) {
7770                // When specifying an explicit component, we prevent the provider from being
7771                // used when either 1) the provider is in an instant application and the
7772                // caller is not the same instant application or 2) the calling package is an
7773                // instant application and the provider is not visible to instant applications.
7774                final boolean matchInstantApp =
7775                        (flags & PackageManager.MATCH_INSTANT) != 0;
7776                final boolean matchVisibleToInstantAppOnly =
7777                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7778                final boolean isCallerInstantApp =
7779                        instantAppPkgName != null;
7780                final boolean isTargetSameInstantApp =
7781                        comp.getPackageName().equals(instantAppPkgName);
7782                final boolean isTargetInstantApp =
7783                        (pi.applicationInfo.privateFlags
7784                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7785                final boolean isTargetHiddenFromInstantApp =
7786                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7787                final boolean blockResolution =
7788                        !isTargetSameInstantApp
7789                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7790                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7791                                        && isTargetHiddenFromInstantApp));
7792                if (!blockResolution) {
7793                    final ResolveInfo ri = new ResolveInfo();
7794                    ri.providerInfo = pi;
7795                    list.add(ri);
7796                }
7797            }
7798            return list;
7799        }
7800
7801        // reader
7802        synchronized (mPackages) {
7803            String pkgName = intent.getPackage();
7804            if (pkgName == null) {
7805                return applyPostContentProviderResolutionFilter(
7806                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7807                        instantAppPkgName);
7808            }
7809            final PackageParser.Package pkg = mPackages.get(pkgName);
7810            if (pkg != null) {
7811                return applyPostContentProviderResolutionFilter(
7812                        mProviders.queryIntentForPackage(
7813                        intent, resolvedType, flags, pkg.providers, userId),
7814                        instantAppPkgName);
7815            }
7816            return Collections.emptyList();
7817        }
7818    }
7819
7820    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7821            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7822        if (instantAppPkgName == null) {
7823            return resolveInfos;
7824        }
7825        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7826            final ResolveInfo info = resolveInfos.get(i);
7827            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7828            // allow providers that are defined in the provided package
7829            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7830                if (info.providerInfo.splitName != null
7831                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7832                                info.providerInfo.splitName)) {
7833                    // requested provider is defined in a split that hasn't been installed yet.
7834                    // add the installer to the resolve list
7835                    if (DEBUG_INSTANT) {
7836                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7837                    }
7838                    final ResolveInfo installerInfo = new ResolveInfo(
7839                            mInstantAppInstallerInfo);
7840                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7841                            null /*failureActivity*/,
7842                            info.providerInfo.packageName,
7843                            info.providerInfo.applicationInfo.longVersionCode,
7844                            info.providerInfo.splitName);
7845                    // add a non-generic filter
7846                    installerInfo.filter = new IntentFilter();
7847                    // load resources from the correct package
7848                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7849                    resolveInfos.set(i, installerInfo);
7850                }
7851                continue;
7852            }
7853            // allow providers that have been explicitly exposed to instant applications
7854            if (!isEphemeralApp
7855                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7856                continue;
7857            }
7858            resolveInfos.remove(i);
7859        }
7860        return resolveInfos;
7861    }
7862
7863    @Override
7864    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7865        final int callingUid = Binder.getCallingUid();
7866        if (getInstantAppPackageName(callingUid) != null) {
7867            return ParceledListSlice.emptyList();
7868        }
7869        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7870        flags = updateFlagsForPackage(flags, userId, null);
7871        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7872        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7873                true /* requireFullPermission */, false /* checkShell */,
7874                "get installed packages");
7875
7876        // writer
7877        synchronized (mPackages) {
7878            ArrayList<PackageInfo> list;
7879            if (listUninstalled) {
7880                list = new ArrayList<>(mSettings.mPackages.size());
7881                for (PackageSetting ps : mSettings.mPackages.values()) {
7882                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7883                        continue;
7884                    }
7885                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7886                        continue;
7887                    }
7888                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7889                    if (pi != null) {
7890                        list.add(pi);
7891                    }
7892                }
7893            } else {
7894                list = new ArrayList<>(mPackages.size());
7895                for (PackageParser.Package p : mPackages.values()) {
7896                    final PackageSetting ps = (PackageSetting) p.mExtras;
7897                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7898                        continue;
7899                    }
7900                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7901                        continue;
7902                    }
7903                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7904                            p.mExtras, flags, userId);
7905                    if (pi != null) {
7906                        list.add(pi);
7907                    }
7908                }
7909            }
7910
7911            return new ParceledListSlice<>(list);
7912        }
7913    }
7914
7915    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7916            String[] permissions, boolean[] tmp, int flags, int userId) {
7917        int numMatch = 0;
7918        final PermissionsState permissionsState = ps.getPermissionsState();
7919        for (int i=0; i<permissions.length; i++) {
7920            final String permission = permissions[i];
7921            if (permissionsState.hasPermission(permission, userId)) {
7922                tmp[i] = true;
7923                numMatch++;
7924            } else {
7925                tmp[i] = false;
7926            }
7927        }
7928        if (numMatch == 0) {
7929            return;
7930        }
7931        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7932
7933        // The above might return null in cases of uninstalled apps or install-state
7934        // skew across users/profiles.
7935        if (pi != null) {
7936            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7937                if (numMatch == permissions.length) {
7938                    pi.requestedPermissions = permissions;
7939                } else {
7940                    pi.requestedPermissions = new String[numMatch];
7941                    numMatch = 0;
7942                    for (int i=0; i<permissions.length; i++) {
7943                        if (tmp[i]) {
7944                            pi.requestedPermissions[numMatch] = permissions[i];
7945                            numMatch++;
7946                        }
7947                    }
7948                }
7949            }
7950            list.add(pi);
7951        }
7952    }
7953
7954    @Override
7955    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7956            String[] permissions, int flags, int userId) {
7957        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7958        flags = updateFlagsForPackage(flags, userId, permissions);
7959        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7960                true /* requireFullPermission */, false /* checkShell */,
7961                "get packages holding permissions");
7962        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7963
7964        // writer
7965        synchronized (mPackages) {
7966            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7967            boolean[] tmpBools = new boolean[permissions.length];
7968            if (listUninstalled) {
7969                for (PackageSetting ps : mSettings.mPackages.values()) {
7970                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7971                            userId);
7972                }
7973            } else {
7974                for (PackageParser.Package pkg : mPackages.values()) {
7975                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7976                    if (ps != null) {
7977                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7978                                userId);
7979                    }
7980                }
7981            }
7982
7983            return new ParceledListSlice<PackageInfo>(list);
7984        }
7985    }
7986
7987    @Override
7988    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7989        final int callingUid = Binder.getCallingUid();
7990        if (getInstantAppPackageName(callingUid) != null) {
7991            return ParceledListSlice.emptyList();
7992        }
7993        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7994        flags = updateFlagsForApplication(flags, userId, null);
7995        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7996
7997        // writer
7998        synchronized (mPackages) {
7999            ArrayList<ApplicationInfo> list;
8000            if (listUninstalled) {
8001                list = new ArrayList<>(mSettings.mPackages.size());
8002                for (PackageSetting ps : mSettings.mPackages.values()) {
8003                    ApplicationInfo ai;
8004                    int effectiveFlags = flags;
8005                    if (ps.isSystem()) {
8006                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8007                    }
8008                    if (ps.pkg != null) {
8009                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8010                            continue;
8011                        }
8012                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8013                            continue;
8014                        }
8015                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8016                                ps.readUserState(userId), userId);
8017                        if (ai != null) {
8018                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8019                        }
8020                    } else {
8021                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8022                        // and already converts to externally visible package name
8023                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8024                                callingUid, effectiveFlags, userId);
8025                    }
8026                    if (ai != null) {
8027                        list.add(ai);
8028                    }
8029                }
8030            } else {
8031                list = new ArrayList<>(mPackages.size());
8032                for (PackageParser.Package p : mPackages.values()) {
8033                    if (p.mExtras != null) {
8034                        PackageSetting ps = (PackageSetting) p.mExtras;
8035                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8036                            continue;
8037                        }
8038                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8039                            continue;
8040                        }
8041                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8042                                ps.readUserState(userId), userId);
8043                        if (ai != null) {
8044                            ai.packageName = resolveExternalPackageNameLPr(p);
8045                            list.add(ai);
8046                        }
8047                    }
8048                }
8049            }
8050
8051            return new ParceledListSlice<>(list);
8052        }
8053    }
8054
8055    @Override
8056    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8057        if (HIDE_EPHEMERAL_APIS) {
8058            return null;
8059        }
8060        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8061            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8062                    "getEphemeralApplications");
8063        }
8064        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8065                true /* requireFullPermission */, false /* checkShell */,
8066                "getEphemeralApplications");
8067        synchronized (mPackages) {
8068            List<InstantAppInfo> instantApps = mInstantAppRegistry
8069                    .getInstantAppsLPr(userId);
8070            if (instantApps != null) {
8071                return new ParceledListSlice<>(instantApps);
8072            }
8073        }
8074        return null;
8075    }
8076
8077    @Override
8078    public boolean isInstantApp(String packageName, int userId) {
8079        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8080                true /* requireFullPermission */, false /* checkShell */,
8081                "isInstantApp");
8082        if (HIDE_EPHEMERAL_APIS) {
8083            return false;
8084        }
8085
8086        synchronized (mPackages) {
8087            int callingUid = Binder.getCallingUid();
8088            if (Process.isIsolated(callingUid)) {
8089                callingUid = mIsolatedOwners.get(callingUid);
8090            }
8091            final PackageSetting ps = mSettings.mPackages.get(packageName);
8092            PackageParser.Package pkg = mPackages.get(packageName);
8093            final boolean returnAllowed =
8094                    ps != null
8095                    && (isCallerSameApp(packageName, callingUid)
8096                            || canViewInstantApps(callingUid, userId)
8097                            || mInstantAppRegistry.isInstantAccessGranted(
8098                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8099            if (returnAllowed) {
8100                return ps.getInstantApp(userId);
8101            }
8102        }
8103        return false;
8104    }
8105
8106    @Override
8107    public byte[] getInstantAppCookie(String packageName, int userId) {
8108        if (HIDE_EPHEMERAL_APIS) {
8109            return null;
8110        }
8111
8112        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8113                true /* requireFullPermission */, false /* checkShell */,
8114                "getInstantAppCookie");
8115        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8116            return null;
8117        }
8118        synchronized (mPackages) {
8119            return mInstantAppRegistry.getInstantAppCookieLPw(
8120                    packageName, userId);
8121        }
8122    }
8123
8124    @Override
8125    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8126        if (HIDE_EPHEMERAL_APIS) {
8127            return true;
8128        }
8129
8130        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8131                true /* requireFullPermission */, true /* checkShell */,
8132                "setInstantAppCookie");
8133        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8134            return false;
8135        }
8136        synchronized (mPackages) {
8137            return mInstantAppRegistry.setInstantAppCookieLPw(
8138                    packageName, cookie, userId);
8139        }
8140    }
8141
8142    @Override
8143    public Bitmap getInstantAppIcon(String packageName, int userId) {
8144        if (HIDE_EPHEMERAL_APIS) {
8145            return null;
8146        }
8147
8148        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8149            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8150                    "getInstantAppIcon");
8151        }
8152        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8153                true /* requireFullPermission */, false /* checkShell */,
8154                "getInstantAppIcon");
8155
8156        synchronized (mPackages) {
8157            return mInstantAppRegistry.getInstantAppIconLPw(
8158                    packageName, userId);
8159        }
8160    }
8161
8162    private boolean isCallerSameApp(String packageName, int uid) {
8163        PackageParser.Package pkg = mPackages.get(packageName);
8164        return pkg != null
8165                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8166    }
8167
8168    @Override
8169    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8170        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8171            return ParceledListSlice.emptyList();
8172        }
8173        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8174    }
8175
8176    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8177        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8178
8179        // reader
8180        synchronized (mPackages) {
8181            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8182            final int userId = UserHandle.getCallingUserId();
8183            while (i.hasNext()) {
8184                final PackageParser.Package p = i.next();
8185                if (p.applicationInfo == null) continue;
8186
8187                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8188                        && !p.applicationInfo.isDirectBootAware();
8189                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8190                        && p.applicationInfo.isDirectBootAware();
8191
8192                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8193                        && (!mSafeMode || isSystemApp(p))
8194                        && (matchesUnaware || matchesAware)) {
8195                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8196                    if (ps != null) {
8197                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8198                                ps.readUserState(userId), userId);
8199                        if (ai != null) {
8200                            finalList.add(ai);
8201                        }
8202                    }
8203                }
8204            }
8205        }
8206
8207        return finalList;
8208    }
8209
8210    @Override
8211    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8212        return resolveContentProviderInternal(name, flags, userId);
8213    }
8214
8215    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8216        if (!sUserManager.exists(userId)) return null;
8217        flags = updateFlagsForComponent(flags, userId, name);
8218        final int callingUid = Binder.getCallingUid();
8219        synchronized (mPackages) {
8220            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8221            PackageSetting ps = provider != null
8222                    ? mSettings.mPackages.get(provider.owner.packageName)
8223                    : null;
8224            if (ps != null) {
8225                // provider not enabled
8226                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8227                    return null;
8228                }
8229                final ComponentName component =
8230                        new ComponentName(provider.info.packageName, provider.info.name);
8231                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8232                    return null;
8233                }
8234                return PackageParser.generateProviderInfo(
8235                        provider, flags, ps.readUserState(userId), userId);
8236            }
8237            return null;
8238        }
8239    }
8240
8241    /**
8242     * @deprecated
8243     */
8244    @Deprecated
8245    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8246        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8247            return;
8248        }
8249        // reader
8250        synchronized (mPackages) {
8251            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8252                    .entrySet().iterator();
8253            final int userId = UserHandle.getCallingUserId();
8254            while (i.hasNext()) {
8255                Map.Entry<String, PackageParser.Provider> entry = i.next();
8256                PackageParser.Provider p = entry.getValue();
8257                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8258
8259                if (ps != null && p.syncable
8260                        && (!mSafeMode || (p.info.applicationInfo.flags
8261                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8262                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8263                            ps.readUserState(userId), userId);
8264                    if (info != null) {
8265                        outNames.add(entry.getKey());
8266                        outInfo.add(info);
8267                    }
8268                }
8269            }
8270        }
8271    }
8272
8273    @Override
8274    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8275            int uid, int flags, String metaDataKey) {
8276        final int callingUid = Binder.getCallingUid();
8277        final int userId = processName != null ? UserHandle.getUserId(uid)
8278                : UserHandle.getCallingUserId();
8279        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8280        flags = updateFlagsForComponent(flags, userId, processName);
8281        ArrayList<ProviderInfo> finalList = null;
8282        // reader
8283        synchronized (mPackages) {
8284            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8285            while (i.hasNext()) {
8286                final PackageParser.Provider p = i.next();
8287                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8288                if (ps != null && p.info.authority != null
8289                        && (processName == null
8290                                || (p.info.processName.equals(processName)
8291                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8292                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8293
8294                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8295                    // parameter.
8296                    if (metaDataKey != null
8297                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8298                        continue;
8299                    }
8300                    final ComponentName component =
8301                            new ComponentName(p.info.packageName, p.info.name);
8302                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8303                        continue;
8304                    }
8305                    if (finalList == null) {
8306                        finalList = new ArrayList<ProviderInfo>(3);
8307                    }
8308                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8309                            ps.readUserState(userId), userId);
8310                    if (info != null) {
8311                        finalList.add(info);
8312                    }
8313                }
8314            }
8315        }
8316
8317        if (finalList != null) {
8318            Collections.sort(finalList, mProviderInitOrderSorter);
8319            return new ParceledListSlice<ProviderInfo>(finalList);
8320        }
8321
8322        return ParceledListSlice.emptyList();
8323    }
8324
8325    @Override
8326    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8327        // reader
8328        synchronized (mPackages) {
8329            final int callingUid = Binder.getCallingUid();
8330            final int callingUserId = UserHandle.getUserId(callingUid);
8331            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8332            if (ps == null) return null;
8333            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8334                return null;
8335            }
8336            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8337            return PackageParser.generateInstrumentationInfo(i, flags);
8338        }
8339    }
8340
8341    @Override
8342    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8343            String targetPackage, int flags) {
8344        final int callingUid = Binder.getCallingUid();
8345        final int callingUserId = UserHandle.getUserId(callingUid);
8346        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8347        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8348            return ParceledListSlice.emptyList();
8349        }
8350        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8351    }
8352
8353    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8354            int flags) {
8355        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8356
8357        // reader
8358        synchronized (mPackages) {
8359            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8360            while (i.hasNext()) {
8361                final PackageParser.Instrumentation p = i.next();
8362                if (targetPackage == null
8363                        || targetPackage.equals(p.info.targetPackage)) {
8364                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8365                            flags);
8366                    if (ii != null) {
8367                        finalList.add(ii);
8368                    }
8369                }
8370            }
8371        }
8372
8373        return finalList;
8374    }
8375
8376    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8377        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8378        try {
8379            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8380        } finally {
8381            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8382        }
8383    }
8384
8385    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8386        final File[] files = scanDir.listFiles();
8387        if (ArrayUtils.isEmpty(files)) {
8388            Log.d(TAG, "No files in app dir " + scanDir);
8389            return;
8390        }
8391
8392        if (DEBUG_PACKAGE_SCANNING) {
8393            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8394                    + " flags=0x" + Integer.toHexString(parseFlags));
8395        }
8396        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8397                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8398                mParallelPackageParserCallback)) {
8399            // Submit files for parsing in parallel
8400            int fileCount = 0;
8401            for (File file : files) {
8402                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8403                        && !PackageInstallerService.isStageName(file.getName());
8404                if (!isPackage) {
8405                    // Ignore entries which are not packages
8406                    continue;
8407                }
8408                parallelPackageParser.submit(file, parseFlags);
8409                fileCount++;
8410            }
8411
8412            // Process results one by one
8413            for (; fileCount > 0; fileCount--) {
8414                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8415                Throwable throwable = parseResult.throwable;
8416                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8417
8418                if (throwable == null) {
8419                    // TODO(toddke): move lower in the scan chain
8420                    // Static shared libraries have synthetic package names
8421                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8422                        renameStaticSharedLibraryPackage(parseResult.pkg);
8423                    }
8424                    try {
8425                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8426                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8427                                    currentTime, null);
8428                        }
8429                    } catch (PackageManagerException e) {
8430                        errorCode = e.error;
8431                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8432                    }
8433                } else if (throwable instanceof PackageParser.PackageParserException) {
8434                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8435                            throwable;
8436                    errorCode = e.error;
8437                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8438                } else {
8439                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8440                            + parseResult.scanFile, throwable);
8441                }
8442
8443                // Delete invalid userdata apps
8444                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8445                        errorCode != PackageManager.INSTALL_SUCCEEDED) {
8446                    logCriticalInfo(Log.WARN,
8447                            "Deleting invalid package at " + parseResult.scanFile);
8448                    removeCodePathLI(parseResult.scanFile);
8449                }
8450            }
8451        }
8452    }
8453
8454    public static void reportSettingsProblem(int priority, String msg) {
8455        logCriticalInfo(priority, msg);
8456    }
8457
8458    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8459            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8460        // When upgrading from pre-N MR1, verify the package time stamp using the package
8461        // directory and not the APK file.
8462        final long lastModifiedTime = mIsPreNMR1Upgrade
8463                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8464        if (ps != null && !forceCollect
8465                && ps.codePathString.equals(pkg.codePath)
8466                && ps.timeStamp == lastModifiedTime
8467                && !isCompatSignatureUpdateNeeded(pkg)
8468                && !isRecoverSignatureUpdateNeeded(pkg)) {
8469            if (ps.signatures.mSigningDetails.signatures != null
8470                    && ps.signatures.mSigningDetails.signatures.length != 0
8471                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8472                            != SignatureSchemeVersion.UNKNOWN) {
8473                // Optimization: reuse the existing cached signing data
8474                // if the package appears to be unchanged.
8475                pkg.mSigningDetails =
8476                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8477                return;
8478            }
8479
8480            Slog.w(TAG, "PackageSetting for " + ps.name
8481                    + " is missing signatures.  Collecting certs again to recover them.");
8482        } else {
8483            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8484                    (forceCollect ? " (forced)" : ""));
8485        }
8486
8487        try {
8488            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8489            PackageParser.collectCertificates(pkg, skipVerify);
8490        } catch (PackageParserException e) {
8491            throw PackageManagerException.from(e);
8492        } finally {
8493            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8494        }
8495    }
8496
8497    /**
8498     * Clear the package profile if this was an upgrade and the package
8499     * version was updated.
8500     */
8501    private void maybeClearProfilesForUpgradesLI(
8502            @Nullable PackageSetting originalPkgSetting,
8503            @NonNull PackageParser.Package currentPkg) {
8504        if (originalPkgSetting == null || !isUpgrade()) {
8505          return;
8506        }
8507        if (originalPkgSetting.versionCode == currentPkg.mVersionCode) {
8508          return;
8509        }
8510
8511        clearAppProfilesLIF(currentPkg, UserHandle.USER_ALL);
8512        if (DEBUG_INSTALL) {
8513            Slog.d(TAG, originalPkgSetting.name
8514                  + " clear profile due to version change "
8515                  + originalPkgSetting.versionCode + " != "
8516                  + currentPkg.mVersionCode);
8517        }
8518    }
8519
8520    /**
8521     *  Traces a package scan.
8522     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8523     */
8524    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8525            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8526        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8527        try {
8528            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8529        } finally {
8530            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8531        }
8532    }
8533
8534    /**
8535     *  Scans a package and returns the newly parsed package.
8536     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8537     */
8538    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8539            long currentTime, UserHandle user) throws PackageManagerException {
8540        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8541        PackageParser pp = new PackageParser();
8542        pp.setSeparateProcesses(mSeparateProcesses);
8543        pp.setOnlyCoreApps(mOnlyCore);
8544        pp.setDisplayMetrics(mMetrics);
8545        pp.setCallback(mPackageParserCallback);
8546
8547        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8548        final PackageParser.Package pkg;
8549        try {
8550            pkg = pp.parsePackage(scanFile, parseFlags);
8551        } catch (PackageParserException e) {
8552            throw PackageManagerException.from(e);
8553        } finally {
8554            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8555        }
8556
8557        // Static shared libraries have synthetic package names
8558        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8559            renameStaticSharedLibraryPackage(pkg);
8560        }
8561
8562        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8563    }
8564
8565    /**
8566     *  Scans a package and returns the newly parsed package.
8567     *  @throws PackageManagerException on a parse error.
8568     */
8569    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8570            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8571            @Nullable UserHandle user)
8572                    throws PackageManagerException {
8573        // If the package has children and this is the first dive in the function
8574        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8575        // packages (parent and children) would be successfully scanned before the
8576        // actual scan since scanning mutates internal state and we want to atomically
8577        // install the package and its children.
8578        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8579            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8580                scanFlags |= SCAN_CHECK_ONLY;
8581            }
8582        } else {
8583            scanFlags &= ~SCAN_CHECK_ONLY;
8584        }
8585
8586        // Scan the parent
8587        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8588                scanFlags, currentTime, user);
8589
8590        // Scan the children
8591        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8592        for (int i = 0; i < childCount; i++) {
8593            PackageParser.Package childPackage = pkg.childPackages.get(i);
8594            addForInitLI(childPackage, parseFlags, scanFlags,
8595                    currentTime, user);
8596        }
8597
8598
8599        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8600            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8601        }
8602
8603        return scannedPkg;
8604    }
8605
8606    /**
8607     * Returns if full apk verification can be skipped for the whole package, including the splits.
8608     */
8609    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8610        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8611            return false;
8612        }
8613        // TODO: Allow base and splits to be verified individually.
8614        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8615            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8616                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8617                    return false;
8618                }
8619            }
8620        }
8621        return true;
8622    }
8623
8624    /**
8625     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8626     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8627     * match one in a trusted source, and should be done separately.
8628     */
8629    private boolean canSkipFullApkVerification(String apkPath) {
8630        byte[] rootHashObserved = null;
8631        try {
8632            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8633            if (rootHashObserved == null) {
8634                return false;  // APK does not contain Merkle tree root hash.
8635            }
8636            synchronized (mInstallLock) {
8637                // Returns whether the observed root hash matches what kernel has.
8638                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8639                return true;
8640            }
8641        } catch (InstallerException | IOException | DigestException |
8642                NoSuchAlgorithmException e) {
8643            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8644        }
8645        return false;
8646    }
8647
8648    /**
8649     * Adds a new package to the internal data structures during platform initialization.
8650     * <p>After adding, the package is known to the system and available for querying.
8651     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8652     * etc...], additional checks are performed. Basic verification [such as ensuring
8653     * matching signatures, checking version codes, etc...] occurs if the package is
8654     * identical to a previously known package. If the package fails a signature check,
8655     * the version installed on /data will be removed. If the version of the new package
8656     * is less than or equal than the version on /data, it will be ignored.
8657     * <p>Regardless of the package location, the results are applied to the internal
8658     * structures and the package is made available to the rest of the system.
8659     * <p>NOTE: The return value should be removed. It's the passed in package object.
8660     */
8661    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8662            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8663            @Nullable UserHandle user)
8664                    throws PackageManagerException {
8665        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8666        final String renamedPkgName;
8667        final PackageSetting disabledPkgSetting;
8668        final boolean isSystemPkgUpdated;
8669        final boolean pkgAlreadyExists;
8670        PackageSetting pkgSetting;
8671
8672        // NOTE: installPackageLI() has the same code to setup the package's
8673        // application info. This probably should be done lower in the call
8674        // stack [such as scanPackageOnly()]. However, we verify the application
8675        // info prior to that [in scanPackageNew()] and thus have to setup
8676        // the application info early.
8677        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8678        pkg.setApplicationInfoCodePath(pkg.codePath);
8679        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8680        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8681        pkg.setApplicationInfoResourcePath(pkg.codePath);
8682        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8683        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8684
8685        synchronized (mPackages) {
8686            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8687            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8688            if (realPkgName != null) {
8689                ensurePackageRenamed(pkg, renamedPkgName);
8690            }
8691            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8692            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8693            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8694            pkgAlreadyExists = pkgSetting != null;
8695            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8696            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8697            isSystemPkgUpdated = disabledPkgSetting != null;
8698
8699            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8700                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8701            }
8702
8703            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8704                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8705                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8706                    : null;
8707            if (DEBUG_PACKAGE_SCANNING
8708                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8709                    && sharedUserSetting != null) {
8710                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8711                        + " (uid=" + sharedUserSetting.userId + "):"
8712                        + " packages=" + sharedUserSetting.packages);
8713            }
8714
8715            if (scanSystemPartition) {
8716                // Potentially prune child packages. If the application on the /system
8717                // partition has been updated via OTA, but, is still disabled by a
8718                // version on /data, cycle through all of its children packages and
8719                // remove children that are no longer defined.
8720                if (isSystemPkgUpdated) {
8721                    final int scannedChildCount = (pkg.childPackages != null)
8722                            ? pkg.childPackages.size() : 0;
8723                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8724                            ? disabledPkgSetting.childPackageNames.size() : 0;
8725                    for (int i = 0; i < disabledChildCount; i++) {
8726                        String disabledChildPackageName =
8727                                disabledPkgSetting.childPackageNames.get(i);
8728                        boolean disabledPackageAvailable = false;
8729                        for (int j = 0; j < scannedChildCount; j++) {
8730                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8731                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8732                                disabledPackageAvailable = true;
8733                                break;
8734                            }
8735                        }
8736                        if (!disabledPackageAvailable) {
8737                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8738                        }
8739                    }
8740                    // we're updating the disabled package, so, scan it as the package setting
8741                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null,
8742                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8743                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8744                            (pkg == mPlatformPackage), user);
8745                    applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
8746                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8747                }
8748            }
8749        }
8750
8751        final boolean newPkgChangedPaths =
8752                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8753        final boolean newPkgVersionGreater =
8754                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8755        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8756                && newPkgChangedPaths && newPkgVersionGreater;
8757        if (isSystemPkgBetter) {
8758            // The version of the application on /system is greater than the version on
8759            // /data. Switch back to the application on /system.
8760            // It's safe to assume the application on /system will correctly scan. If not,
8761            // there won't be a working copy of the application.
8762            synchronized (mPackages) {
8763                // just remove the loaded entries from package lists
8764                mPackages.remove(pkgSetting.name);
8765            }
8766
8767            logCriticalInfo(Log.WARN,
8768                    "System package updated;"
8769                    + " name: " + pkgSetting.name
8770                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8771                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8772
8773            final InstallArgs args = createInstallArgsForExisting(
8774                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8775                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8776            args.cleanUpResourcesLI();
8777            synchronized (mPackages) {
8778                mSettings.enableSystemPackageLPw(pkgSetting.name);
8779            }
8780        }
8781
8782        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8783            // The version of the application on the /system partition is less than or
8784            // equal to the version on the /data partition. Throw an exception and use
8785            // the application already installed on the /data partition.
8786            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8787                    + pkg.codePath + " ignored: updated version " + pkgSetting.versionCode
8788                    + " better than this " + pkg.getLongVersionCode());
8789        }
8790
8791        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8792        // force re-collecting certificate.
8793        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8794                disabledPkgSetting);
8795        // Full APK verification can be skipped during certificate collection, only if the file is
8796        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8797        // cases, only data in Signing Block is verified instead of the whole file.
8798        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8799                (forceCollect && canSkipFullPackageVerification(pkg));
8800        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8801
8802        // Reset profile if the application version is changed
8803        maybeClearProfilesForUpgradesLI(pkgSetting, pkg);
8804
8805        /*
8806         * A new system app appeared, but we already had a non-system one of the
8807         * same name installed earlier.
8808         */
8809        boolean shouldHideSystemApp = false;
8810        // A new application appeared on /system, but, we already have a copy of
8811        // the application installed on /data.
8812        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8813                && !pkgSetting.isSystem()) {
8814
8815            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8816                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
8817                            && !pkgSetting.signatures.mSigningDetails.checkCapability(
8818                                    pkg.mSigningDetails,
8819                                    PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
8820                logCriticalInfo(Log.WARN,
8821                        "System package signature mismatch;"
8822                        + " name: " + pkgSetting.name);
8823                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8824                        "scanPackageInternalLI")) {
8825                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8826                }
8827                pkgSetting = null;
8828            } else if (newPkgVersionGreater) {
8829                // The application on /system is newer than the application on /data.
8830                // Simply remove the application on /data [keeping application data]
8831                // and replace it with the version on /system.
8832                logCriticalInfo(Log.WARN,
8833                        "System package enabled;"
8834                        + " name: " + pkgSetting.name
8835                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8836                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8837                InstallArgs args = createInstallArgsForExisting(
8838                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8839                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8840                synchronized (mInstallLock) {
8841                    args.cleanUpResourcesLI();
8842                }
8843            } else {
8844                // The application on /system is older than the application on /data. Hide
8845                // the application on /system and the version on /data will be scanned later
8846                // and re-added like an update.
8847                shouldHideSystemApp = true;
8848                logCriticalInfo(Log.INFO,
8849                        "System package disabled;"
8850                        + " name: " + pkgSetting.name
8851                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8852                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8853            }
8854        }
8855
8856        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8857                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8858
8859        if (shouldHideSystemApp) {
8860            synchronized (mPackages) {
8861                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8862            }
8863        }
8864        return scannedPkg;
8865    }
8866
8867    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8868        // Derive the new package synthetic package name
8869        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8870                + pkg.staticSharedLibVersion);
8871    }
8872
8873    private static String fixProcessName(String defProcessName,
8874            String processName) {
8875        if (processName == null) {
8876            return defProcessName;
8877        }
8878        return processName;
8879    }
8880
8881    /**
8882     * Enforces that only the system UID or root's UID can call a method exposed
8883     * via Binder.
8884     *
8885     * @param message used as message if SecurityException is thrown
8886     * @throws SecurityException if the caller is not system or root
8887     */
8888    private static final void enforceSystemOrRoot(String message) {
8889        final int uid = Binder.getCallingUid();
8890        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8891            throw new SecurityException(message);
8892        }
8893    }
8894
8895    @Override
8896    public void performFstrimIfNeeded() {
8897        enforceSystemOrRoot("Only the system can request fstrim");
8898
8899        // Before everything else, see whether we need to fstrim.
8900        try {
8901            IStorageManager sm = PackageHelper.getStorageManager();
8902            if (sm != null) {
8903                boolean doTrim = false;
8904                final long interval = android.provider.Settings.Global.getLong(
8905                        mContext.getContentResolver(),
8906                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8907                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8908                if (interval > 0) {
8909                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8910                    if (timeSinceLast > interval) {
8911                        doTrim = true;
8912                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8913                                + "; running immediately");
8914                    }
8915                }
8916                if (doTrim) {
8917                    final boolean dexOptDialogShown;
8918                    synchronized (mPackages) {
8919                        dexOptDialogShown = mDexOptDialogShown;
8920                    }
8921                    if (!isFirstBoot() && dexOptDialogShown) {
8922                        try {
8923                            ActivityManager.getService().showBootMessage(
8924                                    mContext.getResources().getString(
8925                                            R.string.android_upgrading_fstrim), true);
8926                        } catch (RemoteException e) {
8927                        }
8928                    }
8929                    sm.runMaintenance();
8930                }
8931            } else {
8932                Slog.e(TAG, "storageManager service unavailable!");
8933            }
8934        } catch (RemoteException e) {
8935            // Can't happen; StorageManagerService is local
8936        }
8937    }
8938
8939    @Override
8940    public void updatePackagesIfNeeded() {
8941        enforceSystemOrRoot("Only the system can request package update");
8942
8943        // We need to re-extract after an OTA.
8944        boolean causeUpgrade = isUpgrade();
8945
8946        // First boot or factory reset.
8947        // Note: we also handle devices that are upgrading to N right now as if it is their
8948        //       first boot, as they do not have profile data.
8949        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8950
8951        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8952        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8953
8954        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8955            return;
8956        }
8957
8958        List<PackageParser.Package> pkgs;
8959        synchronized (mPackages) {
8960            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8961        }
8962
8963        final long startTime = System.nanoTime();
8964        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8965                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8966                    false /* bootComplete */);
8967
8968        final int elapsedTimeSeconds =
8969                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8970
8971        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8972        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8973        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8974        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8975        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8976    }
8977
8978    /*
8979     * Return the prebuilt profile path given a package base code path.
8980     */
8981    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8982        return pkg.baseCodePath + ".prof";
8983    }
8984
8985    /**
8986     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8987     * containing statistics about the invocation. The array consists of three elements,
8988     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8989     * and {@code numberOfPackagesFailed}.
8990     */
8991    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8992            final int compilationReason, boolean bootComplete) {
8993
8994        int numberOfPackagesVisited = 0;
8995        int numberOfPackagesOptimized = 0;
8996        int numberOfPackagesSkipped = 0;
8997        int numberOfPackagesFailed = 0;
8998        final int numberOfPackagesToDexopt = pkgs.size();
8999
9000        for (PackageParser.Package pkg : pkgs) {
9001            numberOfPackagesVisited++;
9002
9003            boolean useProfileForDexopt = false;
9004
9005            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9006                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9007                // that are already compiled.
9008                File profileFile = new File(getPrebuildProfilePath(pkg));
9009                // Copy profile if it exists.
9010                if (profileFile.exists()) {
9011                    try {
9012                        // We could also do this lazily before calling dexopt in
9013                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9014                        // is that we don't have a good way to say "do this only once".
9015                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9016                                pkg.applicationInfo.uid, pkg.packageName,
9017                                ArtManager.getProfileName(null))) {
9018                            Log.e(TAG, "Installer failed to copy system profile!");
9019                        } else {
9020                            // Disabled as this causes speed-profile compilation during first boot
9021                            // even if things are already compiled.
9022                            // useProfileForDexopt = true;
9023                        }
9024                    } catch (Exception e) {
9025                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9026                                e);
9027                    }
9028                } else {
9029                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9030                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9031                    // minimize the number off apps being speed-profile compiled during first boot.
9032                    // The other paths will not change the filter.
9033                    if (disabledPs != null && disabledPs.pkg.isStub) {
9034                        // The package is the stub one, remove the stub suffix to get the normal
9035                        // package and APK names.
9036                        String systemProfilePath =
9037                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9038                        profileFile = new File(systemProfilePath);
9039                        // If we have a profile for a compressed APK, copy it to the reference
9040                        // location.
9041                        // Note that copying the profile here will cause it to override the
9042                        // reference profile every OTA even though the existing reference profile
9043                        // may have more data. We can't copy during decompression since the
9044                        // directories are not set up at that point.
9045                        if (profileFile.exists()) {
9046                            try {
9047                                // We could also do this lazily before calling dexopt in
9048                                // PackageDexOptimizer to prevent this happening on first boot. The
9049                                // issue is that we don't have a good way to say "do this only
9050                                // once".
9051                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9052                                        pkg.applicationInfo.uid, pkg.packageName,
9053                                        ArtManager.getProfileName(null))) {
9054                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9055                                } else {
9056                                    useProfileForDexopt = true;
9057                                }
9058                            } catch (Exception e) {
9059                                Log.e(TAG, "Failed to copy profile " +
9060                                        profileFile.getAbsolutePath() + " ", e);
9061                            }
9062                        }
9063                    }
9064                }
9065            }
9066
9067            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9068                if (DEBUG_DEXOPT) {
9069                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9070                }
9071                numberOfPackagesSkipped++;
9072                continue;
9073            }
9074
9075            if (DEBUG_DEXOPT) {
9076                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9077                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9078            }
9079
9080            if (showDialog) {
9081                try {
9082                    ActivityManager.getService().showBootMessage(
9083                            mContext.getResources().getString(R.string.android_upgrading_apk,
9084                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9085                } catch (RemoteException e) {
9086                }
9087                synchronized (mPackages) {
9088                    mDexOptDialogShown = true;
9089                }
9090            }
9091
9092            int pkgCompilationReason = compilationReason;
9093            if (useProfileForDexopt) {
9094                // Use background dexopt mode to try and use the profile. Note that this does not
9095                // guarantee usage of the profile.
9096                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9097            }
9098
9099            // checkProfiles is false to avoid merging profiles during boot which
9100            // might interfere with background compilation (b/28612421).
9101            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9102            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9103            // trade-off worth doing to save boot time work.
9104            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9105            if (compilationReason == REASON_FIRST_BOOT) {
9106                // TODO: This doesn't cover the upgrade case, we should check for this too.
9107                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9108            }
9109            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9110                    pkg.packageName,
9111                    pkgCompilationReason,
9112                    dexoptFlags));
9113
9114            switch (primaryDexOptStaus) {
9115                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9116                    numberOfPackagesOptimized++;
9117                    break;
9118                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9119                    numberOfPackagesSkipped++;
9120                    break;
9121                case PackageDexOptimizer.DEX_OPT_FAILED:
9122                    numberOfPackagesFailed++;
9123                    break;
9124                default:
9125                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9126                    break;
9127            }
9128        }
9129
9130        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9131                numberOfPackagesFailed };
9132    }
9133
9134    @Override
9135    public void notifyPackageUse(String packageName, int reason) {
9136        synchronized (mPackages) {
9137            final int callingUid = Binder.getCallingUid();
9138            final int callingUserId = UserHandle.getUserId(callingUid);
9139            if (getInstantAppPackageName(callingUid) != null) {
9140                if (!isCallerSameApp(packageName, callingUid)) {
9141                    return;
9142                }
9143            } else {
9144                if (isInstantApp(packageName, callingUserId)) {
9145                    return;
9146                }
9147            }
9148            notifyPackageUseLocked(packageName, reason);
9149        }
9150    }
9151
9152    @GuardedBy("mPackages")
9153    private void notifyPackageUseLocked(String packageName, int reason) {
9154        final PackageParser.Package p = mPackages.get(packageName);
9155        if (p == null) {
9156            return;
9157        }
9158        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9159    }
9160
9161    @Override
9162    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9163            List<String> classPaths, String loaderIsa) {
9164        int userId = UserHandle.getCallingUserId();
9165        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9166        if (ai == null) {
9167            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9168                + loadingPackageName + ", user=" + userId);
9169            return;
9170        }
9171        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9172    }
9173
9174    @Override
9175    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9176            IDexModuleRegisterCallback callback) {
9177        int userId = UserHandle.getCallingUserId();
9178        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9179        DexManager.RegisterDexModuleResult result;
9180        if (ai == null) {
9181            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9182                     " calling user. package=" + packageName + ", user=" + userId);
9183            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9184        } else {
9185            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9186        }
9187
9188        if (callback != null) {
9189            mHandler.post(() -> {
9190                try {
9191                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9192                } catch (RemoteException e) {
9193                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9194                }
9195            });
9196        }
9197    }
9198
9199    /**
9200     * Ask the package manager to perform a dex-opt with the given compiler filter.
9201     *
9202     * Note: exposed only for the shell command to allow moving packages explicitly to a
9203     *       definite state.
9204     */
9205    @Override
9206    public boolean performDexOptMode(String packageName,
9207            boolean checkProfiles, String targetCompilerFilter, boolean force,
9208            boolean bootComplete, String splitName) {
9209        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9210                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9211                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9212        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9213                targetCompilerFilter, splitName, flags));
9214    }
9215
9216    /**
9217     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9218     * secondary dex files belonging to the given package.
9219     *
9220     * Note: exposed only for the shell command to allow moving packages explicitly to a
9221     *       definite state.
9222     */
9223    @Override
9224    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9225            boolean force) {
9226        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9227                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9228                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9229                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9230        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9231    }
9232
9233    /*package*/ boolean performDexOpt(DexoptOptions options) {
9234        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9235            return false;
9236        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9237            return false;
9238        }
9239
9240        if (options.isDexoptOnlySecondaryDex()) {
9241            return mDexManager.dexoptSecondaryDex(options);
9242        } else {
9243            int dexoptStatus = performDexOptWithStatus(options);
9244            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9245        }
9246    }
9247
9248    /**
9249     * Perform dexopt on the given package and return one of following result:
9250     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9251     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9252     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9253     */
9254    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9255        return performDexOptTraced(options);
9256    }
9257
9258    private int performDexOptTraced(DexoptOptions options) {
9259        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9260        try {
9261            return performDexOptInternal(options);
9262        } finally {
9263            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9264        }
9265    }
9266
9267    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9268    // if the package can now be considered up to date for the given filter.
9269    private int performDexOptInternal(DexoptOptions options) {
9270        PackageParser.Package p;
9271        synchronized (mPackages) {
9272            p = mPackages.get(options.getPackageName());
9273            if (p == null) {
9274                // Package could not be found. Report failure.
9275                return PackageDexOptimizer.DEX_OPT_FAILED;
9276            }
9277            mPackageUsage.maybeWriteAsync(mPackages);
9278            mCompilerStats.maybeWriteAsync();
9279        }
9280        long callingId = Binder.clearCallingIdentity();
9281        try {
9282            synchronized (mInstallLock) {
9283                return performDexOptInternalWithDependenciesLI(p, options);
9284            }
9285        } finally {
9286            Binder.restoreCallingIdentity(callingId);
9287        }
9288    }
9289
9290    public ArraySet<String> getOptimizablePackages() {
9291        ArraySet<String> pkgs = new ArraySet<String>();
9292        synchronized (mPackages) {
9293            for (PackageParser.Package p : mPackages.values()) {
9294                if (PackageDexOptimizer.canOptimizePackage(p)) {
9295                    pkgs.add(p.packageName);
9296                }
9297            }
9298        }
9299        return pkgs;
9300    }
9301
9302    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9303            DexoptOptions options) {
9304        // Select the dex optimizer based on the force parameter.
9305        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9306        //       allocate an object here.
9307        PackageDexOptimizer pdo = options.isForce()
9308                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9309                : mPackageDexOptimizer;
9310
9311        // Dexopt all dependencies first. Note: we ignore the return value and march on
9312        // on errors.
9313        // Note that we are going to call performDexOpt on those libraries as many times as
9314        // they are referenced in packages. When we do a batch of performDexOpt (for example
9315        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9316        // and the first package that uses the library will dexopt it. The
9317        // others will see that the compiled code for the library is up to date.
9318        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9319        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9320        if (!deps.isEmpty()) {
9321            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9322                    options.getCompilationReason(), options.getCompilerFilter(),
9323                    options.getSplitName(),
9324                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9325            for (PackageParser.Package depPackage : deps) {
9326                // TODO: Analyze and investigate if we (should) profile libraries.
9327                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9328                        getOrCreateCompilerPackageStats(depPackage),
9329                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9330            }
9331        }
9332        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9333                getOrCreateCompilerPackageStats(p),
9334                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9335    }
9336
9337    /**
9338     * Reconcile the information we have about the secondary dex files belonging to
9339     * {@code packagName} and the actual dex files. For all dex files that were
9340     * deleted, update the internal records and delete the generated oat files.
9341     */
9342    @Override
9343    public void reconcileSecondaryDexFiles(String packageName) {
9344        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9345            return;
9346        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9347            return;
9348        }
9349        mDexManager.reconcileSecondaryDexFiles(packageName);
9350    }
9351
9352    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9353    // a reference there.
9354    /*package*/ DexManager getDexManager() {
9355        return mDexManager;
9356    }
9357
9358    /**
9359     * Execute the background dexopt job immediately.
9360     */
9361    @Override
9362    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9363        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9364            return false;
9365        }
9366        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9367    }
9368
9369    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9370        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9371                || p.usesStaticLibraries != null) {
9372            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9373            Set<String> collectedNames = new HashSet<>();
9374            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9375
9376            retValue.remove(p);
9377
9378            return retValue;
9379        } else {
9380            return Collections.emptyList();
9381        }
9382    }
9383
9384    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9385            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9386        if (!collectedNames.contains(p.packageName)) {
9387            collectedNames.add(p.packageName);
9388            collected.add(p);
9389
9390            if (p.usesLibraries != null) {
9391                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9392                        null, collected, collectedNames);
9393            }
9394            if (p.usesOptionalLibraries != null) {
9395                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9396                        null, collected, collectedNames);
9397            }
9398            if (p.usesStaticLibraries != null) {
9399                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9400                        p.usesStaticLibrariesVersions, collected, collectedNames);
9401            }
9402        }
9403    }
9404
9405    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9406            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9407        final int libNameCount = libs.size();
9408        for (int i = 0; i < libNameCount; i++) {
9409            String libName = libs.get(i);
9410            long version = (versions != null && versions.length == libNameCount)
9411                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9412            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9413            if (libPkg != null) {
9414                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9415            }
9416        }
9417    }
9418
9419    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9420        synchronized (mPackages) {
9421            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9422            if (libEntry != null) {
9423                return mPackages.get(libEntry.apk);
9424            }
9425            return null;
9426        }
9427    }
9428
9429    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9430        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9431        if (versionedLib == null) {
9432            return null;
9433        }
9434        return versionedLib.get(version);
9435    }
9436
9437    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9438        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9439                pkg.staticSharedLibName);
9440        if (versionedLib == null) {
9441            return null;
9442        }
9443        long previousLibVersion = -1;
9444        final int versionCount = versionedLib.size();
9445        for (int i = 0; i < versionCount; i++) {
9446            final long libVersion = versionedLib.keyAt(i);
9447            if (libVersion < pkg.staticSharedLibVersion) {
9448                previousLibVersion = Math.max(previousLibVersion, libVersion);
9449            }
9450        }
9451        if (previousLibVersion >= 0) {
9452            return versionedLib.get(previousLibVersion);
9453        }
9454        return null;
9455    }
9456
9457    public void shutdown() {
9458        mPackageUsage.writeNow(mPackages);
9459        mCompilerStats.writeNow();
9460        mDexManager.writePackageDexUsageNow();
9461
9462        // This is the last chance to write out pending restriction settings
9463        synchronized (mPackages) {
9464            if (mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
9465                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
9466                for (int userId : mDirtyUsers) {
9467                    mSettings.writePackageRestrictionsLPr(userId);
9468                }
9469                mDirtyUsers.clear();
9470            }
9471        }
9472    }
9473
9474    @Override
9475    public void dumpProfiles(String packageName) {
9476        PackageParser.Package pkg;
9477        synchronized (mPackages) {
9478            pkg = mPackages.get(packageName);
9479            if (pkg == null) {
9480                throw new IllegalArgumentException("Unknown package: " + packageName);
9481            }
9482        }
9483        /* Only the shell, root, or the app user should be able to dump profiles. */
9484        int callingUid = Binder.getCallingUid();
9485        if (callingUid != Process.SHELL_UID &&
9486            callingUid != Process.ROOT_UID &&
9487            callingUid != pkg.applicationInfo.uid) {
9488            throw new SecurityException("dumpProfiles");
9489        }
9490
9491        synchronized (mInstallLock) {
9492            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9493            mArtManagerService.dumpProfiles(pkg);
9494            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9495        }
9496    }
9497
9498    @Override
9499    public void forceDexOpt(String packageName) {
9500        enforceSystemOrRoot("forceDexOpt");
9501
9502        PackageParser.Package pkg;
9503        synchronized (mPackages) {
9504            pkg = mPackages.get(packageName);
9505            if (pkg == null) {
9506                throw new IllegalArgumentException("Unknown package: " + packageName);
9507            }
9508        }
9509
9510        synchronized (mInstallLock) {
9511            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9512
9513            // Whoever is calling forceDexOpt wants a compiled package.
9514            // Don't use profiles since that may cause compilation to be skipped.
9515            final int res = performDexOptInternalWithDependenciesLI(
9516                    pkg,
9517                    new DexoptOptions(packageName,
9518                            getDefaultCompilerFilter(),
9519                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9520
9521            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9522            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9523                throw new IllegalStateException("Failed to dexopt: " + res);
9524            }
9525        }
9526    }
9527
9528    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9529        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9530            Slog.w(TAG, "Unable to update from " + oldPkg.name
9531                    + " to " + newPkg.packageName
9532                    + ": old package not in system partition");
9533            return false;
9534        } else if (mPackages.get(oldPkg.name) != null) {
9535            Slog.w(TAG, "Unable to update from " + oldPkg.name
9536                    + " to " + newPkg.packageName
9537                    + ": old package still exists");
9538            return false;
9539        }
9540        return true;
9541    }
9542
9543    void removeCodePathLI(File codePath) {
9544        if (codePath.isDirectory()) {
9545            try {
9546                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9547            } catch (InstallerException e) {
9548                Slog.w(TAG, "Failed to remove code path", e);
9549            }
9550        } else {
9551            codePath.delete();
9552        }
9553    }
9554
9555    private int[] resolveUserIds(int userId) {
9556        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9557    }
9558
9559    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9560        if (pkg == null) {
9561            Slog.wtf(TAG, "Package was null!", new Throwable());
9562            return;
9563        }
9564        clearAppDataLeafLIF(pkg, userId, flags);
9565        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9566        for (int i = 0; i < childCount; i++) {
9567            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9568        }
9569
9570        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9571    }
9572
9573    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9574        final PackageSetting ps;
9575        synchronized (mPackages) {
9576            ps = mSettings.mPackages.get(pkg.packageName);
9577        }
9578        for (int realUserId : resolveUserIds(userId)) {
9579            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9580            try {
9581                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9582                        ceDataInode);
9583            } catch (InstallerException e) {
9584                Slog.w(TAG, String.valueOf(e));
9585            }
9586        }
9587    }
9588
9589    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9590        if (pkg == null) {
9591            Slog.wtf(TAG, "Package was null!", new Throwable());
9592            return;
9593        }
9594        destroyAppDataLeafLIF(pkg, userId, flags);
9595        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9596        for (int i = 0; i < childCount; i++) {
9597            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9598        }
9599    }
9600
9601    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9602        final PackageSetting ps;
9603        synchronized (mPackages) {
9604            ps = mSettings.mPackages.get(pkg.packageName);
9605        }
9606        for (int realUserId : resolveUserIds(userId)) {
9607            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9608            try {
9609                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9610                        ceDataInode);
9611            } catch (InstallerException e) {
9612                Slog.w(TAG, String.valueOf(e));
9613            }
9614            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9615        }
9616    }
9617
9618    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9619        if (pkg == null) {
9620            Slog.wtf(TAG, "Package was null!", new Throwable());
9621            return;
9622        }
9623        destroyAppProfilesLeafLIF(pkg);
9624        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9625        for (int i = 0; i < childCount; i++) {
9626            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9627        }
9628    }
9629
9630    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9631        try {
9632            mInstaller.destroyAppProfiles(pkg.packageName);
9633        } catch (InstallerException e) {
9634            Slog.w(TAG, String.valueOf(e));
9635        }
9636    }
9637
9638    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9639        if (pkg == null) {
9640            Slog.wtf(TAG, "Package was null!", new Throwable());
9641            return;
9642        }
9643        mArtManagerService.clearAppProfiles(pkg);
9644        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9645        for (int i = 0; i < childCount; i++) {
9646            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9647        }
9648    }
9649
9650    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9651            long lastUpdateTime) {
9652        // Set parent install/update time
9653        PackageSetting ps = (PackageSetting) pkg.mExtras;
9654        if (ps != null) {
9655            ps.firstInstallTime = firstInstallTime;
9656            ps.lastUpdateTime = lastUpdateTime;
9657        }
9658        // Set children install/update time
9659        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9660        for (int i = 0; i < childCount; i++) {
9661            PackageParser.Package childPkg = pkg.childPackages.get(i);
9662            ps = (PackageSetting) childPkg.mExtras;
9663            if (ps != null) {
9664                ps.firstInstallTime = firstInstallTime;
9665                ps.lastUpdateTime = lastUpdateTime;
9666            }
9667        }
9668    }
9669
9670    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9671            SharedLibraryEntry file,
9672            PackageParser.Package changingLib) {
9673        if (file.path != null) {
9674            usesLibraryFiles.add(file.path);
9675            return;
9676        }
9677        PackageParser.Package p = mPackages.get(file.apk);
9678        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9679            // If we are doing this while in the middle of updating a library apk,
9680            // then we need to make sure to use that new apk for determining the
9681            // dependencies here.  (We haven't yet finished committing the new apk
9682            // to the package manager state.)
9683            if (p == null || p.packageName.equals(changingLib.packageName)) {
9684                p = changingLib;
9685            }
9686        }
9687        if (p != null) {
9688            usesLibraryFiles.addAll(p.getAllCodePaths());
9689            if (p.usesLibraryFiles != null) {
9690                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9691            }
9692        }
9693    }
9694
9695    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9696            PackageParser.Package changingLib) throws PackageManagerException {
9697        if (pkg == null) {
9698            return;
9699        }
9700        // The collection used here must maintain the order of addition (so
9701        // that libraries are searched in the correct order) and must have no
9702        // duplicates.
9703        Set<String> usesLibraryFiles = null;
9704        if (pkg.usesLibraries != null) {
9705            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9706                    null, null, pkg.packageName, changingLib, true,
9707                    pkg.applicationInfo.targetSdkVersion, null);
9708        }
9709        if (pkg.usesStaticLibraries != null) {
9710            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9711                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9712                    pkg.packageName, changingLib, true,
9713                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9714        }
9715        if (pkg.usesOptionalLibraries != null) {
9716            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9717                    null, null, pkg.packageName, changingLib, false,
9718                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9719        }
9720        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9721            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9722        } else {
9723            pkg.usesLibraryFiles = null;
9724        }
9725    }
9726
9727    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9728            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9729            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9730            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9731            throws PackageManagerException {
9732        final int libCount = requestedLibraries.size();
9733        for (int i = 0; i < libCount; i++) {
9734            final String libName = requestedLibraries.get(i);
9735            final long libVersion = requiredVersions != null ? requiredVersions[i]
9736                    : SharedLibraryInfo.VERSION_UNDEFINED;
9737            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9738            if (libEntry == null) {
9739                if (required) {
9740                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9741                            "Package " + packageName + " requires unavailable shared library "
9742                                    + libName + "; failing!");
9743                } else if (DEBUG_SHARED_LIBRARIES) {
9744                    Slog.i(TAG, "Package " + packageName
9745                            + " desires unavailable shared library "
9746                            + libName + "; ignoring!");
9747                }
9748            } else {
9749                if (requiredVersions != null && requiredCertDigests != null) {
9750                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9751                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9752                            "Package " + packageName + " requires unavailable static shared"
9753                                    + " library " + libName + " version "
9754                                    + libEntry.info.getLongVersion() + "; failing!");
9755                    }
9756
9757                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9758                    if (libPkg == null) {
9759                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9760                                "Package " + packageName + " requires unavailable static shared"
9761                                        + " library; failing!");
9762                    }
9763
9764                    final String[] expectedCertDigests = requiredCertDigests[i];
9765
9766
9767                    if (expectedCertDigests.length > 1) {
9768
9769                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9770                        final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1)
9771                                ? PackageUtils.computeSignaturesSha256Digests(
9772                                libPkg.mSigningDetails.signatures)
9773                                : PackageUtils.computeSignaturesSha256Digests(
9774                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9775
9776                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9777                        // target O we don't parse the "additional-certificate" tags similarly
9778                        // how we only consider all certs only for apps targeting O (see above).
9779                        // Therefore, the size check is safe to make.
9780                        if (expectedCertDigests.length != libCertDigests.length) {
9781                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9782                                    "Package " + packageName + " requires differently signed" +
9783                                            " static shared library; failing!");
9784                        }
9785
9786                        // Use a predictable order as signature order may vary
9787                        Arrays.sort(libCertDigests);
9788                        Arrays.sort(expectedCertDigests);
9789
9790                        final int certCount = libCertDigests.length;
9791                        for (int j = 0; j < certCount; j++) {
9792                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9793                                throw new PackageManagerException(
9794                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9795                                        "Package " + packageName + " requires differently signed" +
9796                                                " static shared library; failing!");
9797                            }
9798                        }
9799                    } else {
9800
9801                        // lib signing cert could have rotated beyond the one expected, check to see
9802                        // if the new one has been blessed by the old
9803                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9804                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9805                            throw new PackageManagerException(
9806                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9807                                    "Package " + packageName + " requires differently signed" +
9808                                            " static shared library; failing!");
9809                        }
9810                    }
9811                }
9812
9813                if (outUsedLibraries == null) {
9814                    // Use LinkedHashSet to preserve the order of files added to
9815                    // usesLibraryFiles while eliminating duplicates.
9816                    outUsedLibraries = new LinkedHashSet<>();
9817                }
9818                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9819            }
9820        }
9821        return outUsedLibraries;
9822    }
9823
9824    private static boolean hasString(List<String> list, List<String> which) {
9825        if (list == null) {
9826            return false;
9827        }
9828        for (int i=list.size()-1; i>=0; i--) {
9829            for (int j=which.size()-1; j>=0; j--) {
9830                if (which.get(j).equals(list.get(i))) {
9831                    return true;
9832                }
9833            }
9834        }
9835        return false;
9836    }
9837
9838    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9839            PackageParser.Package changingPkg) {
9840        ArrayList<PackageParser.Package> res = null;
9841        for (PackageParser.Package pkg : mPackages.values()) {
9842            if (changingPkg != null
9843                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9844                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9845                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9846                            changingPkg.staticSharedLibName)) {
9847                return null;
9848            }
9849            if (res == null) {
9850                res = new ArrayList<>();
9851            }
9852            res.add(pkg);
9853            try {
9854                updateSharedLibrariesLPr(pkg, changingPkg);
9855            } catch (PackageManagerException e) {
9856                // If a system app update or an app and a required lib missing we
9857                // delete the package and for updated system apps keep the data as
9858                // it is better for the user to reinstall than to be in an limbo
9859                // state. Also libs disappearing under an app should never happen
9860                // - just in case.
9861                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9862                    final int flags = pkg.isUpdatedSystemApp()
9863                            ? PackageManager.DELETE_KEEP_DATA : 0;
9864                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9865                            flags , null, true, null);
9866                }
9867                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9868            }
9869        }
9870        return res;
9871    }
9872
9873    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9874            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9875            @Nullable UserHandle user) throws PackageManagerException {
9876        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9877        // If the package has children and this is the first dive in the function
9878        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9879        // whether all packages (parent and children) would be successfully scanned
9880        // before the actual scan since scanning mutates internal state and we want
9881        // to atomically install the package and its children.
9882        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9883            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9884                scanFlags |= SCAN_CHECK_ONLY;
9885            }
9886        } else {
9887            scanFlags &= ~SCAN_CHECK_ONLY;
9888        }
9889
9890        final PackageParser.Package scannedPkg;
9891        try {
9892            // Scan the parent
9893            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9894            // Scan the children
9895            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9896            for (int i = 0; i < childCount; i++) {
9897                PackageParser.Package childPkg = pkg.childPackages.get(i);
9898                scanPackageNewLI(childPkg, parseFlags,
9899                        scanFlags, currentTime, user);
9900            }
9901        } finally {
9902            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9903        }
9904
9905        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9906            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9907        }
9908
9909        return scannedPkg;
9910    }
9911
9912    /** The result of a package scan. */
9913    private static class ScanResult {
9914        /** Whether or not the package scan was successful */
9915        public final boolean success;
9916        /**
9917         * The final package settings. This may be the same object passed in
9918         * the {@link ScanRequest}, but, with modified values.
9919         */
9920        @Nullable public final PackageSetting pkgSetting;
9921        /** ABI code paths that have changed in the package scan */
9922        @Nullable public final List<String> changedAbiCodePath;
9923        public ScanResult(
9924                boolean success,
9925                @Nullable PackageSetting pkgSetting,
9926                @Nullable List<String> changedAbiCodePath) {
9927            this.success = success;
9928            this.pkgSetting = pkgSetting;
9929            this.changedAbiCodePath = changedAbiCodePath;
9930        }
9931    }
9932
9933    /** A package to be scanned */
9934    private static class ScanRequest {
9935        /** The parsed package */
9936        @NonNull public final PackageParser.Package pkg;
9937        /** The package this package replaces */
9938        @Nullable public final PackageParser.Package oldPkg;
9939        /** Shared user settings, if the package has a shared user */
9940        @Nullable public final SharedUserSetting sharedUserSetting;
9941        /**
9942         * Package settings of the currently installed version.
9943         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9944         * during scan.
9945         */
9946        @Nullable public final PackageSetting pkgSetting;
9947        /** A copy of the settings for the currently installed version */
9948        @Nullable public final PackageSetting oldPkgSetting;
9949        /** Package settings for the disabled version on the /system partition */
9950        @Nullable public final PackageSetting disabledPkgSetting;
9951        /** Package settings for the installed version under its original package name */
9952        @Nullable public final PackageSetting originalPkgSetting;
9953        /** The real package name of a renamed application */
9954        @Nullable public final String realPkgName;
9955        public final @ParseFlags int parseFlags;
9956        public final @ScanFlags int scanFlags;
9957        /** The user for which the package is being scanned */
9958        @Nullable public final UserHandle user;
9959        /** Whether or not the platform package is being scanned */
9960        public final boolean isPlatformPackage;
9961        public ScanRequest(
9962                @NonNull PackageParser.Package pkg,
9963                @Nullable SharedUserSetting sharedUserSetting,
9964                @Nullable PackageParser.Package oldPkg,
9965                @Nullable PackageSetting pkgSetting,
9966                @Nullable PackageSetting disabledPkgSetting,
9967                @Nullable PackageSetting originalPkgSetting,
9968                @Nullable String realPkgName,
9969                @ParseFlags int parseFlags,
9970                @ScanFlags int scanFlags,
9971                boolean isPlatformPackage,
9972                @Nullable UserHandle user) {
9973            this.pkg = pkg;
9974            this.oldPkg = oldPkg;
9975            this.pkgSetting = pkgSetting;
9976            this.sharedUserSetting = sharedUserSetting;
9977            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9978            this.disabledPkgSetting = disabledPkgSetting;
9979            this.originalPkgSetting = originalPkgSetting;
9980            this.realPkgName = realPkgName;
9981            this.parseFlags = parseFlags;
9982            this.scanFlags = scanFlags;
9983            this.isPlatformPackage = isPlatformPackage;
9984            this.user = user;
9985        }
9986    }
9987
9988    /**
9989     * Returns the actual scan flags depending upon the state of the other settings.
9990     * <p>Updated system applications will not have the following flags set
9991     * by default and need to be adjusted after the fact:
9992     * <ul>
9993     * <li>{@link #SCAN_AS_SYSTEM}</li>
9994     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9995     * <li>{@link #SCAN_AS_OEM}</li>
9996     * <li>{@link #SCAN_AS_VENDOR}</li>
9997     * <li>{@link #SCAN_AS_PRODUCT}</li>
9998     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9999     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
10000     * </ul>
10001     */
10002    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
10003            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
10004            PackageParser.Package pkg) {
10005        if (disabledPkgSetting != null) {
10006            // updated system application, must at least have SCAN_AS_SYSTEM
10007            scanFlags |= SCAN_AS_SYSTEM;
10008            if ((disabledPkgSetting.pkgPrivateFlags
10009                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
10010                scanFlags |= SCAN_AS_PRIVILEGED;
10011            }
10012            if ((disabledPkgSetting.pkgPrivateFlags
10013                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
10014                scanFlags |= SCAN_AS_OEM;
10015            }
10016            if ((disabledPkgSetting.pkgPrivateFlags
10017                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
10018                scanFlags |= SCAN_AS_VENDOR;
10019            }
10020            if ((disabledPkgSetting.pkgPrivateFlags
10021                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
10022                scanFlags |= SCAN_AS_PRODUCT;
10023            }
10024        }
10025        if (pkgSetting != null) {
10026            final int userId = ((user == null) ? 0 : user.getIdentifier());
10027            if (pkgSetting.getInstantApp(userId)) {
10028                scanFlags |= SCAN_AS_INSTANT_APP;
10029            }
10030            if (pkgSetting.getVirtulalPreload(userId)) {
10031                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
10032            }
10033        }
10034
10035        // Scan as privileged apps that share a user with a priv-app.
10036        final boolean skipVendorPrivilegeScan = ((scanFlags & SCAN_AS_VENDOR) != 0)
10037                && SystemProperties.getInt("ro.vndk.version", 28) < 28;
10038        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0)
10039                && !pkg.isPrivileged()
10040                && (pkg.mSharedUserId != null)
10041                && !skipVendorPrivilegeScan) {
10042            SharedUserSetting sharedUserSetting = null;
10043            try {
10044                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10045            } catch (PackageManagerException ignore) {}
10046            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10047                // Exempt SharedUsers signed with the platform key.
10048                // TODO(b/72378145) Fix this exemption. Force signature apps
10049                // to whitelist their privileged permissions just like other
10050                // priv-apps.
10051                synchronized (mPackages) {
10052                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10053                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
10054                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
10055                        scanFlags |= SCAN_AS_PRIVILEGED;
10056                    }
10057                }
10058            }
10059        }
10060
10061        return scanFlags;
10062    }
10063
10064    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
10065    // the results / removing app data needs to be moved up a level to the callers of this
10066    // method. Also, we need to solve the problem of potentially creating a new shared user
10067    // setting. That can probably be done later and patch things up after the fact.
10068    @GuardedBy("mInstallLock")
10069    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10070            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10071            @Nullable UserHandle user) throws PackageManagerException {
10072
10073        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10074        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10075        if (realPkgName != null) {
10076            ensurePackageRenamed(pkg, renamedPkgName);
10077        }
10078        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10079        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10080        final PackageSetting disabledPkgSetting =
10081                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10082
10083        if (mTransferedPackages.contains(pkg.packageName)) {
10084            Slog.w(TAG, "Package " + pkg.packageName
10085                    + " was transferred to another, but its .apk remains");
10086        }
10087
10088        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10089        synchronized (mPackages) {
10090            applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10091            assertPackageIsValid(pkg, parseFlags, scanFlags);
10092
10093            SharedUserSetting sharedUserSetting = null;
10094            if (pkg.mSharedUserId != null) {
10095                // SIDE EFFECTS; may potentially allocate a new shared user
10096                sharedUserSetting = mSettings.getSharedUserLPw(
10097                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10098                if (DEBUG_PACKAGE_SCANNING) {
10099                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10100                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10101                                + " (uid=" + sharedUserSetting.userId + "):"
10102                                + " packages=" + sharedUserSetting.packages);
10103                }
10104            }
10105
10106            boolean scanSucceeded = false;
10107            try {
10108                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
10109                        pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting,
10110                        originalPkgSetting, realPkgName, parseFlags, scanFlags,
10111                        (pkg == mPlatformPackage), user);
10112                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10113                if (result.success) {
10114                    commitScanResultsLocked(request, result);
10115                }
10116                scanSucceeded = true;
10117            } finally {
10118                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10119                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10120                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10121                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10122                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10123                  }
10124            }
10125        }
10126        return pkg;
10127    }
10128
10129    /**
10130     * Commits the package scan and modifies system state.
10131     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10132     * of committing the package, leaving the system in an inconsistent state.
10133     * This needs to be fixed so, once we get to this point, no errors are
10134     * possible and the system is not left in an inconsistent state.
10135     */
10136    @GuardedBy("mPackages")
10137    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10138            throws PackageManagerException {
10139        final PackageParser.Package pkg = request.pkg;
10140        final PackageParser.Package oldPkg = request.oldPkg;
10141        final @ParseFlags int parseFlags = request.parseFlags;
10142        final @ScanFlags int scanFlags = request.scanFlags;
10143        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10144        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10145        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10146        final UserHandle user = request.user;
10147        final String realPkgName = request.realPkgName;
10148        final PackageSetting pkgSetting = result.pkgSetting;
10149        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10150        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10151
10152        if (newPkgSettingCreated) {
10153            if (originalPkgSetting != null) {
10154                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10155            }
10156            // THROWS: when we can't allocate a user id. add call to check if there's
10157            // enough space to ensure we won't throw; otherwise, don't modify state
10158            mSettings.addUserToSettingLPw(pkgSetting);
10159
10160            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10161                mTransferedPackages.add(originalPkgSetting.name);
10162            }
10163        }
10164        // TODO(toddke): Consider a method specifically for modifying the Package object
10165        // post scan; or, moving this stuff out of the Package object since it has nothing
10166        // to do with the package on disk.
10167        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10168        // for creating the application ID. If we did this earlier, we would be saving the
10169        // correct ID.
10170        pkg.applicationInfo.uid = pkgSetting.appId;
10171
10172        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10173
10174        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10175            mTransferedPackages.add(pkg.packageName);
10176        }
10177
10178        // THROWS: when requested libraries that can't be found. it only changes
10179        // the state of the passed in pkg object, so, move to the top of the method
10180        // and allow it to abort
10181        if ((scanFlags & SCAN_BOOTING) == 0
10182                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10183            // Check all shared libraries and map to their actual file path.
10184            // We only do this here for apps not on a system dir, because those
10185            // are the only ones that can fail an install due to this.  We
10186            // will take care of the system apps by updating all of their
10187            // library paths after the scan is done. Also during the initial
10188            // scan don't update any libs as we do this wholesale after all
10189            // apps are scanned to avoid dependency based scanning.
10190            updateSharedLibrariesLPr(pkg, null);
10191        }
10192
10193        // All versions of a static shared library are referenced with the same
10194        // package name. Internally, we use a synthetic package name to allow
10195        // multiple versions of the same shared library to be installed. So,
10196        // we need to generate the synthetic package name of the latest shared
10197        // library in order to compare signatures.
10198        PackageSetting signatureCheckPs = pkgSetting;
10199        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10200            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10201            if (libraryEntry != null) {
10202                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10203            }
10204        }
10205
10206        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10207        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10208            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10209                // We just determined the app is signed correctly, so bring
10210                // over the latest parsed certs.
10211                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10212            } else {
10213                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10214                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10215                            "Package " + pkg.packageName + " upgrade keys do not match the "
10216                                    + "previously installed version");
10217                } else {
10218                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10219                    String msg = "System package " + pkg.packageName
10220                            + " signature changed; retaining data.";
10221                    reportSettingsProblem(Log.WARN, msg);
10222                }
10223            }
10224        } else {
10225            try {
10226                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10227                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10228                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10229                        pkg.mSigningDetails, compareCompat, compareRecover);
10230                // The new KeySets will be re-added later in the scanning process.
10231                if (compatMatch) {
10232                    synchronized (mPackages) {
10233                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10234                    }
10235                }
10236                // We just determined the app is signed correctly, so bring
10237                // over the latest parsed certs.
10238                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10239
10240
10241                // if this is is a sharedUser, check to see if the new package is signed by a newer
10242                // signing certificate than the existing one, and if so, copy over the new details
10243                if (signatureCheckPs.sharedUser != null) {
10244                    if (pkg.mSigningDetails.hasAncestor(
10245                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10246                        signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10247                    }
10248                    if (signatureCheckPs.sharedUser.signaturesChanged == null) {
10249                        signatureCheckPs.sharedUser.signaturesChanged = Boolean.FALSE;
10250                    }
10251                }
10252            } catch (PackageManagerException e) {
10253                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10254                    throw e;
10255                }
10256                // The signature has changed, but this package is in the system
10257                // image...  let's recover!
10258                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10259
10260                // If the system app is part of a shared user we allow that shared user to change
10261                // signatures as well as part of an OTA. We still need to verify that the signatures
10262                // are consistent within the shared user for a given boot, so only allow updating
10263                // the signatures on the first package scanned for the shared user (i.e. if the
10264                // signaturesChanged state hasn't been initialized yet in SharedUserSetting).
10265                if (signatureCheckPs.sharedUser != null) {
10266                    if (signatureCheckPs.sharedUser.signaturesChanged != null &&
10267                        compareSignatures(
10268                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10269                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10270                        throw new PackageManagerException(
10271                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10272                                "Signature mismatch for shared user: " + pkgSetting.sharedUser);
10273                    }
10274
10275                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10276                    signatureCheckPs.sharedUser.signaturesChanged = Boolean.TRUE;
10277                }
10278                // File a report about this.
10279                String msg = "System package " + pkg.packageName
10280                        + " signature changed; retaining data.";
10281                reportSettingsProblem(Log.WARN, msg);
10282            } catch (IllegalArgumentException e) {
10283
10284                // should never happen: certs matched when checking, but not when comparing
10285                // old to new for sharedUser
10286                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10287                        "Signing certificates comparison made on incomparable signing details"
10288                        + " but somehow passed verifySignatures!");
10289            }
10290        }
10291
10292        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10293            // This package wants to adopt ownership of permissions from
10294            // another package.
10295            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10296                final String origName = pkg.mAdoptPermissions.get(i);
10297                final PackageSetting orig = mSettings.getPackageLPr(origName);
10298                if (orig != null) {
10299                    if (verifyPackageUpdateLPr(orig, pkg)) {
10300                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10301                                + pkg.packageName);
10302                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10303                    }
10304                }
10305            }
10306        }
10307
10308        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10309            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10310                final String codePathString = changedAbiCodePath.get(i);
10311                try {
10312                    mInstaller.rmdex(codePathString,
10313                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10314                } catch (InstallerException ignored) {
10315                }
10316            }
10317        }
10318
10319        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10320            if (oldPkgSetting != null) {
10321                synchronized (mPackages) {
10322                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10323                }
10324            }
10325        } else {
10326            final int userId = user == null ? 0 : user.getIdentifier();
10327            // Modify state for the given package setting
10328            commitPackageSettings(pkg, oldPkg, pkgSetting, user, scanFlags,
10329                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10330            if (pkgSetting.getInstantApp(userId)) {
10331                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10332            }
10333        }
10334    }
10335
10336    /**
10337     * Returns the "real" name of the package.
10338     * <p>This may differ from the package's actual name if the application has already
10339     * been installed under one of this package's original names.
10340     */
10341    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10342            @Nullable String renamedPkgName) {
10343        if (isPackageRenamed(pkg, renamedPkgName)) {
10344            return pkg.mRealPackage;
10345        }
10346        return null;
10347    }
10348
10349    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10350    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10351            @Nullable String renamedPkgName) {
10352        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10353    }
10354
10355    /**
10356     * Returns the original package setting.
10357     * <p>A package can migrate its name during an update. In this scenario, a package
10358     * designates a set of names that it considers as one of its original names.
10359     * <p>An original package must be signed identically and it must have the same
10360     * shared user [if any].
10361     */
10362    @GuardedBy("mPackages")
10363    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10364            @Nullable String renamedPkgName) {
10365        if (!isPackageRenamed(pkg, renamedPkgName)) {
10366            return null;
10367        }
10368        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10369            final PackageSetting originalPs =
10370                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10371            if (originalPs != null) {
10372                // the package is already installed under its original name...
10373                // but, should we use it?
10374                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10375                    // the new package is incompatible with the original
10376                    continue;
10377                } else if (originalPs.sharedUser != null) {
10378                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10379                        // the shared user id is incompatible with the original
10380                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10381                                + " to " + pkg.packageName + ": old uid "
10382                                + originalPs.sharedUser.name
10383                                + " differs from " + pkg.mSharedUserId);
10384                        continue;
10385                    }
10386                    // TODO: Add case when shared user id is added [b/28144775]
10387                } else {
10388                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10389                            + pkg.packageName + " to old name " + originalPs.name);
10390                }
10391                return originalPs;
10392            }
10393        }
10394        return null;
10395    }
10396
10397    /**
10398     * Renames the package if it was installed under a different name.
10399     * <p>When we've already installed the package under an original name, update
10400     * the new package so we can continue to have the old name.
10401     */
10402    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10403            @NonNull String renamedPackageName) {
10404        if (pkg.mOriginalPackages == null
10405                || !pkg.mOriginalPackages.contains(renamedPackageName)
10406                || pkg.packageName.equals(renamedPackageName)) {
10407            return;
10408        }
10409        pkg.setPackageName(renamedPackageName);
10410    }
10411
10412    /**
10413     * Just scans the package without any side effects.
10414     * <p>Not entirely true at the moment. There is still one side effect -- this
10415     * method potentially modifies a live {@link PackageSetting} object representing
10416     * the package being scanned. This will be resolved in the future.
10417     *
10418     * @param request Information about the package to be scanned
10419     * @param isUnderFactoryTest Whether or not the device is under factory test
10420     * @param currentTime The current time, in millis
10421     * @return The results of the scan
10422     */
10423    @GuardedBy("mInstallLock")
10424    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10425            boolean isUnderFactoryTest, long currentTime)
10426                    throws PackageManagerException {
10427        final PackageParser.Package pkg = request.pkg;
10428        PackageSetting pkgSetting = request.pkgSetting;
10429        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10430        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10431        final @ParseFlags int parseFlags = request.parseFlags;
10432        final @ScanFlags int scanFlags = request.scanFlags;
10433        final String realPkgName = request.realPkgName;
10434        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10435        final UserHandle user = request.user;
10436        final boolean isPlatformPackage = request.isPlatformPackage;
10437
10438        List<String> changedAbiCodePath = null;
10439
10440        if (DEBUG_PACKAGE_SCANNING) {
10441            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10442                Log.d(TAG, "Scanning package " + pkg.packageName);
10443        }
10444
10445        DexManager.maybeLogUnexpectedPackageDetails(pkg);
10446
10447        // Initialize package source and resource directories
10448        final File scanFile = new File(pkg.codePath);
10449        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10450        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10451
10452        // We keep references to the derived CPU Abis from settings in oder to reuse
10453        // them in the case where we're not upgrading or booting for the first time.
10454        String primaryCpuAbiFromSettings = null;
10455        String secondaryCpuAbiFromSettings = null;
10456        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10457
10458        if (!needToDeriveAbi) {
10459            if (pkgSetting != null) {
10460                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10461                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10462            } else {
10463                // Re-scanning a system package after uninstalling updates; need to derive ABI
10464                needToDeriveAbi = true;
10465            }
10466        }
10467
10468        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10469            PackageManagerService.reportSettingsProblem(Log.WARN,
10470                    "Package " + pkg.packageName + " shared user changed from "
10471                            + (pkgSetting.sharedUser != null
10472                            ? pkgSetting.sharedUser.name : "<nothing>")
10473                            + " to "
10474                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10475                            + "; replacing with new");
10476            pkgSetting = null;
10477        }
10478
10479        String[] usesStaticLibraries = null;
10480        if (pkg.usesStaticLibraries != null) {
10481            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10482            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10483        }
10484        final boolean createNewPackage = (pkgSetting == null);
10485        if (createNewPackage) {
10486            final String parentPackageName = (pkg.parentPackage != null)
10487                    ? pkg.parentPackage.packageName : null;
10488            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10489            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10490            // REMOVE SharedUserSetting from method; update in a separate call
10491            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10492                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10493                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10494                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10495                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10496                    user, true /*allowInstall*/, instantApp, virtualPreload,
10497                    parentPackageName, pkg.getChildPackageNames(),
10498                    UserManagerService.getInstance(), usesStaticLibraries,
10499                    pkg.usesStaticLibrariesVersions);
10500        } else {
10501            // REMOVE SharedUserSetting from method; update in a separate call.
10502            //
10503            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10504            // secondaryCpuAbi are not known at this point so we always update them
10505            // to null here, only to reset them at a later point.
10506            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10507                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10508                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10509                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10510                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10511                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10512        }
10513        if (createNewPackage && originalPkgSetting != null) {
10514            // This is the initial transition from the original package, so,
10515            // fix up the new package's name now. We must do this after looking
10516            // up the package under its new name, so getPackageLP takes care of
10517            // fiddling things correctly.
10518            pkg.setPackageName(originalPkgSetting.name);
10519
10520            // File a report about this.
10521            String msg = "New package " + pkgSetting.realName
10522                    + " renamed to replace old package " + pkgSetting.name;
10523            reportSettingsProblem(Log.WARN, msg);
10524        }
10525
10526        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10527        // for existing packages, change the install state; but, only if it's explicitly specified
10528        if (!createNewPackage) {
10529            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10530            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10531            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10532        }
10533
10534        if (disabledPkgSetting != null) {
10535            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10536        }
10537
10538        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10539        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10540        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10541        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10542        // least restrictive selinux domain.
10543        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10544        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10545        // ensures that all packages continue to run in the same selinux domain.
10546        final int targetSdkVersion =
10547            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10548            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10549        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10550        // They currently can be if the sharedUser apps are signed with the platform key.
10551        final boolean isPrivileged = (sharedUserSetting != null) ?
10552            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10553
10554        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10555                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10556        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10557                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10558
10559        pkg.mExtras = pkgSetting;
10560        pkg.applicationInfo.processName = fixProcessName(
10561                pkg.applicationInfo.packageName,
10562                pkg.applicationInfo.processName);
10563
10564        if (!isPlatformPackage) {
10565            // Get all of our default paths setup
10566            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10567        }
10568
10569        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10570
10571        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10572            if (needToDeriveAbi) {
10573                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10574                final boolean extractNativeLibs = !pkg.isLibrary();
10575                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10576                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10577
10578                // Some system apps still use directory structure for native libraries
10579                // in which case we might end up not detecting abi solely based on apk
10580                // structure. Try to detect abi based on directory structure.
10581                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10582                        pkg.applicationInfo.primaryCpuAbi == null) {
10583                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10584                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10585                }
10586            } else {
10587                // This is not a first boot or an upgrade, don't bother deriving the
10588                // ABI during the scan. Instead, trust the value that was stored in the
10589                // package setting.
10590                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10591                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10592
10593                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10594
10595                if (DEBUG_ABI_SELECTION) {
10596                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10597                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10598                            pkg.applicationInfo.secondaryCpuAbi);
10599                }
10600            }
10601        } else {
10602            if ((scanFlags & SCAN_MOVE) != 0) {
10603                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10604                // but we already have this packages package info in the PackageSetting. We just
10605                // use that and derive the native library path based on the new codepath.
10606                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10607                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10608            }
10609
10610            // Set native library paths again. For moves, the path will be updated based on the
10611            // ABIs we've determined above. For non-moves, the path will be updated based on the
10612            // ABIs we determined during compilation, but the path will depend on the final
10613            // package path (after the rename away from the stage path).
10614            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10615        }
10616
10617        // This is a special case for the "system" package, where the ABI is
10618        // dictated by the zygote configuration (and init.rc). We should keep track
10619        // of this ABI so that we can deal with "normal" applications that run under
10620        // the same UID correctly.
10621        if (isPlatformPackage) {
10622            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10623                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10624        }
10625
10626        // If there's a mismatch between the abi-override in the package setting
10627        // and the abiOverride specified for the install. Warn about this because we
10628        // would've already compiled the app without taking the package setting into
10629        // account.
10630        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10631            if (cpuAbiOverride == null && pkg.packageName != null) {
10632                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10633                        " for package " + pkg.packageName);
10634            }
10635        }
10636
10637        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10638        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10639        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10640
10641        // Copy the derived override back to the parsed package, so that we can
10642        // update the package settings accordingly.
10643        pkg.cpuAbiOverride = cpuAbiOverride;
10644
10645        if (DEBUG_ABI_SELECTION) {
10646            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10647                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10648                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10649        }
10650
10651        // Push the derived path down into PackageSettings so we know what to
10652        // clean up at uninstall time.
10653        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10654
10655        if (DEBUG_ABI_SELECTION) {
10656            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10657                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10658                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10659        }
10660
10661        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10662            // We don't do this here during boot because we can do it all
10663            // at once after scanning all existing packages.
10664            //
10665            // We also do this *before* we perform dexopt on this package, so that
10666            // we can avoid redundant dexopts, and also to make sure we've got the
10667            // code and package path correct.
10668            changedAbiCodePath =
10669                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10670        }
10671
10672        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10673                android.Manifest.permission.FACTORY_TEST)) {
10674            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10675        }
10676
10677        if (isSystemApp(pkg)) {
10678            pkgSetting.isOrphaned = true;
10679        }
10680
10681        // Take care of first install / last update times.
10682        final long scanFileTime = getLastModifiedTime(pkg);
10683        if (currentTime != 0) {
10684            if (pkgSetting.firstInstallTime == 0) {
10685                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10686            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10687                pkgSetting.lastUpdateTime = currentTime;
10688            }
10689        } else if (pkgSetting.firstInstallTime == 0) {
10690            // We need *something*.  Take time time stamp of the file.
10691            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10692        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10693            if (scanFileTime != pkgSetting.timeStamp) {
10694                // A package on the system image has changed; consider this
10695                // to be an update.
10696                pkgSetting.lastUpdateTime = scanFileTime;
10697            }
10698        }
10699        pkgSetting.setTimeStamp(scanFileTime);
10700
10701        pkgSetting.pkg = pkg;
10702        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10703        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10704            pkgSetting.versionCode = pkg.getLongVersionCode();
10705        }
10706        // Update volume if needed
10707        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10708        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10709            Slog.i(PackageManagerService.TAG,
10710                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10711                    + " package " + pkg.packageName
10712                    + " volume from " + pkgSetting.volumeUuid
10713                    + " to " + volumeUuid);
10714            pkgSetting.volumeUuid = volumeUuid;
10715        }
10716
10717        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10718    }
10719
10720    /**
10721     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10722     */
10723    private static boolean apkHasCode(String fileName) {
10724        StrictJarFile jarFile = null;
10725        try {
10726            jarFile = new StrictJarFile(fileName,
10727                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10728            return jarFile.findEntry("classes.dex") != null;
10729        } catch (IOException ignore) {
10730        } finally {
10731            try {
10732                if (jarFile != null) {
10733                    jarFile.close();
10734                }
10735            } catch (IOException ignore) {}
10736        }
10737        return false;
10738    }
10739
10740    /**
10741     * Enforces code policy for the package. This ensures that if an APK has
10742     * declared hasCode="true" in its manifest that the APK actually contains
10743     * code.
10744     *
10745     * @throws PackageManagerException If bytecode could not be found when it should exist
10746     */
10747    private static void assertCodePolicy(PackageParser.Package pkg)
10748            throws PackageManagerException {
10749        final boolean shouldHaveCode =
10750                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10751        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10752            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10753                    "Package " + pkg.baseCodePath + " code is missing");
10754        }
10755
10756        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10757            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10758                final boolean splitShouldHaveCode =
10759                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10760                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10761                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10762                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10763                }
10764            }
10765        }
10766    }
10767
10768    /**
10769     * Applies policy to the parsed package based upon the given policy flags.
10770     * Ensures the package is in a good state.
10771     * <p>
10772     * Implementation detail: This method must NOT have any side effect. It would
10773     * ideally be static, but, it requires locks to read system state.
10774     */
10775    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10776            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10777        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10778            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10779            if (pkg.applicationInfo.isDirectBootAware()) {
10780                // we're direct boot aware; set for all components
10781                for (PackageParser.Service s : pkg.services) {
10782                    s.info.encryptionAware = s.info.directBootAware = true;
10783                }
10784                for (PackageParser.Provider p : pkg.providers) {
10785                    p.info.encryptionAware = p.info.directBootAware = true;
10786                }
10787                for (PackageParser.Activity a : pkg.activities) {
10788                    a.info.encryptionAware = a.info.directBootAware = true;
10789                }
10790                for (PackageParser.Activity r : pkg.receivers) {
10791                    r.info.encryptionAware = r.info.directBootAware = true;
10792                }
10793            }
10794            if (compressedFileExists(pkg.codePath)) {
10795                pkg.isStub = true;
10796            }
10797        } else {
10798            // non system apps can't be flagged as core
10799            pkg.coreApp = false;
10800            // clear flags not applicable to regular apps
10801            pkg.applicationInfo.flags &=
10802                    ~ApplicationInfo.FLAG_PERSISTENT;
10803            pkg.applicationInfo.privateFlags &=
10804                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10805            pkg.applicationInfo.privateFlags &=
10806                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10807            // cap permission priorities
10808            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10809                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10810                    pkg.permissionGroups.get(i).info.priority = 0;
10811                }
10812            }
10813        }
10814        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10815            // clear protected broadcasts
10816            pkg.protectedBroadcasts = null;
10817            // ignore export request for single user receivers
10818            if (pkg.receivers != null) {
10819                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10820                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10821                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10822                        receiver.info.exported = false;
10823                    }
10824                }
10825            }
10826            // ignore export request for single user services
10827            if (pkg.services != null) {
10828                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10829                    final PackageParser.Service service = pkg.services.get(i);
10830                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10831                        service.info.exported = false;
10832                    }
10833                }
10834            }
10835            // ignore export request for single user providers
10836            if (pkg.providers != null) {
10837                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10838                    final PackageParser.Provider provider = pkg.providers.get(i);
10839                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10840                        provider.info.exported = false;
10841                    }
10842                }
10843            }
10844        }
10845
10846        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10847            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10848        }
10849
10850        if ((scanFlags & SCAN_AS_OEM) != 0) {
10851            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10852        }
10853
10854        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10855            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10856        }
10857
10858        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10859            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10860        }
10861
10862        // Check if the package is signed with the same key as the platform package.
10863        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10864                (platformPkg != null && compareSignatures(
10865                        platformPkg.mSigningDetails.signatures,
10866                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10867            pkg.applicationInfo.privateFlags |=
10868                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10869        }
10870
10871        if (!isSystemApp(pkg)) {
10872            // Only system apps can use these features.
10873            pkg.mOriginalPackages = null;
10874            pkg.mRealPackage = null;
10875            pkg.mAdoptPermissions = null;
10876        }
10877    }
10878
10879    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10880            throws PackageManagerException {
10881        if (object == null) {
10882            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10883        }
10884        return object;
10885    }
10886
10887    /**
10888     * Asserts the parsed package is valid according to the given policy. If the
10889     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10890     * <p>
10891     * Implementation detail: This method must NOT have any side effects. It would
10892     * ideally be static, but, it requires locks to read system state.
10893     *
10894     * @throws PackageManagerException If the package fails any of the validation checks
10895     */
10896    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10897            final @ScanFlags int scanFlags)
10898                    throws PackageManagerException {
10899        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10900            assertCodePolicy(pkg);
10901        }
10902
10903        if (pkg.applicationInfo.getCodePath() == null ||
10904                pkg.applicationInfo.getResourcePath() == null) {
10905            // Bail out. The resource and code paths haven't been set.
10906            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10907                    "Code and resource paths haven't been set correctly");
10908        }
10909
10910        // Make sure we're not adding any bogus keyset info
10911        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10912        ksms.assertScannedPackageValid(pkg);
10913
10914        synchronized (mPackages) {
10915            // The special "android" package can only be defined once
10916            if (pkg.packageName.equals("android")) {
10917                if (mAndroidApplication != null) {
10918                    Slog.w(TAG, "*************************************************");
10919                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10920                    Slog.w(TAG, " codePath=" + pkg.codePath);
10921                    Slog.w(TAG, "*************************************************");
10922                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10923                            "Core android package being redefined.  Skipping.");
10924                }
10925            }
10926
10927            // A package name must be unique; don't allow duplicates
10928            if (mPackages.containsKey(pkg.packageName)) {
10929                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10930                        "Application package " + pkg.packageName
10931                        + " already installed.  Skipping duplicate.");
10932            }
10933
10934            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10935                // Static libs have a synthetic package name containing the version
10936                // but we still want the base name to be unique.
10937                if (mPackages.containsKey(pkg.manifestPackageName)) {
10938                    throw new PackageManagerException(
10939                            "Duplicate static shared lib provider package");
10940                }
10941
10942                // Static shared libraries should have at least O target SDK
10943                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10944                    throw new PackageManagerException(
10945                            "Packages declaring static-shared libs must target O SDK or higher");
10946                }
10947
10948                // Package declaring static a shared lib cannot be instant apps
10949                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10950                    throw new PackageManagerException(
10951                            "Packages declaring static-shared libs cannot be instant apps");
10952                }
10953
10954                // Package declaring static a shared lib cannot be renamed since the package
10955                // name is synthetic and apps can't code around package manager internals.
10956                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10957                    throw new PackageManagerException(
10958                            "Packages declaring static-shared libs cannot be renamed");
10959                }
10960
10961                // Package declaring static a shared lib cannot declare child packages
10962                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10963                    throw new PackageManagerException(
10964                            "Packages declaring static-shared libs cannot have child packages");
10965                }
10966
10967                // Package declaring static a shared lib cannot declare dynamic libs
10968                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10969                    throw new PackageManagerException(
10970                            "Packages declaring static-shared libs cannot declare dynamic libs");
10971                }
10972
10973                // Package declaring static a shared lib cannot declare shared users
10974                if (pkg.mSharedUserId != null) {
10975                    throw new PackageManagerException(
10976                            "Packages declaring static-shared libs cannot declare shared users");
10977                }
10978
10979                // Static shared libs cannot declare activities
10980                if (!pkg.activities.isEmpty()) {
10981                    throw new PackageManagerException(
10982                            "Static shared libs cannot declare activities");
10983                }
10984
10985                // Static shared libs cannot declare services
10986                if (!pkg.services.isEmpty()) {
10987                    throw new PackageManagerException(
10988                            "Static shared libs cannot declare services");
10989                }
10990
10991                // Static shared libs cannot declare providers
10992                if (!pkg.providers.isEmpty()) {
10993                    throw new PackageManagerException(
10994                            "Static shared libs cannot declare content providers");
10995                }
10996
10997                // Static shared libs cannot declare receivers
10998                if (!pkg.receivers.isEmpty()) {
10999                    throw new PackageManagerException(
11000                            "Static shared libs cannot declare broadcast receivers");
11001                }
11002
11003                // Static shared libs cannot declare permission groups
11004                if (!pkg.permissionGroups.isEmpty()) {
11005                    throw new PackageManagerException(
11006                            "Static shared libs cannot declare permission groups");
11007                }
11008
11009                // Static shared libs cannot declare permissions
11010                if (!pkg.permissions.isEmpty()) {
11011                    throw new PackageManagerException(
11012                            "Static shared libs cannot declare permissions");
11013                }
11014
11015                // Static shared libs cannot declare protected broadcasts
11016                if (pkg.protectedBroadcasts != null) {
11017                    throw new PackageManagerException(
11018                            "Static shared libs cannot declare protected broadcasts");
11019                }
11020
11021                // Static shared libs cannot be overlay targets
11022                if (pkg.mOverlayTarget != null) {
11023                    throw new PackageManagerException(
11024                            "Static shared libs cannot be overlay targets");
11025                }
11026
11027                // The version codes must be ordered as lib versions
11028                long minVersionCode = Long.MIN_VALUE;
11029                long maxVersionCode = Long.MAX_VALUE;
11030
11031                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11032                        pkg.staticSharedLibName);
11033                if (versionedLib != null) {
11034                    final int versionCount = versionedLib.size();
11035                    for (int i = 0; i < versionCount; i++) {
11036                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11037                        final long libVersionCode = libInfo.getDeclaringPackage()
11038                                .getLongVersionCode();
11039                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
11040                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11041                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
11042                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11043                        } else {
11044                            minVersionCode = maxVersionCode = libVersionCode;
11045                            break;
11046                        }
11047                    }
11048                }
11049                if (pkg.getLongVersionCode() < minVersionCode
11050                        || pkg.getLongVersionCode() > maxVersionCode) {
11051                    throw new PackageManagerException("Static shared"
11052                            + " lib version codes must be ordered as lib versions");
11053                }
11054            }
11055
11056            // Only privileged apps and updated privileged apps can add child packages.
11057            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11058                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
11059                    throw new PackageManagerException("Only privileged apps can add child "
11060                            + "packages. Ignoring package " + pkg.packageName);
11061                }
11062                final int childCount = pkg.childPackages.size();
11063                for (int i = 0; i < childCount; i++) {
11064                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11065                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11066                            childPkg.packageName)) {
11067                        throw new PackageManagerException("Can't override child of "
11068                                + "another disabled app. Ignoring package " + pkg.packageName);
11069                    }
11070                }
11071            }
11072
11073            // If we're only installing presumed-existing packages, require that the
11074            // scanned APK is both already known and at the path previously established
11075            // for it.  Previously unknown packages we pick up normally, but if we have an
11076            // a priori expectation about this package's install presence, enforce it.
11077            // With a singular exception for new system packages. When an OTA contains
11078            // a new system package, we allow the codepath to change from a system location
11079            // to the user-installed location. If we don't allow this change, any newer,
11080            // user-installed version of the application will be ignored.
11081            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11082                if (mExpectingBetter.containsKey(pkg.packageName)) {
11083                    logCriticalInfo(Log.WARN,
11084                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11085                } else {
11086                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11087                    if (known != null) {
11088                        if (DEBUG_PACKAGE_SCANNING) {
11089                            Log.d(TAG, "Examining " + pkg.codePath
11090                                    + " and requiring known paths " + known.codePathString
11091                                    + " & " + known.resourcePathString);
11092                        }
11093                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11094                                || !pkg.applicationInfo.getResourcePath().equals(
11095                                        known.resourcePathString)) {
11096                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11097                                    "Application package " + pkg.packageName
11098                                    + " found at " + pkg.applicationInfo.getCodePath()
11099                                    + " but expected at " + known.codePathString
11100                                    + "; ignoring.");
11101                        }
11102                    } else {
11103                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11104                                "Application package " + pkg.packageName
11105                                + " not found; ignoring.");
11106                    }
11107                }
11108            }
11109
11110            // Verify that this new package doesn't have any content providers
11111            // that conflict with existing packages.  Only do this if the
11112            // package isn't already installed, since we don't want to break
11113            // things that are installed.
11114            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11115                final int N = pkg.providers.size();
11116                int i;
11117                for (i=0; i<N; i++) {
11118                    PackageParser.Provider p = pkg.providers.get(i);
11119                    if (p.info.authority != null) {
11120                        String names[] = p.info.authority.split(";");
11121                        for (int j = 0; j < names.length; j++) {
11122                            if (mProvidersByAuthority.containsKey(names[j])) {
11123                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11124                                final String otherPackageName =
11125                                        ((other != null && other.getComponentName() != null) ?
11126                                                other.getComponentName().getPackageName() : "?");
11127                                throw new PackageManagerException(
11128                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11129                                        "Can't install because provider name " + names[j]
11130                                                + " (in package " + pkg.applicationInfo.packageName
11131                                                + ") is already used by " + otherPackageName);
11132                            }
11133                        }
11134                    }
11135                }
11136            }
11137
11138            // Verify that packages sharing a user with a privileged app are marked as privileged.
11139            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11140                SharedUserSetting sharedUserSetting = null;
11141                try {
11142                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11143                } catch (PackageManagerException ignore) {}
11144                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11145                    // Exempt SharedUsers signed with the platform key.
11146                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11147                    if ((platformPkgSetting.signatures.mSigningDetails
11148                            != PackageParser.SigningDetails.UNKNOWN)
11149                            && (compareSignatures(
11150                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11151                                    pkg.mSigningDetails.signatures)
11152                                            != PackageManager.SIGNATURE_MATCH)) {
11153                        throw new PackageManagerException("Apps that share a user with a " +
11154                                "privileged app must themselves be marked as privileged. " +
11155                                pkg.packageName + " shares privileged user " +
11156                                pkg.mSharedUserId + ".");
11157                    }
11158                }
11159            }
11160
11161            // Apply policies specific for runtime resource overlays (RROs).
11162            if (pkg.mOverlayTarget != null) {
11163                // System overlays have some restrictions on their use of the 'static' state.
11164                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11165                    // We are scanning a system overlay. This can be the first scan of the
11166                    // system/vendor/oem partition, or an update to the system overlay.
11167                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11168                        // This must be an update to a system overlay.
11169                        final PackageSetting previousPkg = assertNotNull(
11170                                mSettings.getPackageLPr(pkg.packageName),
11171                                "previous package state not present");
11172
11173                        // previousPkg.pkg may be null: the package will be not be scanned if the
11174                        // package manager knows there is a newer version on /data.
11175                        // TODO[b/79435695]: Find a better way to keep track of the "static"
11176                        // property for RROs instead of having to parse packages on /system
11177                        PackageParser.Package ppkg = previousPkg.pkg;
11178                        if (ppkg == null) {
11179                            try {
11180                                final PackageParser pp = new PackageParser();
11181                                ppkg = pp.parsePackage(previousPkg.codePath,
11182                                        parseFlags | PackageParser.PARSE_IS_SYSTEM_DIR);
11183                            } catch (PackageParserException e) {
11184                                Slog.w(TAG, "failed to parse " + previousPkg.codePath, e);
11185                            }
11186                        }
11187
11188                        // Static overlays cannot be updated.
11189                        if (ppkg != null && ppkg.mOverlayIsStatic) {
11190                            throw new PackageManagerException("Overlay " + pkg.packageName +
11191                                    " is static and cannot be upgraded.");
11192                        // Non-static overlays cannot be converted to static overlays.
11193                        } else if (pkg.mOverlayIsStatic) {
11194                            throw new PackageManagerException("Overlay " + pkg.packageName +
11195                                    " cannot be upgraded into a static overlay.");
11196                        }
11197                    }
11198                } else {
11199                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11200                    if (pkg.mOverlayIsStatic) {
11201                        throw new PackageManagerException("Overlay " + pkg.packageName +
11202                                " is static but not pre-installed.");
11203                    }
11204
11205                    // The only case where we allow installation of a non-system overlay is when
11206                    // its signature is signed with the platform certificate.
11207                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11208                    if ((platformPkgSetting.signatures.mSigningDetails
11209                            != PackageParser.SigningDetails.UNKNOWN)
11210                            && (compareSignatures(
11211                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11212                                    pkg.mSigningDetails.signatures)
11213                                            != PackageManager.SIGNATURE_MATCH)) {
11214                        throw new PackageManagerException("Overlay " + pkg.packageName +
11215                                " must be signed with the platform certificate.");
11216                    }
11217                }
11218            }
11219        }
11220    }
11221
11222    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11223            int type, String declaringPackageName, long declaringVersionCode) {
11224        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11225        if (versionedLib == null) {
11226            versionedLib = new LongSparseArray<>();
11227            mSharedLibraries.put(name, versionedLib);
11228            if (type == SharedLibraryInfo.TYPE_STATIC) {
11229                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11230            }
11231        } else if (versionedLib.indexOfKey(version) >= 0) {
11232            return false;
11233        }
11234        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11235                version, type, declaringPackageName, declaringVersionCode);
11236        versionedLib.put(version, libEntry);
11237        return true;
11238    }
11239
11240    private boolean removeSharedLibraryLPw(String name, long version) {
11241        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11242        if (versionedLib == null) {
11243            return false;
11244        }
11245        final int libIdx = versionedLib.indexOfKey(version);
11246        if (libIdx < 0) {
11247            return false;
11248        }
11249        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11250        versionedLib.remove(version);
11251        if (versionedLib.size() <= 0) {
11252            mSharedLibraries.remove(name);
11253            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11254                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11255                        .getPackageName());
11256            }
11257        }
11258        return true;
11259    }
11260
11261    /**
11262     * Adds a scanned package to the system. When this method is finished, the package will
11263     * be available for query, resolution, etc...
11264     */
11265    private void commitPackageSettings(PackageParser.Package pkg,
11266            @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, UserHandle user,
11267            final @ScanFlags int scanFlags, boolean chatty) {
11268        final String pkgName = pkg.packageName;
11269        if (mCustomResolverComponentName != null &&
11270                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11271            setUpCustomResolverActivity(pkg);
11272        }
11273
11274        if (pkg.packageName.equals("android")) {
11275            synchronized (mPackages) {
11276                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11277                    // Set up information for our fall-back user intent resolution activity.
11278                    mPlatformPackage = pkg;
11279                    pkg.mVersionCode = mSdkVersion;
11280                    pkg.mVersionCodeMajor = 0;
11281                    mAndroidApplication = pkg.applicationInfo;
11282                    if (!mResolverReplaced) {
11283                        mResolveActivity.applicationInfo = mAndroidApplication;
11284                        mResolveActivity.name = ResolverActivity.class.getName();
11285                        mResolveActivity.packageName = mAndroidApplication.packageName;
11286                        mResolveActivity.processName = "system:ui";
11287                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11288                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11289                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11290                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11291                        mResolveActivity.exported = true;
11292                        mResolveActivity.enabled = true;
11293                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11294                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11295                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11296                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11297                                | ActivityInfo.CONFIG_ORIENTATION
11298                                | ActivityInfo.CONFIG_KEYBOARD
11299                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11300                        mResolveInfo.activityInfo = mResolveActivity;
11301                        mResolveInfo.priority = 0;
11302                        mResolveInfo.preferredOrder = 0;
11303                        mResolveInfo.match = 0;
11304                        mResolveComponentName = new ComponentName(
11305                                mAndroidApplication.packageName, mResolveActivity.name);
11306                    }
11307                }
11308            }
11309        }
11310
11311        ArrayList<PackageParser.Package> clientLibPkgs = null;
11312        // writer
11313        synchronized (mPackages) {
11314            boolean hasStaticSharedLibs = false;
11315
11316            // Any app can add new static shared libraries
11317            if (pkg.staticSharedLibName != null) {
11318                // Static shared libs don't allow renaming as they have synthetic package
11319                // names to allow install of multiple versions, so use name from manifest.
11320                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11321                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11322                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11323                    hasStaticSharedLibs = true;
11324                } else {
11325                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11326                                + pkg.staticSharedLibName + " already exists; skipping");
11327                }
11328                // Static shared libs cannot be updated once installed since they
11329                // use synthetic package name which includes the version code, so
11330                // not need to update other packages's shared lib dependencies.
11331            }
11332
11333            if (!hasStaticSharedLibs
11334                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11335                // Only system apps can add new dynamic shared libraries.
11336                if (pkg.libraryNames != null) {
11337                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11338                        String name = pkg.libraryNames.get(i);
11339                        boolean allowed = false;
11340                        if (pkg.isUpdatedSystemApp()) {
11341                            // New library entries can only be added through the
11342                            // system image.  This is important to get rid of a lot
11343                            // of nasty edge cases: for example if we allowed a non-
11344                            // system update of the app to add a library, then uninstalling
11345                            // the update would make the library go away, and assumptions
11346                            // we made such as through app install filtering would now
11347                            // have allowed apps on the device which aren't compatible
11348                            // with it.  Better to just have the restriction here, be
11349                            // conservative, and create many fewer cases that can negatively
11350                            // impact the user experience.
11351                            final PackageSetting sysPs = mSettings
11352                                    .getDisabledSystemPkgLPr(pkg.packageName);
11353                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11354                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11355                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11356                                        allowed = true;
11357                                        break;
11358                                    }
11359                                }
11360                            }
11361                        } else {
11362                            allowed = true;
11363                        }
11364                        if (allowed) {
11365                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11366                                    SharedLibraryInfo.VERSION_UNDEFINED,
11367                                    SharedLibraryInfo.TYPE_DYNAMIC,
11368                                    pkg.packageName, pkg.getLongVersionCode())) {
11369                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11370                                        + name + " already exists; skipping");
11371                            }
11372                        } else {
11373                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11374                                    + name + " that is not declared on system image; skipping");
11375                        }
11376                    }
11377
11378                    if ((scanFlags & SCAN_BOOTING) == 0) {
11379                        // If we are not booting, we need to update any applications
11380                        // that are clients of our shared library.  If we are booting,
11381                        // this will all be done once the scan is complete.
11382                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11383                    }
11384                }
11385            }
11386        }
11387
11388        if ((scanFlags & SCAN_BOOTING) != 0) {
11389            // No apps can run during boot scan, so they don't need to be frozen
11390        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11391            // Caller asked to not kill app, so it's probably not frozen
11392        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11393            // Caller asked us to ignore frozen check for some reason; they
11394            // probably didn't know the package name
11395        } else {
11396            // We're doing major surgery on this package, so it better be frozen
11397            // right now to keep it from launching
11398            checkPackageFrozen(pkgName);
11399        }
11400
11401        // Also need to kill any apps that are dependent on the library.
11402        if (clientLibPkgs != null) {
11403            for (int i=0; i<clientLibPkgs.size(); i++) {
11404                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11405                killApplication(clientPkg.applicationInfo.packageName,
11406                        clientPkg.applicationInfo.uid, "update lib");
11407            }
11408        }
11409
11410        // writer
11411        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11412
11413        synchronized (mPackages) {
11414            // We don't expect installation to fail beyond this point
11415
11416            // Add the new setting to mSettings
11417            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11418            // Add the new setting to mPackages
11419            mPackages.put(pkg.applicationInfo.packageName, pkg);
11420            // Make sure we don't accidentally delete its data.
11421            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11422            while (iter.hasNext()) {
11423                PackageCleanItem item = iter.next();
11424                if (pkgName.equals(item.packageName)) {
11425                    iter.remove();
11426                }
11427            }
11428
11429            // Add the package's KeySets to the global KeySetManagerService
11430            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11431            ksms.addScannedPackageLPw(pkg);
11432
11433            int N = pkg.providers.size();
11434            StringBuilder r = null;
11435            int i;
11436            for (i=0; i<N; i++) {
11437                PackageParser.Provider p = pkg.providers.get(i);
11438                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11439                        p.info.processName);
11440                mProviders.addProvider(p);
11441                p.syncable = p.info.isSyncable;
11442                if (p.info.authority != null) {
11443                    String names[] = p.info.authority.split(";");
11444                    p.info.authority = null;
11445                    for (int j = 0; j < names.length; j++) {
11446                        if (j == 1 && p.syncable) {
11447                            // We only want the first authority for a provider to possibly be
11448                            // syncable, so if we already added this provider using a different
11449                            // authority clear the syncable flag. We copy the provider before
11450                            // changing it because the mProviders object contains a reference
11451                            // to a provider that we don't want to change.
11452                            // Only do this for the second authority since the resulting provider
11453                            // object can be the same for all future authorities for this provider.
11454                            p = new PackageParser.Provider(p);
11455                            p.syncable = false;
11456                        }
11457                        if (!mProvidersByAuthority.containsKey(names[j])) {
11458                            mProvidersByAuthority.put(names[j], p);
11459                            if (p.info.authority == null) {
11460                                p.info.authority = names[j];
11461                            } else {
11462                                p.info.authority = p.info.authority + ";" + names[j];
11463                            }
11464                            if (DEBUG_PACKAGE_SCANNING) {
11465                                if (chatty)
11466                                    Log.d(TAG, "Registered content provider: " + names[j]
11467                                            + ", className = " + p.info.name + ", isSyncable = "
11468                                            + p.info.isSyncable);
11469                            }
11470                        } else {
11471                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11472                            Slog.w(TAG, "Skipping provider name " + names[j] +
11473                                    " (in package " + pkg.applicationInfo.packageName +
11474                                    "): name already used by "
11475                                    + ((other != null && other.getComponentName() != null)
11476                                            ? other.getComponentName().getPackageName() : "?"));
11477                        }
11478                    }
11479                }
11480                if (chatty) {
11481                    if (r == null) {
11482                        r = new StringBuilder(256);
11483                    } else {
11484                        r.append(' ');
11485                    }
11486                    r.append(p.info.name);
11487                }
11488            }
11489            if (r != null) {
11490                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11491            }
11492
11493            N = pkg.services.size();
11494            r = null;
11495            for (i=0; i<N; i++) {
11496                PackageParser.Service s = pkg.services.get(i);
11497                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11498                        s.info.processName);
11499                mServices.addService(s);
11500                if (chatty) {
11501                    if (r == null) {
11502                        r = new StringBuilder(256);
11503                    } else {
11504                        r.append(' ');
11505                    }
11506                    r.append(s.info.name);
11507                }
11508            }
11509            if (r != null) {
11510                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11511            }
11512
11513            N = pkg.receivers.size();
11514            r = null;
11515            for (i=0; i<N; i++) {
11516                PackageParser.Activity a = pkg.receivers.get(i);
11517                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11518                        a.info.processName);
11519                mReceivers.addActivity(a, "receiver");
11520                if (chatty) {
11521                    if (r == null) {
11522                        r = new StringBuilder(256);
11523                    } else {
11524                        r.append(' ');
11525                    }
11526                    r.append(a.info.name);
11527                }
11528            }
11529            if (r != null) {
11530                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11531            }
11532
11533            N = pkg.activities.size();
11534            r = null;
11535            for (i=0; i<N; i++) {
11536                PackageParser.Activity a = pkg.activities.get(i);
11537                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11538                        a.info.processName);
11539                mActivities.addActivity(a, "activity");
11540                if (chatty) {
11541                    if (r == null) {
11542                        r = new StringBuilder(256);
11543                    } else {
11544                        r.append(' ');
11545                    }
11546                    r.append(a.info.name);
11547                }
11548            }
11549            if (r != null) {
11550                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11551            }
11552
11553            // Don't allow ephemeral applications to define new permissions groups.
11554            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11555                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11556                        + " ignored: instant apps cannot define new permission groups.");
11557            } else {
11558                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11559            }
11560
11561            // Don't allow ephemeral applications to define new permissions.
11562            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11563                Slog.w(TAG, "Permissions from package " + pkg.packageName
11564                        + " ignored: instant apps cannot define new permissions.");
11565            } else {
11566                mPermissionManager.addAllPermissions(pkg, chatty);
11567            }
11568
11569            N = pkg.instrumentation.size();
11570            r = null;
11571            for (i=0; i<N; i++) {
11572                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11573                a.info.packageName = pkg.applicationInfo.packageName;
11574                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11575                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11576                a.info.splitNames = pkg.splitNames;
11577                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11578                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11579                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11580                a.info.dataDir = pkg.applicationInfo.dataDir;
11581                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11582                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11583                a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11584                a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
11585                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11586                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11587                mInstrumentation.put(a.getComponentName(), a);
11588                if (chatty) {
11589                    if (r == null) {
11590                        r = new StringBuilder(256);
11591                    } else {
11592                        r.append(' ');
11593                    }
11594                    r.append(a.info.name);
11595                }
11596            }
11597            if (r != null) {
11598                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11599            }
11600
11601            if (pkg.protectedBroadcasts != null) {
11602                N = pkg.protectedBroadcasts.size();
11603                synchronized (mProtectedBroadcasts) {
11604                    for (i = 0; i < N; i++) {
11605                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11606                    }
11607                }
11608            }
11609
11610            if (oldPkg != null) {
11611                // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
11612                // revoke callbacks from this method might need to kill apps which need the
11613                // mPackages lock on a different thread. This would dead lock.
11614                //
11615                // Hence create a copy of all package names and pass it into
11616                // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
11617                // revoked. If a new package is added before the async code runs the permission
11618                // won't be granted yet, hence new packages are no problem.
11619                final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
11620
11621                AsyncTask.execute(() ->
11622                        mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
11623                                allPackageNames, mPermissionCallback));
11624            }
11625        }
11626
11627        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11628    }
11629
11630    /**
11631     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11632     * is derived purely on the basis of the contents of {@code scanFile} and
11633     * {@code cpuAbiOverride}.
11634     *
11635     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11636     */
11637    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11638            boolean extractLibs)
11639                    throws PackageManagerException {
11640        // Give ourselves some initial paths; we'll come back for another
11641        // pass once we've determined ABI below.
11642        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11643
11644        // We would never need to extract libs for forward-locked and external packages,
11645        // since the container service will do it for us. We shouldn't attempt to
11646        // extract libs from system app when it was not updated.
11647        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11648                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11649            extractLibs = false;
11650        }
11651
11652        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11653        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11654
11655        NativeLibraryHelper.Handle handle = null;
11656        try {
11657            handle = NativeLibraryHelper.Handle.create(pkg);
11658            // TODO(multiArch): This can be null for apps that didn't go through the
11659            // usual installation process. We can calculate it again, like we
11660            // do during install time.
11661            //
11662            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11663            // unnecessary.
11664            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11665
11666            // Null out the abis so that they can be recalculated.
11667            pkg.applicationInfo.primaryCpuAbi = null;
11668            pkg.applicationInfo.secondaryCpuAbi = null;
11669            if (isMultiArch(pkg.applicationInfo)) {
11670                // Warn if we've set an abiOverride for multi-lib packages..
11671                // By definition, we need to copy both 32 and 64 bit libraries for
11672                // such packages.
11673                if (pkg.cpuAbiOverride != null
11674                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11675                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11676                }
11677
11678                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11679                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11680                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11681                    if (extractLibs) {
11682                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11683                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11684                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11685                                useIsaSpecificSubdirs);
11686                    } else {
11687                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11688                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11689                    }
11690                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11691                }
11692
11693                // Shared library native code should be in the APK zip aligned
11694                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11695                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11696                            "Shared library native lib extraction not supported");
11697                }
11698
11699                maybeThrowExceptionForMultiArchCopy(
11700                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11701
11702                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11703                    if (extractLibs) {
11704                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11705                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11706                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11707                                useIsaSpecificSubdirs);
11708                    } else {
11709                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11710                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11711                    }
11712                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11713                }
11714
11715                maybeThrowExceptionForMultiArchCopy(
11716                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11717
11718                if (abi64 >= 0) {
11719                    // Shared library native libs should be in the APK zip aligned
11720                    if (extractLibs && pkg.isLibrary()) {
11721                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11722                                "Shared library native lib extraction not supported");
11723                    }
11724                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11725                }
11726
11727                if (abi32 >= 0) {
11728                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11729                    if (abi64 >= 0) {
11730                        if (pkg.use32bitAbi) {
11731                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11732                            pkg.applicationInfo.primaryCpuAbi = abi;
11733                        } else {
11734                            pkg.applicationInfo.secondaryCpuAbi = abi;
11735                        }
11736                    } else {
11737                        pkg.applicationInfo.primaryCpuAbi = abi;
11738                    }
11739                }
11740            } else {
11741                String[] abiList = (cpuAbiOverride != null) ?
11742                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11743
11744                // Enable gross and lame hacks for apps that are built with old
11745                // SDK tools. We must scan their APKs for renderscript bitcode and
11746                // not launch them if it's present. Don't bother checking on devices
11747                // that don't have 64 bit support.
11748                boolean needsRenderScriptOverride = false;
11749                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11750                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11751                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11752                    needsRenderScriptOverride = true;
11753                }
11754
11755                final int copyRet;
11756                if (extractLibs) {
11757                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11758                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11759                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11760                } else {
11761                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11762                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11763                }
11764                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11765
11766                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11767                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11768                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11769                }
11770
11771                if (copyRet >= 0) {
11772                    // Shared libraries that have native libs must be multi-architecture
11773                    if (pkg.isLibrary()) {
11774                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11775                                "Shared library with native libs must be multiarch");
11776                    }
11777                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11778                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11779                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11780                } else if (needsRenderScriptOverride) {
11781                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11782                }
11783            }
11784        } catch (IOException ioe) {
11785            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11786        } finally {
11787            IoUtils.closeQuietly(handle);
11788        }
11789
11790        // Now that we've calculated the ABIs and determined if it's an internal app,
11791        // we will go ahead and populate the nativeLibraryPath.
11792        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11793    }
11794
11795    /**
11796     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11797     * i.e, so that all packages can be run inside a single process if required.
11798     *
11799     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11800     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11801     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11802     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11803     * updating a package that belongs to a shared user.
11804     *
11805     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11806     * adds unnecessary complexity.
11807     */
11808    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11809            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11810        List<String> changedAbiCodePath = null;
11811        String requiredInstructionSet = null;
11812        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11813            requiredInstructionSet = VMRuntime.getInstructionSet(
11814                     scannedPackage.applicationInfo.primaryCpuAbi);
11815        }
11816
11817        PackageSetting requirer = null;
11818        for (PackageSetting ps : packagesForUser) {
11819            // If packagesForUser contains scannedPackage, we skip it. This will happen
11820            // when scannedPackage is an update of an existing package. Without this check,
11821            // we will never be able to change the ABI of any package belonging to a shared
11822            // user, even if it's compatible with other packages.
11823            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11824                if (ps.primaryCpuAbiString == null) {
11825                    continue;
11826                }
11827
11828                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11829                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11830                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11831                    // this but there's not much we can do.
11832                    String errorMessage = "Instruction set mismatch, "
11833                            + ((requirer == null) ? "[caller]" : requirer)
11834                            + " requires " + requiredInstructionSet + " whereas " + ps
11835                            + " requires " + instructionSet;
11836                    Slog.w(TAG, errorMessage);
11837                }
11838
11839                if (requiredInstructionSet == null) {
11840                    requiredInstructionSet = instructionSet;
11841                    requirer = ps;
11842                }
11843            }
11844        }
11845
11846        if (requiredInstructionSet != null) {
11847            String adjustedAbi;
11848            if (requirer != null) {
11849                // requirer != null implies that either scannedPackage was null or that scannedPackage
11850                // did not require an ABI, in which case we have to adjust scannedPackage to match
11851                // the ABI of the set (which is the same as requirer's ABI)
11852                adjustedAbi = requirer.primaryCpuAbiString;
11853                if (scannedPackage != null) {
11854                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11855                }
11856            } else {
11857                // requirer == null implies that we're updating all ABIs in the set to
11858                // match scannedPackage.
11859                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11860            }
11861
11862            for (PackageSetting ps : packagesForUser) {
11863                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11864                    if (ps.primaryCpuAbiString != null) {
11865                        continue;
11866                    }
11867
11868                    ps.primaryCpuAbiString = adjustedAbi;
11869                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11870                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11871                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11872                        if (DEBUG_ABI_SELECTION) {
11873                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11874                                    + " (requirer="
11875                                    + (requirer != null ? requirer.pkg : "null")
11876                                    + ", scannedPackage="
11877                                    + (scannedPackage != null ? scannedPackage : "null")
11878                                    + ")");
11879                        }
11880                        if (changedAbiCodePath == null) {
11881                            changedAbiCodePath = new ArrayList<>();
11882                        }
11883                        changedAbiCodePath.add(ps.codePathString);
11884                    }
11885                }
11886            }
11887        }
11888        return changedAbiCodePath;
11889    }
11890
11891    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11892        synchronized (mPackages) {
11893            mResolverReplaced = true;
11894            // Set up information for custom user intent resolution activity.
11895            mResolveActivity.applicationInfo = pkg.applicationInfo;
11896            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11897            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11898            mResolveActivity.processName = pkg.applicationInfo.packageName;
11899            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11900            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11901                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11902            mResolveActivity.theme = 0;
11903            mResolveActivity.exported = true;
11904            mResolveActivity.enabled = true;
11905            mResolveInfo.activityInfo = mResolveActivity;
11906            mResolveInfo.priority = 0;
11907            mResolveInfo.preferredOrder = 0;
11908            mResolveInfo.match = 0;
11909            mResolveComponentName = mCustomResolverComponentName;
11910            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11911                    mResolveComponentName);
11912        }
11913    }
11914
11915    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11916        if (installerActivity == null) {
11917            if (DEBUG_INSTANT) {
11918                Slog.d(TAG, "Clear ephemeral installer activity");
11919            }
11920            mInstantAppInstallerActivity = null;
11921            return;
11922        }
11923
11924        if (DEBUG_INSTANT) {
11925            Slog.d(TAG, "Set ephemeral installer activity: "
11926                    + installerActivity.getComponentName());
11927        }
11928        // Set up information for ephemeral installer activity
11929        mInstantAppInstallerActivity = installerActivity;
11930        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11931                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11932        mInstantAppInstallerActivity.exported = true;
11933        mInstantAppInstallerActivity.enabled = true;
11934        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11935        mInstantAppInstallerInfo.priority = 1;
11936        mInstantAppInstallerInfo.preferredOrder = 1;
11937        mInstantAppInstallerInfo.isDefault = true;
11938        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11939                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11940    }
11941
11942    private static String calculateBundledApkRoot(final String codePathString) {
11943        final File codePath = new File(codePathString);
11944        final File codeRoot;
11945        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11946            codeRoot = Environment.getRootDirectory();
11947        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11948            codeRoot = Environment.getOemDirectory();
11949        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11950            codeRoot = Environment.getVendorDirectory();
11951        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11952            codeRoot = Environment.getOdmDirectory();
11953        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11954            codeRoot = Environment.getProductDirectory();
11955        } else {
11956            // Unrecognized code path; take its top real segment as the apk root:
11957            // e.g. /something/app/blah.apk => /something
11958            try {
11959                File f = codePath.getCanonicalFile();
11960                File parent = f.getParentFile();    // non-null because codePath is a file
11961                File tmp;
11962                while ((tmp = parent.getParentFile()) != null) {
11963                    f = parent;
11964                    parent = tmp;
11965                }
11966                codeRoot = f;
11967                Slog.w(TAG, "Unrecognized code path "
11968                        + codePath + " - using " + codeRoot);
11969            } catch (IOException e) {
11970                // Can't canonicalize the code path -- shenanigans?
11971                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11972                return Environment.getRootDirectory().getPath();
11973            }
11974        }
11975        return codeRoot.getPath();
11976    }
11977
11978    /**
11979     * Derive and set the location of native libraries for the given package,
11980     * which varies depending on where and how the package was installed.
11981     */
11982    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11983        final ApplicationInfo info = pkg.applicationInfo;
11984        final String codePath = pkg.codePath;
11985        final File codeFile = new File(codePath);
11986        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11987        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11988
11989        info.nativeLibraryRootDir = null;
11990        info.nativeLibraryRootRequiresIsa = false;
11991        info.nativeLibraryDir = null;
11992        info.secondaryNativeLibraryDir = null;
11993
11994        if (isApkFile(codeFile)) {
11995            // Monolithic install
11996            if (bundledApp) {
11997                // If "/system/lib64/apkname" exists, assume that is the per-package
11998                // native library directory to use; otherwise use "/system/lib/apkname".
11999                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12000                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12001                        getPrimaryInstructionSet(info));
12002
12003                // This is a bundled system app so choose the path based on the ABI.
12004                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12005                // is just the default path.
12006                final String apkName = deriveCodePathName(codePath);
12007                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12008                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12009                        apkName).getAbsolutePath();
12010
12011                if (info.secondaryCpuAbi != null) {
12012                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12013                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12014                            secondaryLibDir, apkName).getAbsolutePath();
12015                }
12016            } else if (asecApp) {
12017                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12018                        .getAbsolutePath();
12019            } else {
12020                final String apkName = deriveCodePathName(codePath);
12021                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12022                        .getAbsolutePath();
12023            }
12024
12025            info.nativeLibraryRootRequiresIsa = false;
12026            info.nativeLibraryDir = info.nativeLibraryRootDir;
12027        } else {
12028            // Cluster install
12029            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12030            info.nativeLibraryRootRequiresIsa = true;
12031
12032            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12033                    getPrimaryInstructionSet(info)).getAbsolutePath();
12034
12035            if (info.secondaryCpuAbi != null) {
12036                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12037                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12038            }
12039        }
12040    }
12041
12042    /**
12043     * Calculate the abis and roots for a bundled app. These can uniquely
12044     * be determined from the contents of the system partition, i.e whether
12045     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12046     * of this information, and instead assume that the system was built
12047     * sensibly.
12048     */
12049    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12050                                           PackageSetting pkgSetting) {
12051        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12052
12053        // If "/system/lib64/apkname" exists, assume that is the per-package
12054        // native library directory to use; otherwise use "/system/lib/apkname".
12055        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12056        setBundledAppAbi(pkg, apkRoot, apkName);
12057        // pkgSetting might be null during rescan following uninstall of updates
12058        // to a bundled app, so accommodate that possibility.  The settings in
12059        // that case will be established later from the parsed package.
12060        //
12061        // If the settings aren't null, sync them up with what we've just derived.
12062        // note that apkRoot isn't stored in the package settings.
12063        if (pkgSetting != null) {
12064            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12065            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12066        }
12067    }
12068
12069    /**
12070     * Deduces the ABI of a bundled app and sets the relevant fields on the
12071     * parsed pkg object.
12072     *
12073     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12074     *        under which system libraries are installed.
12075     * @param apkName the name of the installed package.
12076     */
12077    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12078        final File codeFile = new File(pkg.codePath);
12079
12080        final boolean has64BitLibs;
12081        final boolean has32BitLibs;
12082        if (isApkFile(codeFile)) {
12083            // Monolithic install
12084            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12085            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12086        } else {
12087            // Cluster install
12088            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12089            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12090                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12091                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12092                has64BitLibs = (new File(rootDir, isa)).exists();
12093            } else {
12094                has64BitLibs = false;
12095            }
12096            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12097                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12098                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12099                has32BitLibs = (new File(rootDir, isa)).exists();
12100            } else {
12101                has32BitLibs = false;
12102            }
12103        }
12104
12105        if (has64BitLibs && !has32BitLibs) {
12106            // The package has 64 bit libs, but not 32 bit libs. Its primary
12107            // ABI should be 64 bit. We can safely assume here that the bundled
12108            // native libraries correspond to the most preferred ABI in the list.
12109
12110            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12111            pkg.applicationInfo.secondaryCpuAbi = null;
12112        } else if (has32BitLibs && !has64BitLibs) {
12113            // The package has 32 bit libs but not 64 bit libs. Its primary
12114            // ABI should be 32 bit.
12115
12116            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12117            pkg.applicationInfo.secondaryCpuAbi = null;
12118        } else if (has32BitLibs && has64BitLibs) {
12119            // The application has both 64 and 32 bit bundled libraries. We check
12120            // here that the app declares multiArch support, and warn if it doesn't.
12121            //
12122            // We will be lenient here and record both ABIs. The primary will be the
12123            // ABI that's higher on the list, i.e, a device that's configured to prefer
12124            // 64 bit apps will see a 64 bit primary ABI,
12125
12126            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12127                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12128            }
12129
12130            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12131                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12132                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12133            } else {
12134                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12135                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12136            }
12137        } else {
12138            pkg.applicationInfo.primaryCpuAbi = null;
12139            pkg.applicationInfo.secondaryCpuAbi = null;
12140        }
12141    }
12142
12143    private void killApplication(String pkgName, int appId, String reason) {
12144        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12145    }
12146
12147    private void killApplication(String pkgName, int appId, int userId, String reason) {
12148        // Request the ActivityManager to kill the process(only for existing packages)
12149        // so that we do not end up in a confused state while the user is still using the older
12150        // version of the application while the new one gets installed.
12151        final long token = Binder.clearCallingIdentity();
12152        try {
12153            IActivityManager am = ActivityManager.getService();
12154            if (am != null) {
12155                try {
12156                    am.killApplication(pkgName, appId, userId, reason);
12157                } catch (RemoteException e) {
12158                }
12159            }
12160        } finally {
12161            Binder.restoreCallingIdentity(token);
12162        }
12163    }
12164
12165    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12166        // Remove the parent package setting
12167        PackageSetting ps = (PackageSetting) pkg.mExtras;
12168        if (ps != null) {
12169            removePackageLI(ps, chatty);
12170        }
12171        // Remove the child package setting
12172        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12173        for (int i = 0; i < childCount; i++) {
12174            PackageParser.Package childPkg = pkg.childPackages.get(i);
12175            ps = (PackageSetting) childPkg.mExtras;
12176            if (ps != null) {
12177                removePackageLI(ps, chatty);
12178            }
12179        }
12180    }
12181
12182    void removePackageLI(PackageSetting ps, boolean chatty) {
12183        if (DEBUG_INSTALL) {
12184            if (chatty)
12185                Log.d(TAG, "Removing package " + ps.name);
12186        }
12187
12188        // writer
12189        synchronized (mPackages) {
12190            mPackages.remove(ps.name);
12191            final PackageParser.Package pkg = ps.pkg;
12192            if (pkg != null) {
12193                cleanPackageDataStructuresLILPw(pkg, chatty);
12194            }
12195        }
12196    }
12197
12198    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12199        if (DEBUG_INSTALL) {
12200            if (chatty)
12201                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12202        }
12203
12204        // writer
12205        synchronized (mPackages) {
12206            // Remove the parent package
12207            mPackages.remove(pkg.applicationInfo.packageName);
12208            cleanPackageDataStructuresLILPw(pkg, chatty);
12209
12210            // Remove the child packages
12211            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12212            for (int i = 0; i < childCount; i++) {
12213                PackageParser.Package childPkg = pkg.childPackages.get(i);
12214                mPackages.remove(childPkg.applicationInfo.packageName);
12215                cleanPackageDataStructuresLILPw(childPkg, chatty);
12216            }
12217        }
12218    }
12219
12220    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12221        int N = pkg.providers.size();
12222        StringBuilder r = null;
12223        int i;
12224        for (i=0; i<N; i++) {
12225            PackageParser.Provider p = pkg.providers.get(i);
12226            mProviders.removeProvider(p);
12227            if (p.info.authority == null) {
12228
12229                /* There was another ContentProvider with this authority when
12230                 * this app was installed so this authority is null,
12231                 * Ignore it as we don't have to unregister the provider.
12232                 */
12233                continue;
12234            }
12235            String names[] = p.info.authority.split(";");
12236            for (int j = 0; j < names.length; j++) {
12237                if (mProvidersByAuthority.get(names[j]) == p) {
12238                    mProvidersByAuthority.remove(names[j]);
12239                    if (DEBUG_REMOVE) {
12240                        if (chatty)
12241                            Log.d(TAG, "Unregistered content provider: " + names[j]
12242                                    + ", className = " + p.info.name + ", isSyncable = "
12243                                    + p.info.isSyncable);
12244                    }
12245                }
12246            }
12247            if (DEBUG_REMOVE && chatty) {
12248                if (r == null) {
12249                    r = new StringBuilder(256);
12250                } else {
12251                    r.append(' ');
12252                }
12253                r.append(p.info.name);
12254            }
12255        }
12256        if (r != null) {
12257            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12258        }
12259
12260        N = pkg.services.size();
12261        r = null;
12262        for (i=0; i<N; i++) {
12263            PackageParser.Service s = pkg.services.get(i);
12264            mServices.removeService(s);
12265            if (chatty) {
12266                if (r == null) {
12267                    r = new StringBuilder(256);
12268                } else {
12269                    r.append(' ');
12270                }
12271                r.append(s.info.name);
12272            }
12273        }
12274        if (r != null) {
12275            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12276        }
12277
12278        N = pkg.receivers.size();
12279        r = null;
12280        for (i=0; i<N; i++) {
12281            PackageParser.Activity a = pkg.receivers.get(i);
12282            mReceivers.removeActivity(a, "receiver");
12283            if (DEBUG_REMOVE && chatty) {
12284                if (r == null) {
12285                    r = new StringBuilder(256);
12286                } else {
12287                    r.append(' ');
12288                }
12289                r.append(a.info.name);
12290            }
12291        }
12292        if (r != null) {
12293            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12294        }
12295
12296        N = pkg.activities.size();
12297        r = null;
12298        for (i=0; i<N; i++) {
12299            PackageParser.Activity a = pkg.activities.get(i);
12300            mActivities.removeActivity(a, "activity");
12301            if (DEBUG_REMOVE && chatty) {
12302                if (r == null) {
12303                    r = new StringBuilder(256);
12304                } else {
12305                    r.append(' ');
12306                }
12307                r.append(a.info.name);
12308            }
12309        }
12310        if (r != null) {
12311            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12312        }
12313
12314        mPermissionManager.removeAllPermissions(pkg, chatty);
12315
12316        N = pkg.instrumentation.size();
12317        r = null;
12318        for (i=0; i<N; i++) {
12319            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12320            mInstrumentation.remove(a.getComponentName());
12321            if (DEBUG_REMOVE && chatty) {
12322                if (r == null) {
12323                    r = new StringBuilder(256);
12324                } else {
12325                    r.append(' ');
12326                }
12327                r.append(a.info.name);
12328            }
12329        }
12330        if (r != null) {
12331            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12332        }
12333
12334        r = null;
12335        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12336            // Only system apps can hold shared libraries.
12337            if (pkg.libraryNames != null) {
12338                for (i = 0; i < pkg.libraryNames.size(); i++) {
12339                    String name = pkg.libraryNames.get(i);
12340                    if (removeSharedLibraryLPw(name, 0)) {
12341                        if (DEBUG_REMOVE && chatty) {
12342                            if (r == null) {
12343                                r = new StringBuilder(256);
12344                            } else {
12345                                r.append(' ');
12346                            }
12347                            r.append(name);
12348                        }
12349                    }
12350                }
12351            }
12352        }
12353
12354        r = null;
12355
12356        // Any package can hold static shared libraries.
12357        if (pkg.staticSharedLibName != null) {
12358            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12359                if (DEBUG_REMOVE && chatty) {
12360                    if (r == null) {
12361                        r = new StringBuilder(256);
12362                    } else {
12363                        r.append(' ');
12364                    }
12365                    r.append(pkg.staticSharedLibName);
12366                }
12367            }
12368        }
12369
12370        if (r != null) {
12371            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12372        }
12373    }
12374
12375
12376    final class ActivityIntentResolver
12377            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12378        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12379                boolean defaultOnly, int userId) {
12380            if (!sUserManager.exists(userId)) return null;
12381            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12382            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12383        }
12384
12385        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12386                int userId) {
12387            if (!sUserManager.exists(userId)) return null;
12388            mFlags = flags;
12389            return super.queryIntent(intent, resolvedType,
12390                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12391                    userId);
12392        }
12393
12394        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12395                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12396            if (!sUserManager.exists(userId)) return null;
12397            if (packageActivities == null) {
12398                return null;
12399            }
12400            mFlags = flags;
12401            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12402            final int N = packageActivities.size();
12403            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12404                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12405
12406            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12407            for (int i = 0; i < N; ++i) {
12408                intentFilters = packageActivities.get(i).intents;
12409                if (intentFilters != null && intentFilters.size() > 0) {
12410                    PackageParser.ActivityIntentInfo[] array =
12411                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12412                    intentFilters.toArray(array);
12413                    listCut.add(array);
12414                }
12415            }
12416            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12417        }
12418
12419        /**
12420         * Finds a privileged activity that matches the specified activity names.
12421         */
12422        private PackageParser.Activity findMatchingActivity(
12423                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12424            for (PackageParser.Activity sysActivity : activityList) {
12425                if (sysActivity.info.name.equals(activityInfo.name)) {
12426                    return sysActivity;
12427                }
12428                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12429                    return sysActivity;
12430                }
12431                if (sysActivity.info.targetActivity != null) {
12432                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12433                        return sysActivity;
12434                    }
12435                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12436                        return sysActivity;
12437                    }
12438                }
12439            }
12440            return null;
12441        }
12442
12443        public class IterGenerator<E> {
12444            public Iterator<E> generate(ActivityIntentInfo info) {
12445                return null;
12446            }
12447        }
12448
12449        public class ActionIterGenerator extends IterGenerator<String> {
12450            @Override
12451            public Iterator<String> generate(ActivityIntentInfo info) {
12452                return info.actionsIterator();
12453            }
12454        }
12455
12456        public class CategoriesIterGenerator extends IterGenerator<String> {
12457            @Override
12458            public Iterator<String> generate(ActivityIntentInfo info) {
12459                return info.categoriesIterator();
12460            }
12461        }
12462
12463        public class SchemesIterGenerator extends IterGenerator<String> {
12464            @Override
12465            public Iterator<String> generate(ActivityIntentInfo info) {
12466                return info.schemesIterator();
12467            }
12468        }
12469
12470        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12471            @Override
12472            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12473                return info.authoritiesIterator();
12474            }
12475        }
12476
12477        /**
12478         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12479         * MODIFIED. Do not pass in a list that should not be changed.
12480         */
12481        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12482                IterGenerator<T> generator, Iterator<T> searchIterator) {
12483            // loop through the set of actions; every one must be found in the intent filter
12484            while (searchIterator.hasNext()) {
12485                // we must have at least one filter in the list to consider a match
12486                if (intentList.size() == 0) {
12487                    break;
12488                }
12489
12490                final T searchAction = searchIterator.next();
12491
12492                // loop through the set of intent filters
12493                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12494                while (intentIter.hasNext()) {
12495                    final ActivityIntentInfo intentInfo = intentIter.next();
12496                    boolean selectionFound = false;
12497
12498                    // loop through the intent filter's selection criteria; at least one
12499                    // of them must match the searched criteria
12500                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12501                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12502                        final T intentSelection = intentSelectionIter.next();
12503                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12504                            selectionFound = true;
12505                            break;
12506                        }
12507                    }
12508
12509                    // the selection criteria wasn't found in this filter's set; this filter
12510                    // is not a potential match
12511                    if (!selectionFound) {
12512                        intentIter.remove();
12513                    }
12514                }
12515            }
12516        }
12517
12518        private boolean isProtectedAction(ActivityIntentInfo filter) {
12519            final Iterator<String> actionsIter = filter.actionsIterator();
12520            while (actionsIter != null && actionsIter.hasNext()) {
12521                final String filterAction = actionsIter.next();
12522                if (PROTECTED_ACTIONS.contains(filterAction)) {
12523                    return true;
12524                }
12525            }
12526            return false;
12527        }
12528
12529        /**
12530         * Adjusts the priority of the given intent filter according to policy.
12531         * <p>
12532         * <ul>
12533         * <li>The priority for non privileged applications is capped to '0'</li>
12534         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12535         * <li>The priority for unbundled updates to privileged applications is capped to the
12536         *      priority defined on the system partition</li>
12537         * </ul>
12538         * <p>
12539         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12540         * allowed to obtain any priority on any action.
12541         */
12542        private void adjustPriority(
12543                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12544            // nothing to do; priority is fine as-is
12545            if (intent.getPriority() <= 0) {
12546                return;
12547            }
12548
12549            final ActivityInfo activityInfo = intent.activity.info;
12550            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12551
12552            final boolean privilegedApp =
12553                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12554            if (!privilegedApp) {
12555                // non-privileged applications can never define a priority >0
12556                if (DEBUG_FILTERS) {
12557                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12558                            + " package: " + applicationInfo.packageName
12559                            + " activity: " + intent.activity.className
12560                            + " origPrio: " + intent.getPriority());
12561                }
12562                intent.setPriority(0);
12563                return;
12564            }
12565
12566            if (systemActivities == null) {
12567                // the system package is not disabled; we're parsing the system partition
12568                if (isProtectedAction(intent)) {
12569                    if (mDeferProtectedFilters) {
12570                        // We can't deal with these just yet. No component should ever obtain a
12571                        // >0 priority for a protected actions, with ONE exception -- the setup
12572                        // wizard. The setup wizard, however, cannot be known until we're able to
12573                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12574                        // until all intent filters have been processed. Chicken, meet egg.
12575                        // Let the filter temporarily have a high priority and rectify the
12576                        // priorities after all system packages have been scanned.
12577                        mProtectedFilters.add(intent);
12578                        if (DEBUG_FILTERS) {
12579                            Slog.i(TAG, "Protected action; save for later;"
12580                                    + " package: " + applicationInfo.packageName
12581                                    + " activity: " + intent.activity.className
12582                                    + " origPrio: " + intent.getPriority());
12583                        }
12584                        return;
12585                    } else {
12586                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12587                            Slog.i(TAG, "No setup wizard;"
12588                                + " All protected intents capped to priority 0");
12589                        }
12590                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12591                            if (DEBUG_FILTERS) {
12592                                Slog.i(TAG, "Found setup wizard;"
12593                                    + " allow priority " + intent.getPriority() + ";"
12594                                    + " package: " + intent.activity.info.packageName
12595                                    + " activity: " + intent.activity.className
12596                                    + " priority: " + intent.getPriority());
12597                            }
12598                            // setup wizard gets whatever it wants
12599                            return;
12600                        }
12601                        if (DEBUG_FILTERS) {
12602                            Slog.i(TAG, "Protected action; cap priority to 0;"
12603                                    + " package: " + intent.activity.info.packageName
12604                                    + " activity: " + intent.activity.className
12605                                    + " origPrio: " + intent.getPriority());
12606                        }
12607                        intent.setPriority(0);
12608                        return;
12609                    }
12610                }
12611                // privileged apps on the system image get whatever priority they request
12612                return;
12613            }
12614
12615            // privileged app unbundled update ... try to find the same activity
12616            final PackageParser.Activity foundActivity =
12617                    findMatchingActivity(systemActivities, activityInfo);
12618            if (foundActivity == null) {
12619                // this is a new activity; it cannot obtain >0 priority
12620                if (DEBUG_FILTERS) {
12621                    Slog.i(TAG, "New activity; cap priority to 0;"
12622                            + " package: " + applicationInfo.packageName
12623                            + " activity: " + intent.activity.className
12624                            + " origPrio: " + intent.getPriority());
12625                }
12626                intent.setPriority(0);
12627                return;
12628            }
12629
12630            // found activity, now check for filter equivalence
12631
12632            // a shallow copy is enough; we modify the list, not its contents
12633            final List<ActivityIntentInfo> intentListCopy =
12634                    new ArrayList<>(foundActivity.intents);
12635            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12636
12637            // find matching action subsets
12638            final Iterator<String> actionsIterator = intent.actionsIterator();
12639            if (actionsIterator != null) {
12640                getIntentListSubset(
12641                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12642                if (intentListCopy.size() == 0) {
12643                    // no more intents to match; we're not equivalent
12644                    if (DEBUG_FILTERS) {
12645                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12646                                + " package: " + applicationInfo.packageName
12647                                + " activity: " + intent.activity.className
12648                                + " origPrio: " + intent.getPriority());
12649                    }
12650                    intent.setPriority(0);
12651                    return;
12652                }
12653            }
12654
12655            // find matching category subsets
12656            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12657            if (categoriesIterator != null) {
12658                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12659                        categoriesIterator);
12660                if (intentListCopy.size() == 0) {
12661                    // no more intents to match; we're not equivalent
12662                    if (DEBUG_FILTERS) {
12663                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12664                                + " package: " + applicationInfo.packageName
12665                                + " activity: " + intent.activity.className
12666                                + " origPrio: " + intent.getPriority());
12667                    }
12668                    intent.setPriority(0);
12669                    return;
12670                }
12671            }
12672
12673            // find matching schemes subsets
12674            final Iterator<String> schemesIterator = intent.schemesIterator();
12675            if (schemesIterator != null) {
12676                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12677                        schemesIterator);
12678                if (intentListCopy.size() == 0) {
12679                    // no more intents to match; we're not equivalent
12680                    if (DEBUG_FILTERS) {
12681                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12682                                + " package: " + applicationInfo.packageName
12683                                + " activity: " + intent.activity.className
12684                                + " origPrio: " + intent.getPriority());
12685                    }
12686                    intent.setPriority(0);
12687                    return;
12688                }
12689            }
12690
12691            // find matching authorities subsets
12692            final Iterator<IntentFilter.AuthorityEntry>
12693                    authoritiesIterator = intent.authoritiesIterator();
12694            if (authoritiesIterator != null) {
12695                getIntentListSubset(intentListCopy,
12696                        new AuthoritiesIterGenerator(),
12697                        authoritiesIterator);
12698                if (intentListCopy.size() == 0) {
12699                    // no more intents to match; we're not equivalent
12700                    if (DEBUG_FILTERS) {
12701                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12702                                + " package: " + applicationInfo.packageName
12703                                + " activity: " + intent.activity.className
12704                                + " origPrio: " + intent.getPriority());
12705                    }
12706                    intent.setPriority(0);
12707                    return;
12708                }
12709            }
12710
12711            // we found matching filter(s); app gets the max priority of all intents
12712            int cappedPriority = 0;
12713            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12714                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12715            }
12716            if (intent.getPriority() > cappedPriority) {
12717                if (DEBUG_FILTERS) {
12718                    Slog.i(TAG, "Found matching filter(s);"
12719                            + " cap priority to " + cappedPriority + ";"
12720                            + " package: " + applicationInfo.packageName
12721                            + " activity: " + intent.activity.className
12722                            + " origPrio: " + intent.getPriority());
12723                }
12724                intent.setPriority(cappedPriority);
12725                return;
12726            }
12727            // all this for nothing; the requested priority was <= what was on the system
12728        }
12729
12730        public final void addActivity(PackageParser.Activity a, String type) {
12731            mActivities.put(a.getComponentName(), a);
12732            if (DEBUG_SHOW_INFO)
12733                Log.v(
12734                TAG, "  " + type + " " +
12735                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12736            if (DEBUG_SHOW_INFO)
12737                Log.v(TAG, "    Class=" + a.info.name);
12738            final int NI = a.intents.size();
12739            for (int j=0; j<NI; j++) {
12740                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12741                if ("activity".equals(type)) {
12742                    final PackageSetting ps =
12743                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12744                    final List<PackageParser.Activity> systemActivities =
12745                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12746                    adjustPriority(systemActivities, intent);
12747                }
12748                if (DEBUG_SHOW_INFO) {
12749                    Log.v(TAG, "    IntentFilter:");
12750                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12751                }
12752                if (!intent.debugCheck()) {
12753                    Log.w(TAG, "==> For Activity " + a.info.name);
12754                }
12755                addFilter(intent);
12756            }
12757        }
12758
12759        public final void removeActivity(PackageParser.Activity a, String type) {
12760            mActivities.remove(a.getComponentName());
12761            if (DEBUG_SHOW_INFO) {
12762                Log.v(TAG, "  " + type + " "
12763                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12764                                : a.info.name) + ":");
12765                Log.v(TAG, "    Class=" + a.info.name);
12766            }
12767            final int NI = a.intents.size();
12768            for (int j=0; j<NI; j++) {
12769                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12770                if (DEBUG_SHOW_INFO) {
12771                    Log.v(TAG, "    IntentFilter:");
12772                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12773                }
12774                removeFilter(intent);
12775            }
12776        }
12777
12778        @Override
12779        protected boolean allowFilterResult(
12780                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12781            ActivityInfo filterAi = filter.activity.info;
12782            for (int i=dest.size()-1; i>=0; i--) {
12783                ActivityInfo destAi = dest.get(i).activityInfo;
12784                if (destAi.name == filterAi.name
12785                        && destAi.packageName == filterAi.packageName) {
12786                    return false;
12787                }
12788            }
12789            return true;
12790        }
12791
12792        @Override
12793        protected ActivityIntentInfo[] newArray(int size) {
12794            return new ActivityIntentInfo[size];
12795        }
12796
12797        @Override
12798        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12799            if (!sUserManager.exists(userId)) return true;
12800            PackageParser.Package p = filter.activity.owner;
12801            if (p != null) {
12802                PackageSetting ps = (PackageSetting)p.mExtras;
12803                if (ps != null) {
12804                    // System apps are never considered stopped for purposes of
12805                    // filtering, because there may be no way for the user to
12806                    // actually re-launch them.
12807                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12808                            && ps.getStopped(userId);
12809                }
12810            }
12811            return false;
12812        }
12813
12814        @Override
12815        protected boolean isPackageForFilter(String packageName,
12816                PackageParser.ActivityIntentInfo info) {
12817            return packageName.equals(info.activity.owner.packageName);
12818        }
12819
12820        @Override
12821        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12822                int match, int userId) {
12823            if (!sUserManager.exists(userId)) return null;
12824            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12825                return null;
12826            }
12827            final PackageParser.Activity activity = info.activity;
12828            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12829            if (ps == null) {
12830                return null;
12831            }
12832            final PackageUserState userState = ps.readUserState(userId);
12833            ActivityInfo ai =
12834                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12835            if (ai == null) {
12836                return null;
12837            }
12838            final boolean matchExplicitlyVisibleOnly =
12839                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12840            final boolean matchVisibleToInstantApp =
12841                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12842            final boolean componentVisible =
12843                    matchVisibleToInstantApp
12844                    && info.isVisibleToInstantApp()
12845                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12846            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12847            // throw out filters that aren't visible to ephemeral apps
12848            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12849                return null;
12850            }
12851            // throw out instant app filters if we're not explicitly requesting them
12852            if (!matchInstantApp && userState.instantApp) {
12853                return null;
12854            }
12855            // throw out instant app filters if updates are available; will trigger
12856            // instant app resolution
12857            if (userState.instantApp && ps.isUpdateAvailable()) {
12858                return null;
12859            }
12860            final ResolveInfo res = new ResolveInfo();
12861            res.activityInfo = ai;
12862            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12863                res.filter = info;
12864            }
12865            if (info != null) {
12866                res.handleAllWebDataURI = info.handleAllWebDataURI();
12867            }
12868            res.priority = info.getPriority();
12869            res.preferredOrder = activity.owner.mPreferredOrder;
12870            //System.out.println("Result: " + res.activityInfo.className +
12871            //                   " = " + res.priority);
12872            res.match = match;
12873            res.isDefault = info.hasDefault;
12874            res.labelRes = info.labelRes;
12875            res.nonLocalizedLabel = info.nonLocalizedLabel;
12876            if (userNeedsBadging(userId)) {
12877                res.noResourceId = true;
12878            } else {
12879                res.icon = info.icon;
12880            }
12881            res.iconResourceId = info.icon;
12882            res.system = res.activityInfo.applicationInfo.isSystemApp();
12883            res.isInstantAppAvailable = userState.instantApp;
12884            return res;
12885        }
12886
12887        @Override
12888        protected void sortResults(List<ResolveInfo> results) {
12889            Collections.sort(results, mResolvePrioritySorter);
12890        }
12891
12892        @Override
12893        protected void dumpFilter(PrintWriter out, String prefix,
12894                PackageParser.ActivityIntentInfo filter) {
12895            out.print(prefix); out.print(
12896                    Integer.toHexString(System.identityHashCode(filter.activity)));
12897                    out.print(' ');
12898                    filter.activity.printComponentShortName(out);
12899                    out.print(" filter ");
12900                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12901        }
12902
12903        @Override
12904        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12905            return filter.activity;
12906        }
12907
12908        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12909            PackageParser.Activity activity = (PackageParser.Activity)label;
12910            out.print(prefix); out.print(
12911                    Integer.toHexString(System.identityHashCode(activity)));
12912                    out.print(' ');
12913                    activity.printComponentShortName(out);
12914            if (count > 1) {
12915                out.print(" ("); out.print(count); out.print(" filters)");
12916            }
12917            out.println();
12918        }
12919
12920        // Keys are String (activity class name), values are Activity.
12921        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12922                = new ArrayMap<ComponentName, PackageParser.Activity>();
12923        private int mFlags;
12924    }
12925
12926    private final class ServiceIntentResolver
12927            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12928        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12929                boolean defaultOnly, int userId) {
12930            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12931            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12932        }
12933
12934        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12935                int userId) {
12936            if (!sUserManager.exists(userId)) return null;
12937            mFlags = flags;
12938            return super.queryIntent(intent, resolvedType,
12939                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12940                    userId);
12941        }
12942
12943        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12944                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12945            if (!sUserManager.exists(userId)) return null;
12946            if (packageServices == null) {
12947                return null;
12948            }
12949            mFlags = flags;
12950            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12951            final int N = packageServices.size();
12952            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12953                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12954
12955            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12956            for (int i = 0; i < N; ++i) {
12957                intentFilters = packageServices.get(i).intents;
12958                if (intentFilters != null && intentFilters.size() > 0) {
12959                    PackageParser.ServiceIntentInfo[] array =
12960                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12961                    intentFilters.toArray(array);
12962                    listCut.add(array);
12963                }
12964            }
12965            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12966        }
12967
12968        public final void addService(PackageParser.Service s) {
12969            mServices.put(s.getComponentName(), s);
12970            if (DEBUG_SHOW_INFO) {
12971                Log.v(TAG, "  "
12972                        + (s.info.nonLocalizedLabel != null
12973                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12974                Log.v(TAG, "    Class=" + s.info.name);
12975            }
12976            final int NI = s.intents.size();
12977            int j;
12978            for (j=0; j<NI; j++) {
12979                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12980                if (DEBUG_SHOW_INFO) {
12981                    Log.v(TAG, "    IntentFilter:");
12982                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12983                }
12984                if (!intent.debugCheck()) {
12985                    Log.w(TAG, "==> For Service " + s.info.name);
12986                }
12987                addFilter(intent);
12988            }
12989        }
12990
12991        public final void removeService(PackageParser.Service s) {
12992            mServices.remove(s.getComponentName());
12993            if (DEBUG_SHOW_INFO) {
12994                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12995                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12996                Log.v(TAG, "    Class=" + s.info.name);
12997            }
12998            final int NI = s.intents.size();
12999            int j;
13000            for (j=0; j<NI; j++) {
13001                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13002                if (DEBUG_SHOW_INFO) {
13003                    Log.v(TAG, "    IntentFilter:");
13004                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13005                }
13006                removeFilter(intent);
13007            }
13008        }
13009
13010        @Override
13011        protected boolean allowFilterResult(
13012                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13013            ServiceInfo filterSi = filter.service.info;
13014            for (int i=dest.size()-1; i>=0; i--) {
13015                ServiceInfo destAi = dest.get(i).serviceInfo;
13016                if (destAi.name == filterSi.name
13017                        && destAi.packageName == filterSi.packageName) {
13018                    return false;
13019                }
13020            }
13021            return true;
13022        }
13023
13024        @Override
13025        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13026            return new PackageParser.ServiceIntentInfo[size];
13027        }
13028
13029        @Override
13030        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13031            if (!sUserManager.exists(userId)) return true;
13032            PackageParser.Package p = filter.service.owner;
13033            if (p != null) {
13034                PackageSetting ps = (PackageSetting)p.mExtras;
13035                if (ps != null) {
13036                    // System apps are never considered stopped for purposes of
13037                    // filtering, because there may be no way for the user to
13038                    // actually re-launch them.
13039                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13040                            && ps.getStopped(userId);
13041                }
13042            }
13043            return false;
13044        }
13045
13046        @Override
13047        protected boolean isPackageForFilter(String packageName,
13048                PackageParser.ServiceIntentInfo info) {
13049            return packageName.equals(info.service.owner.packageName);
13050        }
13051
13052        @Override
13053        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13054                int match, int userId) {
13055            if (!sUserManager.exists(userId)) return null;
13056            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13057            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13058                return null;
13059            }
13060            final PackageParser.Service service = info.service;
13061            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13062            if (ps == null) {
13063                return null;
13064            }
13065            final PackageUserState userState = ps.readUserState(userId);
13066            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13067                    userState, userId);
13068            if (si == null) {
13069                return null;
13070            }
13071            final boolean matchVisibleToInstantApp =
13072                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13073            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13074            // throw out filters that aren't visible to ephemeral apps
13075            if (matchVisibleToInstantApp
13076                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13077                return null;
13078            }
13079            // throw out ephemeral filters if we're not explicitly requesting them
13080            if (!isInstantApp && userState.instantApp) {
13081                return null;
13082            }
13083            // throw out instant app filters if updates are available; will trigger
13084            // instant app resolution
13085            if (userState.instantApp && ps.isUpdateAvailable()) {
13086                return null;
13087            }
13088            final ResolveInfo res = new ResolveInfo();
13089            res.serviceInfo = si;
13090            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13091                res.filter = filter;
13092            }
13093            res.priority = info.getPriority();
13094            res.preferredOrder = service.owner.mPreferredOrder;
13095            res.match = match;
13096            res.isDefault = info.hasDefault;
13097            res.labelRes = info.labelRes;
13098            res.nonLocalizedLabel = info.nonLocalizedLabel;
13099            res.icon = info.icon;
13100            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13101            return res;
13102        }
13103
13104        @Override
13105        protected void sortResults(List<ResolveInfo> results) {
13106            Collections.sort(results, mResolvePrioritySorter);
13107        }
13108
13109        @Override
13110        protected void dumpFilter(PrintWriter out, String prefix,
13111                PackageParser.ServiceIntentInfo filter) {
13112            out.print(prefix); out.print(
13113                    Integer.toHexString(System.identityHashCode(filter.service)));
13114                    out.print(' ');
13115                    filter.service.printComponentShortName(out);
13116                    out.print(" filter ");
13117                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13118                    if (filter.service.info.permission != null) {
13119                        out.print(" permission "); out.println(filter.service.info.permission);
13120                    } else {
13121                        out.println();
13122                    }
13123        }
13124
13125        @Override
13126        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13127            return filter.service;
13128        }
13129
13130        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13131            PackageParser.Service service = (PackageParser.Service)label;
13132            out.print(prefix); out.print(
13133                    Integer.toHexString(System.identityHashCode(service)));
13134                    out.print(' ');
13135                    service.printComponentShortName(out);
13136            if (count > 1) {
13137                out.print(" ("); out.print(count); out.print(" filters)");
13138            }
13139            out.println();
13140        }
13141
13142//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13143//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13144//            final List<ResolveInfo> retList = Lists.newArrayList();
13145//            while (i.hasNext()) {
13146//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13147//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13148//                    retList.add(resolveInfo);
13149//                }
13150//            }
13151//            return retList;
13152//        }
13153
13154        // Keys are String (activity class name), values are Activity.
13155        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13156                = new ArrayMap<ComponentName, PackageParser.Service>();
13157        private int mFlags;
13158    }
13159
13160    private final class ProviderIntentResolver
13161            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13162        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13163                boolean defaultOnly, int userId) {
13164            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13165            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13166        }
13167
13168        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13169                int userId) {
13170            if (!sUserManager.exists(userId))
13171                return null;
13172            mFlags = flags;
13173            return super.queryIntent(intent, resolvedType,
13174                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13175                    userId);
13176        }
13177
13178        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13179                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13180            if (!sUserManager.exists(userId))
13181                return null;
13182            if (packageProviders == null) {
13183                return null;
13184            }
13185            mFlags = flags;
13186            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13187            final int N = packageProviders.size();
13188            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13189                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13190
13191            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13192            for (int i = 0; i < N; ++i) {
13193                intentFilters = packageProviders.get(i).intents;
13194                if (intentFilters != null && intentFilters.size() > 0) {
13195                    PackageParser.ProviderIntentInfo[] array =
13196                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13197                    intentFilters.toArray(array);
13198                    listCut.add(array);
13199                }
13200            }
13201            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13202        }
13203
13204        public final void addProvider(PackageParser.Provider p) {
13205            if (mProviders.containsKey(p.getComponentName())) {
13206                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13207                return;
13208            }
13209
13210            mProviders.put(p.getComponentName(), p);
13211            if (DEBUG_SHOW_INFO) {
13212                Log.v(TAG, "  "
13213                        + (p.info.nonLocalizedLabel != null
13214                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13215                Log.v(TAG, "    Class=" + p.info.name);
13216            }
13217            final int NI = p.intents.size();
13218            int j;
13219            for (j = 0; j < NI; j++) {
13220                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13221                if (DEBUG_SHOW_INFO) {
13222                    Log.v(TAG, "    IntentFilter:");
13223                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13224                }
13225                if (!intent.debugCheck()) {
13226                    Log.w(TAG, "==> For Provider " + p.info.name);
13227                }
13228                addFilter(intent);
13229            }
13230        }
13231
13232        public final void removeProvider(PackageParser.Provider p) {
13233            mProviders.remove(p.getComponentName());
13234            if (DEBUG_SHOW_INFO) {
13235                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13236                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13237                Log.v(TAG, "    Class=" + p.info.name);
13238            }
13239            final int NI = p.intents.size();
13240            int j;
13241            for (j = 0; j < NI; j++) {
13242                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13243                if (DEBUG_SHOW_INFO) {
13244                    Log.v(TAG, "    IntentFilter:");
13245                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13246                }
13247                removeFilter(intent);
13248            }
13249        }
13250
13251        @Override
13252        protected boolean allowFilterResult(
13253                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13254            ProviderInfo filterPi = filter.provider.info;
13255            for (int i = dest.size() - 1; i >= 0; i--) {
13256                ProviderInfo destPi = dest.get(i).providerInfo;
13257                if (destPi.name == filterPi.name
13258                        && destPi.packageName == filterPi.packageName) {
13259                    return false;
13260                }
13261            }
13262            return true;
13263        }
13264
13265        @Override
13266        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13267            return new PackageParser.ProviderIntentInfo[size];
13268        }
13269
13270        @Override
13271        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13272            if (!sUserManager.exists(userId))
13273                return true;
13274            PackageParser.Package p = filter.provider.owner;
13275            if (p != null) {
13276                PackageSetting ps = (PackageSetting) p.mExtras;
13277                if (ps != null) {
13278                    // System apps are never considered stopped for purposes of
13279                    // filtering, because there may be no way for the user to
13280                    // actually re-launch them.
13281                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13282                            && ps.getStopped(userId);
13283                }
13284            }
13285            return false;
13286        }
13287
13288        @Override
13289        protected boolean isPackageForFilter(String packageName,
13290                PackageParser.ProviderIntentInfo info) {
13291            return packageName.equals(info.provider.owner.packageName);
13292        }
13293
13294        @Override
13295        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13296                int match, int userId) {
13297            if (!sUserManager.exists(userId))
13298                return null;
13299            final PackageParser.ProviderIntentInfo info = filter;
13300            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13301                return null;
13302            }
13303            final PackageParser.Provider provider = info.provider;
13304            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13305            if (ps == null) {
13306                return null;
13307            }
13308            final PackageUserState userState = ps.readUserState(userId);
13309            final boolean matchVisibleToInstantApp =
13310                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13311            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13312            // throw out filters that aren't visible to instant applications
13313            if (matchVisibleToInstantApp
13314                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13315                return null;
13316            }
13317            // throw out instant application filters if we're not explicitly requesting them
13318            if (!isInstantApp && userState.instantApp) {
13319                return null;
13320            }
13321            // throw out instant application filters if updates are available; will trigger
13322            // instant application resolution
13323            if (userState.instantApp && ps.isUpdateAvailable()) {
13324                return null;
13325            }
13326            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13327                    userState, userId);
13328            if (pi == null) {
13329                return null;
13330            }
13331            final ResolveInfo res = new ResolveInfo();
13332            res.providerInfo = pi;
13333            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13334                res.filter = filter;
13335            }
13336            res.priority = info.getPriority();
13337            res.preferredOrder = provider.owner.mPreferredOrder;
13338            res.match = match;
13339            res.isDefault = info.hasDefault;
13340            res.labelRes = info.labelRes;
13341            res.nonLocalizedLabel = info.nonLocalizedLabel;
13342            res.icon = info.icon;
13343            res.system = res.providerInfo.applicationInfo.isSystemApp();
13344            return res;
13345        }
13346
13347        @Override
13348        protected void sortResults(List<ResolveInfo> results) {
13349            Collections.sort(results, mResolvePrioritySorter);
13350        }
13351
13352        @Override
13353        protected void dumpFilter(PrintWriter out, String prefix,
13354                PackageParser.ProviderIntentInfo filter) {
13355            out.print(prefix);
13356            out.print(
13357                    Integer.toHexString(System.identityHashCode(filter.provider)));
13358            out.print(' ');
13359            filter.provider.printComponentShortName(out);
13360            out.print(" filter ");
13361            out.println(Integer.toHexString(System.identityHashCode(filter)));
13362        }
13363
13364        @Override
13365        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13366            return filter.provider;
13367        }
13368
13369        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13370            PackageParser.Provider provider = (PackageParser.Provider)label;
13371            out.print(prefix); out.print(
13372                    Integer.toHexString(System.identityHashCode(provider)));
13373                    out.print(' ');
13374                    provider.printComponentShortName(out);
13375            if (count > 1) {
13376                out.print(" ("); out.print(count); out.print(" filters)");
13377            }
13378            out.println();
13379        }
13380
13381        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13382                = new ArrayMap<ComponentName, PackageParser.Provider>();
13383        private int mFlags;
13384    }
13385
13386    static final class InstantAppIntentResolver
13387            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13388            AuxiliaryResolveInfo.AuxiliaryFilter> {
13389        /**
13390         * The result that has the highest defined order. Ordering applies on a
13391         * per-package basis. Mapping is from package name to Pair of order and
13392         * EphemeralResolveInfo.
13393         * <p>
13394         * NOTE: This is implemented as a field variable for convenience and efficiency.
13395         * By having a field variable, we're able to track filter ordering as soon as
13396         * a non-zero order is defined. Otherwise, multiple loops across the result set
13397         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13398         * this needs to be contained entirely within {@link #filterResults}.
13399         */
13400        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13401
13402        @Override
13403        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13404            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13405        }
13406
13407        @Override
13408        protected boolean isPackageForFilter(String packageName,
13409                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13410            return true;
13411        }
13412
13413        @Override
13414        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13415                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13416            if (!sUserManager.exists(userId)) {
13417                return null;
13418            }
13419            final String packageName = responseObj.resolveInfo.getPackageName();
13420            final Integer order = responseObj.getOrder();
13421            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13422                    mOrderResult.get(packageName);
13423            // ordering is enabled and this item's order isn't high enough
13424            if (lastOrderResult != null && lastOrderResult.first >= order) {
13425                return null;
13426            }
13427            final InstantAppResolveInfo res = responseObj.resolveInfo;
13428            if (order > 0) {
13429                // non-zero order, enable ordering
13430                mOrderResult.put(packageName, new Pair<>(order, res));
13431            }
13432            return responseObj;
13433        }
13434
13435        @Override
13436        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13437            // only do work if ordering is enabled [most of the time it won't be]
13438            if (mOrderResult.size() == 0) {
13439                return;
13440            }
13441            int resultSize = results.size();
13442            for (int i = 0; i < resultSize; i++) {
13443                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13444                final String packageName = info.getPackageName();
13445                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13446                if (savedInfo == null) {
13447                    // package doesn't having ordering
13448                    continue;
13449                }
13450                if (savedInfo.second == info) {
13451                    // circled back to the highest ordered item; remove from order list
13452                    mOrderResult.remove(packageName);
13453                    if (mOrderResult.size() == 0) {
13454                        // no more ordered items
13455                        break;
13456                    }
13457                    continue;
13458                }
13459                // item has a worse order, remove it from the result list
13460                results.remove(i);
13461                resultSize--;
13462                i--;
13463            }
13464        }
13465    }
13466
13467    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13468            new Comparator<ResolveInfo>() {
13469        public int compare(ResolveInfo r1, ResolveInfo r2) {
13470            int v1 = r1.priority;
13471            int v2 = r2.priority;
13472            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13473            if (v1 != v2) {
13474                return (v1 > v2) ? -1 : 1;
13475            }
13476            v1 = r1.preferredOrder;
13477            v2 = r2.preferredOrder;
13478            if (v1 != v2) {
13479                return (v1 > v2) ? -1 : 1;
13480            }
13481            if (r1.isDefault != r2.isDefault) {
13482                return r1.isDefault ? -1 : 1;
13483            }
13484            v1 = r1.match;
13485            v2 = r2.match;
13486            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13487            if (v1 != v2) {
13488                return (v1 > v2) ? -1 : 1;
13489            }
13490            if (r1.system != r2.system) {
13491                return r1.system ? -1 : 1;
13492            }
13493            if (r1.activityInfo != null) {
13494                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13495            }
13496            if (r1.serviceInfo != null) {
13497                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13498            }
13499            if (r1.providerInfo != null) {
13500                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13501            }
13502            return 0;
13503        }
13504    };
13505
13506    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13507            new Comparator<ProviderInfo>() {
13508        public int compare(ProviderInfo p1, ProviderInfo p2) {
13509            final int v1 = p1.initOrder;
13510            final int v2 = p2.initOrder;
13511            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13512        }
13513    };
13514
13515    @Override
13516    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13517            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13518            final int[] userIds, int[] instantUserIds) {
13519        mHandler.post(new Runnable() {
13520            @Override
13521            public void run() {
13522                try {
13523                    final IActivityManager am = ActivityManager.getService();
13524                    if (am == null) return;
13525                    final int[] resolvedUserIds;
13526                    if (userIds == null) {
13527                        resolvedUserIds = am.getRunningUserIds();
13528                    } else {
13529                        resolvedUserIds = userIds;
13530                    }
13531                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13532                            resolvedUserIds, false);
13533                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13534                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13535                                instantUserIds, true);
13536                    }
13537                } catch (RemoteException ex) {
13538                }
13539            }
13540        });
13541    }
13542
13543    @Override
13544    public void notifyPackageAdded(String packageName) {
13545        final PackageListObserver[] observers;
13546        synchronized (mPackages) {
13547            if (mPackageListObservers.size() == 0) {
13548                return;
13549            }
13550            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13551        }
13552        for (int i = observers.length - 1; i >= 0; --i) {
13553            observers[i].onPackageAdded(packageName);
13554        }
13555    }
13556
13557    @Override
13558    public void notifyPackageRemoved(String packageName) {
13559        final PackageListObserver[] observers;
13560        synchronized (mPackages) {
13561            if (mPackageListObservers.size() == 0) {
13562                return;
13563            }
13564            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13565        }
13566        for (int i = observers.length - 1; i >= 0; --i) {
13567            observers[i].onPackageRemoved(packageName);
13568        }
13569    }
13570
13571    /**
13572     * Sends a broadcast for the given action.
13573     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13574     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13575     * the system and applications allowed to see instant applications to receive package
13576     * lifecycle events for instant applications.
13577     */
13578    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13579            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13580            int[] userIds, boolean isInstantApp)
13581                    throws RemoteException {
13582        for (int id : userIds) {
13583            final Intent intent = new Intent(action,
13584                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13585            final String[] requiredPermissions =
13586                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13587            if (extras != null) {
13588                intent.putExtras(extras);
13589            }
13590            if (targetPkg != null) {
13591                intent.setPackage(targetPkg);
13592            }
13593            // Modify the UID when posting to other users
13594            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13595            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13596                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13597                intent.putExtra(Intent.EXTRA_UID, uid);
13598            }
13599            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13600            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13601            if (DEBUG_BROADCASTS) {
13602                RuntimeException here = new RuntimeException("here");
13603                here.fillInStackTrace();
13604                Slog.d(TAG, "Sending to user " + id + ": "
13605                        + intent.toShortString(false, true, false, false)
13606                        + " " + intent.getExtras(), here);
13607            }
13608            am.broadcastIntent(null, intent, null, finishedReceiver,
13609                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13610                    null, finishedReceiver != null, false, id);
13611        }
13612    }
13613
13614    /**
13615     * Check if the external storage media is available. This is true if there
13616     * is a mounted external storage medium or if the external storage is
13617     * emulated.
13618     */
13619    private boolean isExternalMediaAvailable() {
13620        return mMediaMounted || Environment.isExternalStorageEmulated();
13621    }
13622
13623    @Override
13624    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13625        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13626            return null;
13627        }
13628        if (!isExternalMediaAvailable()) {
13629                // If the external storage is no longer mounted at this point,
13630                // the caller may not have been able to delete all of this
13631                // packages files and can not delete any more.  Bail.
13632            return null;
13633        }
13634        synchronized (mPackages) {
13635            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13636            if (lastPackage != null) {
13637                pkgs.remove(lastPackage);
13638            }
13639            if (pkgs.size() > 0) {
13640                return pkgs.get(0);
13641            }
13642        }
13643        return null;
13644    }
13645
13646    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13647        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13648                userId, andCode ? 1 : 0, packageName);
13649        if (mSystemReady) {
13650            msg.sendToTarget();
13651        } else {
13652            if (mPostSystemReadyMessages == null) {
13653                mPostSystemReadyMessages = new ArrayList<>();
13654            }
13655            mPostSystemReadyMessages.add(msg);
13656        }
13657    }
13658
13659    void startCleaningPackages() {
13660        // reader
13661        if (!isExternalMediaAvailable()) {
13662            return;
13663        }
13664        synchronized (mPackages) {
13665            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13666                return;
13667            }
13668        }
13669        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13670        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13671        IActivityManager am = ActivityManager.getService();
13672        if (am != null) {
13673            int dcsUid = -1;
13674            synchronized (mPackages) {
13675                if (!mDefaultContainerWhitelisted) {
13676                    mDefaultContainerWhitelisted = true;
13677                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13678                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13679                }
13680            }
13681            try {
13682                if (dcsUid > 0) {
13683                    am.backgroundWhitelistUid(dcsUid);
13684                }
13685                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13686                        UserHandle.USER_SYSTEM);
13687            } catch (RemoteException e) {
13688            }
13689        }
13690    }
13691
13692    /**
13693     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13694     * it is acting on behalf on an enterprise or the user).
13695     *
13696     * Note that the ordering of the conditionals in this method is important. The checks we perform
13697     * are as follows, in this order:
13698     *
13699     * 1) If the install is being performed by a system app, we can trust the app to have set the
13700     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13701     *    what it is.
13702     * 2) If the install is being performed by a device or profile owner app, the install reason
13703     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13704     *    set the install reason correctly. If the app targets an older SDK version where install
13705     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13706     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13707     * 3) In all other cases, the install is being performed by a regular app that is neither part
13708     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13709     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13710     *    set to enterprise policy and if so, change it to unknown instead.
13711     */
13712    private int fixUpInstallReason(String installerPackageName, int installerUid,
13713            int installReason) {
13714        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13715                == PERMISSION_GRANTED) {
13716            // If the install is being performed by a system app, we trust that app to have set the
13717            // install reason correctly.
13718            return installReason;
13719        }
13720        final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(
13721                UserHandle.getUserId(installerUid));
13722        if (ownerPackage != null && ownerPackage.equals(installerPackageName)) {
13723            // If the install is being performed by a device or profile owner, the install
13724            // reason should be enterprise policy.
13725            return PackageManager.INSTALL_REASON_POLICY;
13726        }
13727
13728
13729        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13730            // If the install is being performed by a regular app (i.e. neither system app nor
13731            // device or profile owner), we have no reason to believe that the app is acting on
13732            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13733            // change it to unknown instead.
13734            return PackageManager.INSTALL_REASON_UNKNOWN;
13735        }
13736
13737        // If the install is being performed by a regular app and the install reason was set to any
13738        // value but enterprise policy, leave the install reason unchanged.
13739        return installReason;
13740    }
13741
13742    /**
13743     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13744     * install commit.
13745     */
13746    void earlyBindToDefContainer() {
13747        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13748    }
13749
13750    void installStage(String packageName, File stagedDir,
13751            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13752            String installerPackageName, int installerUid, UserHandle user,
13753            PackageParser.SigningDetails signingDetails) {
13754        if (DEBUG_INSTANT) {
13755            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13756                Slog.d(TAG, "Ephemeral install of " + packageName);
13757            }
13758        }
13759        final VerificationInfo verificationInfo = new VerificationInfo(
13760                sessionParams.originatingUri, sessionParams.referrerUri,
13761                sessionParams.originatingUid, installerUid);
13762
13763        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13764
13765        final Message msg = mHandler.obtainMessage(INIT_COPY);
13766        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13767                sessionParams.installReason);
13768        final InstallParams params = new InstallParams(origin, null, observer,
13769                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13770                verificationInfo, user, sessionParams.abiOverride,
13771                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13772        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13773        msg.obj = params;
13774
13775        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13776                System.identityHashCode(msg.obj));
13777        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13778                System.identityHashCode(msg.obj));
13779
13780        mHandler.sendMessage(msg);
13781    }
13782
13783    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13784            int userId) {
13785        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13786        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13787        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13788        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13789        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13790                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13791
13792        // Send a session commit broadcast
13793        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13794        info.installReason = pkgSetting.getInstallReason(userId);
13795        info.appPackageName = packageName;
13796        sendSessionCommitBroadcast(info, userId);
13797    }
13798
13799    @Override
13800    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13801            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13802        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13803            return;
13804        }
13805        Bundle extras = new Bundle(1);
13806        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13807        final int uid = UserHandle.getUid(
13808                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13809        extras.putInt(Intent.EXTRA_UID, uid);
13810
13811        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13812                packageName, extras, 0, null, null, userIds, instantUserIds);
13813        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13814            mHandler.post(() -> {
13815                        for (int userId : userIds) {
13816                            sendBootCompletedBroadcastToSystemApp(
13817                                    packageName, includeStopped, userId);
13818                        }
13819                    }
13820            );
13821        }
13822    }
13823
13824    /**
13825     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13826     * automatically without needing an explicit launch.
13827     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13828     */
13829    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13830            int userId) {
13831        // If user is not running, the app didn't miss any broadcast
13832        if (!mUserManagerInternal.isUserRunning(userId)) {
13833            return;
13834        }
13835        final IActivityManager am = ActivityManager.getService();
13836        try {
13837            // Deliver LOCKED_BOOT_COMPLETED first
13838            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13839                    .setPackage(packageName);
13840            if (includeStopped) {
13841                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13842            }
13843            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13844            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13845                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13846
13847            // Deliver BOOT_COMPLETED only if user is unlocked
13848            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13849                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13850                if (includeStopped) {
13851                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13852                }
13853                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13854                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13855            }
13856        } catch (RemoteException e) {
13857            throw e.rethrowFromSystemServer();
13858        }
13859    }
13860
13861    @Override
13862    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13863            int userId) {
13864        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13865        PackageSetting pkgSetting;
13866        final int callingUid = Binder.getCallingUid();
13867        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13868                true /* requireFullPermission */, true /* checkShell */,
13869                "setApplicationHiddenSetting for user " + userId);
13870
13871        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13872            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13873            return false;
13874        }
13875
13876        long callingId = Binder.clearCallingIdentity();
13877        try {
13878            boolean sendAdded = false;
13879            boolean sendRemoved = false;
13880            // writer
13881            synchronized (mPackages) {
13882                pkgSetting = mSettings.mPackages.get(packageName);
13883                if (pkgSetting == null) {
13884                    return false;
13885                }
13886                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13887                    return false;
13888                }
13889                // Do not allow "android" is being disabled
13890                if ("android".equals(packageName)) {
13891                    Slog.w(TAG, "Cannot hide package: android");
13892                    return false;
13893                }
13894                // Cannot hide static shared libs as they are considered
13895                // a part of the using app (emulating static linking). Also
13896                // static libs are installed always on internal storage.
13897                PackageParser.Package pkg = mPackages.get(packageName);
13898                if (pkg != null && pkg.staticSharedLibName != null) {
13899                    Slog.w(TAG, "Cannot hide package: " + packageName
13900                            + " providing static shared library: "
13901                            + pkg.staticSharedLibName);
13902                    return false;
13903                }
13904                // Only allow protected packages to hide themselves.
13905                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13906                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13907                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13908                    return false;
13909                }
13910
13911                if (pkgSetting.getHidden(userId) != hidden) {
13912                    pkgSetting.setHidden(hidden, userId);
13913                    mSettings.writePackageRestrictionsLPr(userId);
13914                    if (hidden) {
13915                        sendRemoved = true;
13916                    } else {
13917                        sendAdded = true;
13918                    }
13919                }
13920            }
13921            if (sendAdded) {
13922                sendPackageAddedForUser(packageName, pkgSetting, userId);
13923                return true;
13924            }
13925            if (sendRemoved) {
13926                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13927                        "hiding pkg");
13928                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13929                return true;
13930            }
13931        } finally {
13932            Binder.restoreCallingIdentity(callingId);
13933        }
13934        return false;
13935    }
13936
13937    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13938            int userId) {
13939        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13940        info.removedPackage = packageName;
13941        info.installerPackageName = pkgSetting.installerPackageName;
13942        info.removedUsers = new int[] {userId};
13943        info.broadcastUsers = new int[] {userId};
13944        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13945        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13946    }
13947
13948    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13949            PersistableBundle launcherExtras) {
13950        if (pkgList.length > 0) {
13951            Bundle extras = new Bundle(1);
13952            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13953            if (launcherExtras != null) {
13954                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13955                        new Bundle(launcherExtras.deepCopy()));
13956            }
13957            sendPackageBroadcast(
13958                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13959                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13960                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13961                    new int[] {userId}, null);
13962        }
13963    }
13964
13965    /**
13966     * Returns true if application is not found or there was an error. Otherwise it returns
13967     * the hidden state of the package for the given user.
13968     */
13969    @Override
13970    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13971        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13972        final int callingUid = Binder.getCallingUid();
13973        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13974                true /* requireFullPermission */, false /* checkShell */,
13975                "getApplicationHidden for user " + userId);
13976        PackageSetting ps;
13977        long callingId = Binder.clearCallingIdentity();
13978        try {
13979            // writer
13980            synchronized (mPackages) {
13981                ps = mSettings.mPackages.get(packageName);
13982                if (ps == null) {
13983                    return true;
13984                }
13985                if (filterAppAccessLPr(ps, callingUid, userId)) {
13986                    return true;
13987                }
13988                return ps.getHidden(userId);
13989            }
13990        } finally {
13991            Binder.restoreCallingIdentity(callingId);
13992        }
13993    }
13994
13995    /**
13996     * @hide
13997     */
13998    @Override
13999    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14000            int installReason) {
14001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14002                null);
14003        PackageSetting pkgSetting;
14004        final int callingUid = Binder.getCallingUid();
14005        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14006                true /* requireFullPermission */, true /* checkShell */,
14007                "installExistingPackage for user " + userId);
14008        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14009            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14010        }
14011
14012        long callingId = Binder.clearCallingIdentity();
14013        try {
14014            boolean installed = false;
14015            final boolean instantApp =
14016                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14017            final boolean fullApp =
14018                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14019
14020            // writer
14021            synchronized (mPackages) {
14022                pkgSetting = mSettings.mPackages.get(packageName);
14023                if (pkgSetting == null) {
14024                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14025                }
14026                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14027                    // only allow the existing package to be used if it's installed as a full
14028                    // application for at least one user
14029                    boolean installAllowed = false;
14030                    for (int checkUserId : sUserManager.getUserIds()) {
14031                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14032                        if (installAllowed) {
14033                            break;
14034                        }
14035                    }
14036                    if (!installAllowed) {
14037                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14038                    }
14039                }
14040                if (!pkgSetting.getInstalled(userId)) {
14041                    pkgSetting.setInstalled(true, userId);
14042                    pkgSetting.setHidden(false, userId);
14043                    pkgSetting.setInstallReason(installReason, userId);
14044                    mSettings.writePackageRestrictionsLPr(userId);
14045                    mSettings.writeKernelMappingLPr(pkgSetting);
14046                    installed = true;
14047                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14048                    // upgrade app from instant to full; we don't allow app downgrade
14049                    installed = true;
14050                }
14051                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14052            }
14053
14054            if (installed) {
14055                if (pkgSetting.pkg != null) {
14056                    synchronized (mInstallLock) {
14057                        // We don't need to freeze for a brand new install
14058                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14059                    }
14060                }
14061                sendPackageAddedForUser(packageName, pkgSetting, userId);
14062                synchronized (mPackages) {
14063                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14064                }
14065            }
14066        } finally {
14067            Binder.restoreCallingIdentity(callingId);
14068        }
14069
14070        return PackageManager.INSTALL_SUCCEEDED;
14071    }
14072
14073    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14074            boolean instantApp, boolean fullApp) {
14075        // no state specified; do nothing
14076        if (!instantApp && !fullApp) {
14077            return;
14078        }
14079        if (userId != UserHandle.USER_ALL) {
14080            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14081                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14082            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14083                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14084            }
14085        } else {
14086            for (int currentUserId : sUserManager.getUserIds()) {
14087                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14088                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14089                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14090                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14091                }
14092            }
14093        }
14094    }
14095
14096    boolean isUserRestricted(int userId, String restrictionKey) {
14097        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14098        if (restrictions.getBoolean(restrictionKey, false)) {
14099            Log.w(TAG, "User is restricted: " + restrictionKey);
14100            return true;
14101        }
14102        return false;
14103    }
14104
14105    @Override
14106    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14107            PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
14108            String callingPackage, int userId) {
14109        try {
14110            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
14111        } catch (SecurityException e) {
14112            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
14113                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
14114                            + Manifest.permission.MANAGE_USERS);
14115        }
14116        final int callingUid = Binder.getCallingUid();
14117        if (callingUid != Process.ROOT_UID && callingUid != Process.SYSTEM_UID
14118                && getPackageUid(callingPackage, 0, userId) != callingUid) {
14119            throw new SecurityException("Calling package " + callingPackage + " in user "
14120                    + userId + " does not belong to calling uid " + callingUid);
14121        }
14122        if (!PLATFORM_PACKAGE_NAME.equals(callingPackage)
14123                && mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId) != null) {
14124            throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User "
14125                    + userId + " has an active DO or PO");
14126        }
14127        if (ArrayUtils.isEmpty(packageNames)) {
14128            return packageNames;
14129        }
14130
14131        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14132        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14133        final long callingId = Binder.clearCallingIdentity();
14134        try {
14135            synchronized (mPackages) {
14136                for (int i = 0; i < packageNames.length; i++) {
14137                    final String packageName = packageNames[i];
14138                    if (callingPackage.equals(packageName)) {
14139                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14140                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14141                        unactionedPackages.add(packageName);
14142                        continue;
14143                    }
14144                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14145                    if (pkgSetting == null
14146                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14147                        Slog.w(TAG, "Could not find package setting for package: " + packageName
14148                                + ". Skipping suspending/un-suspending.");
14149                        unactionedPackages.add(packageName);
14150                        continue;
14151                    }
14152                    if (!canSuspendPackageForUserLocked(packageName, userId)) {
14153                        unactionedPackages.add(packageName);
14154                        continue;
14155                    }
14156                    pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
14157                            launcherExtras, userId);
14158                    changedPackagesList.add(packageName);
14159                }
14160            }
14161        } finally {
14162            Binder.restoreCallingIdentity(callingId);
14163        }
14164        if (!changedPackagesList.isEmpty()) {
14165            final String[] changedPackages = changedPackagesList.toArray(
14166                    new String[changedPackagesList.size()]);
14167            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14168            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14169            synchronized (mPackages) {
14170                scheduleWritePackageRestrictionsLocked(userId);
14171            }
14172        }
14173        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14174    }
14175
14176    @Override
14177    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14178        final int callingUid = Binder.getCallingUid();
14179        if (getPackageUid(packageName, 0, userId) != callingUid) {
14180            throw new SecurityException("Calling package " + packageName
14181                    + " does not belong to calling uid " + callingUid);
14182        }
14183        synchronized (mPackages) {
14184            final PackageSetting ps = mSettings.mPackages.get(packageName);
14185            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14186                throw new IllegalArgumentException("Unknown target package: " + packageName);
14187            }
14188            final PackageUserState packageUserState = ps.readUserState(userId);
14189            if (packageUserState.suspended) {
14190                return packageUserState.suspendedAppExtras;
14191            }
14192            return null;
14193        }
14194    }
14195
14196    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14197            PersistableBundle appExtras, int userId) {
14198        final String action;
14199        final Bundle intentExtras = new Bundle();
14200        if (suspended) {
14201            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14202            if (appExtras != null) {
14203                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14204                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14205            }
14206        } else {
14207            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14208        }
14209        mHandler.post(new Runnable() {
14210            @Override
14211            public void run() {
14212                try {
14213                    final IActivityManager am = ActivityManager.getService();
14214                    if (am == null) {
14215                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14216                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14217                        return;
14218                    }
14219                    final int[] targetUserIds = new int[] {userId};
14220                    for (String packageName : affectedPackages) {
14221                        doSendBroadcast(am, action, null, intentExtras,
14222                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14223                                targetUserIds, false);
14224                    }
14225                } catch (RemoteException ex) {
14226                    // Shouldn't happen as AMS is in the same process.
14227                }
14228            }
14229        });
14230    }
14231
14232    @Override
14233    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14234        final int callingUid = Binder.getCallingUid();
14235        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14236                true /* requireFullPermission */, false /* checkShell */,
14237                "isPackageSuspendedForUser for user " + userId);
14238        synchronized (mPackages) {
14239            final PackageSetting ps = mSettings.mPackages.get(packageName);
14240            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14241                throw new IllegalArgumentException("Unknown target package: " + packageName);
14242            }
14243            return ps.getSuspended(userId);
14244        }
14245    }
14246
14247    /**
14248     * Immediately unsuspends any packages suspended by the given package. To be called
14249     * when such a package's data is cleared or it is removed from the device.
14250     *
14251     * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
14252     * synchronously
14253     *
14254     * @param packageName The package holding {@link Manifest.permission#SUSPEND_APPS} permission
14255     * @param affectedUser The user for which the changes are taking place.
14256     */
14257    void unsuspendForSuspendingPackage(String packageName, int affectedUser) {
14258        final int[] userIds = (affectedUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14259                : new int[] {affectedUser};
14260        for (int userId : userIds) {
14261            List<String> affectedPackages = new ArrayList<>();
14262            synchronized (mPackages) {
14263                for (PackageSetting ps : mSettings.mPackages.values()) {
14264                    final PackageUserState pus = ps.readUserState(userId);
14265                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14266                        ps.setSuspended(false, null, null, null, null, userId);
14267                        affectedPackages.add(ps.name);
14268                    }
14269                }
14270            }
14271            if (!affectedPackages.isEmpty()) {
14272                final String[] packageArray = affectedPackages.toArray(
14273                        new String[affectedPackages.size()]);
14274                sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
14275                sendPackagesSuspendedForUser(packageArray, userId, false, null);
14276                // Write package restrictions immediately to avoid an inconsistent state.
14277                mSettings.writePackageRestrictionsLPr(userId);
14278            }
14279        }
14280    }
14281
14282    @GuardedBy("mPackages")
14283    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14284        if (isPackageDeviceAdmin(packageName, userId)) {
14285            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14286                    + "\": has an active device admin");
14287            return false;
14288        }
14289
14290        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14291        if (packageName.equals(activeLauncherPackageName)) {
14292            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14293                    + "\": contains the active launcher");
14294            return false;
14295        }
14296
14297        if (packageName.equals(mRequiredInstallerPackage)) {
14298            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14299                    + "\": required for package installation");
14300            return false;
14301        }
14302
14303        if (packageName.equals(mRequiredUninstallerPackage)) {
14304            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14305                    + "\": required for package uninstallation");
14306            return false;
14307        }
14308
14309        if (packageName.equals(mRequiredVerifierPackage)) {
14310            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14311                    + "\": required for package verification");
14312            return false;
14313        }
14314
14315        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14316            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14317                    + "\": is the default dialer");
14318            return false;
14319        }
14320
14321        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14322            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14323                    + "\": protected package");
14324            return false;
14325        }
14326
14327        // Cannot suspend static shared libs as they are considered
14328        // a part of the using app (emulating static linking). Also
14329        // static libs are installed always on internal storage.
14330        PackageParser.Package pkg = mPackages.get(packageName);
14331        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14332            Slog.w(TAG, "Cannot suspend package: " + packageName
14333                    + " providing static shared library: "
14334                    + pkg.staticSharedLibName);
14335            return false;
14336        }
14337
14338        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14339            Slog.w(TAG, "Cannot suspend package: " + packageName);
14340            return false;
14341        }
14342
14343        return true;
14344    }
14345
14346    private String getActiveLauncherPackageName(int userId) {
14347        Intent intent = new Intent(Intent.ACTION_MAIN);
14348        intent.addCategory(Intent.CATEGORY_HOME);
14349        ResolveInfo resolveInfo = resolveIntent(
14350                intent,
14351                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14352                PackageManager.MATCH_DEFAULT_ONLY,
14353                userId);
14354
14355        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14356    }
14357
14358    private String getDefaultDialerPackageName(int userId) {
14359        synchronized (mPackages) {
14360            return mSettings.getDefaultDialerPackageNameLPw(userId);
14361        }
14362    }
14363
14364    @Override
14365    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14366        mContext.enforceCallingOrSelfPermission(
14367                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14368                "Only package verification agents can verify applications");
14369
14370        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14371        final PackageVerificationResponse response = new PackageVerificationResponse(
14372                verificationCode, Binder.getCallingUid());
14373        msg.arg1 = id;
14374        msg.obj = response;
14375        mHandler.sendMessage(msg);
14376    }
14377
14378    @Override
14379    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14380            long millisecondsToDelay) {
14381        mContext.enforceCallingOrSelfPermission(
14382                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14383                "Only package verification agents can extend verification timeouts");
14384
14385        final PackageVerificationState state = mPendingVerification.get(id);
14386        final PackageVerificationResponse response = new PackageVerificationResponse(
14387                verificationCodeAtTimeout, Binder.getCallingUid());
14388
14389        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14390            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14391        }
14392        if (millisecondsToDelay < 0) {
14393            millisecondsToDelay = 0;
14394        }
14395        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14396                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14397            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14398        }
14399
14400        if ((state != null) && !state.timeoutExtended()) {
14401            state.extendTimeout();
14402
14403            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14404            msg.arg1 = id;
14405            msg.obj = response;
14406            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14407        }
14408    }
14409
14410    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14411            int verificationCode, UserHandle user) {
14412        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14413        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14414        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14415        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14416        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14417
14418        mContext.sendBroadcastAsUser(intent, user,
14419                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14420    }
14421
14422    private ComponentName matchComponentForVerifier(String packageName,
14423            List<ResolveInfo> receivers) {
14424        ActivityInfo targetReceiver = null;
14425
14426        final int NR = receivers.size();
14427        for (int i = 0; i < NR; i++) {
14428            final ResolveInfo info = receivers.get(i);
14429            if (info.activityInfo == null) {
14430                continue;
14431            }
14432
14433            if (packageName.equals(info.activityInfo.packageName)) {
14434                targetReceiver = info.activityInfo;
14435                break;
14436            }
14437        }
14438
14439        if (targetReceiver == null) {
14440            return null;
14441        }
14442
14443        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14444    }
14445
14446    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14447            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14448        if (pkgInfo.verifiers.length == 0) {
14449            return null;
14450        }
14451
14452        final int N = pkgInfo.verifiers.length;
14453        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14454        for (int i = 0; i < N; i++) {
14455            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14456
14457            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14458                    receivers);
14459            if (comp == null) {
14460                continue;
14461            }
14462
14463            final int verifierUid = getUidForVerifier(verifierInfo);
14464            if (verifierUid == -1) {
14465                continue;
14466            }
14467
14468            if (DEBUG_VERIFY) {
14469                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14470                        + " with the correct signature");
14471            }
14472            sufficientVerifiers.add(comp);
14473            verificationState.addSufficientVerifier(verifierUid);
14474        }
14475
14476        return sufficientVerifiers;
14477    }
14478
14479    private int getUidForVerifier(VerifierInfo verifierInfo) {
14480        synchronized (mPackages) {
14481            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14482            if (pkg == null) {
14483                return -1;
14484            } else if (pkg.mSigningDetails.signatures.length != 1) {
14485                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14486                        + " has more than one signature; ignoring");
14487                return -1;
14488            }
14489
14490            /*
14491             * If the public key of the package's signature does not match
14492             * our expected public key, then this is a different package and
14493             * we should skip.
14494             */
14495
14496            final byte[] expectedPublicKey;
14497            try {
14498                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14499                final PublicKey publicKey = verifierSig.getPublicKey();
14500                expectedPublicKey = publicKey.getEncoded();
14501            } catch (CertificateException e) {
14502                return -1;
14503            }
14504
14505            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14506
14507            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14508                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14509                        + " does not have the expected public key; ignoring");
14510                return -1;
14511            }
14512
14513            return pkg.applicationInfo.uid;
14514        }
14515    }
14516
14517    @Override
14518    public void finishPackageInstall(int token, boolean didLaunch) {
14519        enforceSystemOrRoot("Only the system is allowed to finish installs");
14520
14521        if (DEBUG_INSTALL) {
14522            Slog.v(TAG, "BM finishing package install for " + token);
14523        }
14524        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14525
14526        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14527        mHandler.sendMessage(msg);
14528    }
14529
14530    /**
14531     * Get the verification agent timeout.  Used for both the APK verifier and the
14532     * intent filter verifier.
14533     *
14534     * @return verification timeout in milliseconds
14535     */
14536    private long getVerificationTimeout() {
14537        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14538                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14539                DEFAULT_VERIFICATION_TIMEOUT);
14540    }
14541
14542    /**
14543     * Get the default verification agent response code.
14544     *
14545     * @return default verification response code
14546     */
14547    private int getDefaultVerificationResponse(UserHandle user) {
14548        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14549            return PackageManager.VERIFICATION_REJECT;
14550        }
14551        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14552                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14553                DEFAULT_VERIFICATION_RESPONSE);
14554    }
14555
14556    /**
14557     * Check whether or not package verification has been enabled.
14558     *
14559     * @return true if verification should be performed
14560     */
14561    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14562        if (!DEFAULT_VERIFY_ENABLE) {
14563            return false;
14564        }
14565
14566        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14567
14568        // Check if installing from ADB
14569        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14570            // Do not run verification in a test harness environment
14571            if (ActivityManager.isRunningInTestHarness()) {
14572                return false;
14573            }
14574            if (ensureVerifyAppsEnabled) {
14575                return true;
14576            }
14577            // Check if the developer does not want package verification for ADB installs
14578            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14579                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14580                return false;
14581            }
14582        } else {
14583            // only when not installed from ADB, skip verification for instant apps when
14584            // the installer and verifier are the same.
14585            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14586                if (mInstantAppInstallerActivity != null
14587                        && mInstantAppInstallerActivity.packageName.equals(
14588                                mRequiredVerifierPackage)) {
14589                    try {
14590                        mContext.getSystemService(AppOpsManager.class)
14591                                .checkPackage(installerUid, mRequiredVerifierPackage);
14592                        if (DEBUG_VERIFY) {
14593                            Slog.i(TAG, "disable verification for instant app");
14594                        }
14595                        return false;
14596                    } catch (SecurityException ignore) { }
14597                }
14598            }
14599        }
14600
14601        if (ensureVerifyAppsEnabled) {
14602            return true;
14603        }
14604
14605        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14606                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14607    }
14608
14609    @Override
14610    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14611            throws RemoteException {
14612        mContext.enforceCallingOrSelfPermission(
14613                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14614                "Only intentfilter verification agents can verify applications");
14615
14616        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14617        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14618                Binder.getCallingUid(), verificationCode, failedDomains);
14619        msg.arg1 = id;
14620        msg.obj = response;
14621        mHandler.sendMessage(msg);
14622    }
14623
14624    @Override
14625    public int getIntentVerificationStatus(String packageName, int userId) {
14626        final int callingUid = Binder.getCallingUid();
14627        if (UserHandle.getUserId(callingUid) != userId) {
14628            mContext.enforceCallingOrSelfPermission(
14629                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14630                    "getIntentVerificationStatus" + userId);
14631        }
14632        if (getInstantAppPackageName(callingUid) != null) {
14633            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14634        }
14635        synchronized (mPackages) {
14636            final PackageSetting ps = mSettings.mPackages.get(packageName);
14637            if (ps == null
14638                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14639                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14640            }
14641            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14642        }
14643    }
14644
14645    @Override
14646    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14647        mContext.enforceCallingOrSelfPermission(
14648                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14649
14650        boolean result = false;
14651        synchronized (mPackages) {
14652            final PackageSetting ps = mSettings.mPackages.get(packageName);
14653            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14654                return false;
14655            }
14656            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14657        }
14658        if (result) {
14659            scheduleWritePackageRestrictionsLocked(userId);
14660        }
14661        return result;
14662    }
14663
14664    @Override
14665    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14666            String packageName) {
14667        final int callingUid = Binder.getCallingUid();
14668        if (getInstantAppPackageName(callingUid) != null) {
14669            return ParceledListSlice.emptyList();
14670        }
14671        synchronized (mPackages) {
14672            final PackageSetting ps = mSettings.mPackages.get(packageName);
14673            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14674                return ParceledListSlice.emptyList();
14675            }
14676            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14677        }
14678    }
14679
14680    @Override
14681    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14682        if (TextUtils.isEmpty(packageName)) {
14683            return ParceledListSlice.emptyList();
14684        }
14685        final int callingUid = Binder.getCallingUid();
14686        final int callingUserId = UserHandle.getUserId(callingUid);
14687        synchronized (mPackages) {
14688            PackageParser.Package pkg = mPackages.get(packageName);
14689            if (pkg == null || pkg.activities == null) {
14690                return ParceledListSlice.emptyList();
14691            }
14692            if (pkg.mExtras == null) {
14693                return ParceledListSlice.emptyList();
14694            }
14695            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14696            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14697                return ParceledListSlice.emptyList();
14698            }
14699            final int count = pkg.activities.size();
14700            ArrayList<IntentFilter> result = new ArrayList<>();
14701            for (int n=0; n<count; n++) {
14702                PackageParser.Activity activity = pkg.activities.get(n);
14703                if (activity.intents != null && activity.intents.size() > 0) {
14704                    result.addAll(activity.intents);
14705                }
14706            }
14707            return new ParceledListSlice<>(result);
14708        }
14709    }
14710
14711    @Override
14712    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14713        mContext.enforceCallingOrSelfPermission(
14714                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14715        if (UserHandle.getCallingUserId() != userId) {
14716            mContext.enforceCallingOrSelfPermission(
14717                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14718        }
14719
14720        synchronized (mPackages) {
14721            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14722            if (packageName != null) {
14723                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14724                        packageName, userId);
14725            }
14726            return result;
14727        }
14728    }
14729
14730    @Override
14731    public String getDefaultBrowserPackageName(int userId) {
14732        if (UserHandle.getCallingUserId() != userId) {
14733            mContext.enforceCallingOrSelfPermission(
14734                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14735        }
14736        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14737            return null;
14738        }
14739        synchronized (mPackages) {
14740            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14741        }
14742    }
14743
14744    /**
14745     * Get the "allow unknown sources" setting.
14746     *
14747     * @return the current "allow unknown sources" setting
14748     */
14749    private int getUnknownSourcesSettings() {
14750        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14751                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14752                -1);
14753    }
14754
14755    @Override
14756    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14757        final int callingUid = Binder.getCallingUid();
14758        if (getInstantAppPackageName(callingUid) != null) {
14759            return;
14760        }
14761        // writer
14762        synchronized (mPackages) {
14763            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14764            if (targetPackageSetting == null
14765                    || filterAppAccessLPr(
14766                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14767                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14768            }
14769
14770            PackageSetting installerPackageSetting;
14771            if (installerPackageName != null) {
14772                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14773                if (installerPackageSetting == null) {
14774                    throw new IllegalArgumentException("Unknown installer package: "
14775                            + installerPackageName);
14776                }
14777            } else {
14778                installerPackageSetting = null;
14779            }
14780
14781            Signature[] callerSignature;
14782            Object obj = mSettings.getUserIdLPr(callingUid);
14783            if (obj != null) {
14784                if (obj instanceof SharedUserSetting) {
14785                    callerSignature =
14786                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14787                } else if (obj instanceof PackageSetting) {
14788                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14789                } else {
14790                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14791                }
14792            } else {
14793                throw new SecurityException("Unknown calling UID: " + callingUid);
14794            }
14795
14796            // Verify: can't set installerPackageName to a package that is
14797            // not signed with the same cert as the caller.
14798            if (installerPackageSetting != null) {
14799                if (compareSignatures(callerSignature,
14800                        installerPackageSetting.signatures.mSigningDetails.signatures)
14801                        != PackageManager.SIGNATURE_MATCH) {
14802                    throw new SecurityException(
14803                            "Caller does not have same cert as new installer package "
14804                            + installerPackageName);
14805                }
14806            }
14807
14808            // Verify: if target already has an installer package, it must
14809            // be signed with the same cert as the caller.
14810            if (targetPackageSetting.installerPackageName != null) {
14811                PackageSetting setting = mSettings.mPackages.get(
14812                        targetPackageSetting.installerPackageName);
14813                // If the currently set package isn't valid, then it's always
14814                // okay to change it.
14815                if (setting != null) {
14816                    if (compareSignatures(callerSignature,
14817                            setting.signatures.mSigningDetails.signatures)
14818                            != PackageManager.SIGNATURE_MATCH) {
14819                        throw new SecurityException(
14820                                "Caller does not have same cert as old installer package "
14821                                + targetPackageSetting.installerPackageName);
14822                    }
14823                }
14824            }
14825
14826            // Okay!
14827            targetPackageSetting.installerPackageName = installerPackageName;
14828            if (installerPackageName != null) {
14829                mSettings.mInstallerPackages.add(installerPackageName);
14830            }
14831            scheduleWriteSettingsLocked();
14832        }
14833    }
14834
14835    @Override
14836    public void setApplicationCategoryHint(String packageName, int categoryHint,
14837            String callerPackageName) {
14838        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14839            throw new SecurityException("Instant applications don't have access to this method");
14840        }
14841        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14842                callerPackageName);
14843        synchronized (mPackages) {
14844            PackageSetting ps = mSettings.mPackages.get(packageName);
14845            if (ps == null) {
14846                throw new IllegalArgumentException("Unknown target package " + packageName);
14847            }
14848            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14849                throw new IllegalArgumentException("Unknown target package " + packageName);
14850            }
14851            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14852                throw new IllegalArgumentException("Calling package " + callerPackageName
14853                        + " is not installer for " + packageName);
14854            }
14855
14856            if (ps.categoryHint != categoryHint) {
14857                ps.categoryHint = categoryHint;
14858                scheduleWriteSettingsLocked();
14859            }
14860        }
14861    }
14862
14863    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14864        // Queue up an async operation since the package installation may take a little while.
14865        mHandler.post(new Runnable() {
14866            public void run() {
14867                mHandler.removeCallbacks(this);
14868                 // Result object to be returned
14869                PackageInstalledInfo res = new PackageInstalledInfo();
14870                res.setReturnCode(currentStatus);
14871                res.uid = -1;
14872                res.pkg = null;
14873                res.removedInfo = null;
14874                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14875                    args.doPreInstall(res.returnCode);
14876                    synchronized (mInstallLock) {
14877                        installPackageTracedLI(args, res);
14878                    }
14879                    args.doPostInstall(res.returnCode, res.uid);
14880                }
14881
14882                // A restore should be performed at this point if (a) the install
14883                // succeeded, (b) the operation is not an update, and (c) the new
14884                // package has not opted out of backup participation.
14885                final boolean update = res.removedInfo != null
14886                        && res.removedInfo.removedPackage != null;
14887                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14888                boolean doRestore = !update
14889                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14890
14891                // Set up the post-install work request bookkeeping.  This will be used
14892                // and cleaned up by the post-install event handling regardless of whether
14893                // there's a restore pass performed.  Token values are >= 1.
14894                int token;
14895                if (mNextInstallToken < 0) mNextInstallToken = 1;
14896                token = mNextInstallToken++;
14897
14898                PostInstallData data = new PostInstallData(args, res);
14899                mRunningInstalls.put(token, data);
14900                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14901
14902                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14903                    // Pass responsibility to the Backup Manager.  It will perform a
14904                    // restore if appropriate, then pass responsibility back to the
14905                    // Package Manager to run the post-install observer callbacks
14906                    // and broadcasts.
14907                    IBackupManager bm = IBackupManager.Stub.asInterface(
14908                            ServiceManager.getService(Context.BACKUP_SERVICE));
14909                    if (bm != null) {
14910                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14911                                + " to BM for possible restore");
14912                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14913                        try {
14914                            // TODO: http://b/22388012
14915                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14916                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14917                            } else {
14918                                doRestore = false;
14919                            }
14920                        } catch (RemoteException e) {
14921                            // can't happen; the backup manager is local
14922                        } catch (Exception e) {
14923                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14924                            doRestore = false;
14925                        }
14926                    } else {
14927                        Slog.e(TAG, "Backup Manager not found!");
14928                        doRestore = false;
14929                    }
14930                }
14931
14932                if (!doRestore) {
14933                    // No restore possible, or the Backup Manager was mysteriously not
14934                    // available -- just fire the post-install work request directly.
14935                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14936
14937                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14938
14939                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14940                    mHandler.sendMessage(msg);
14941                }
14942            }
14943        });
14944    }
14945
14946    /**
14947     * Callback from PackageSettings whenever an app is first transitioned out of the
14948     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14949     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14950     * here whether the app is the target of an ongoing install, and only send the
14951     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14952     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14953     * handling.
14954     */
14955    void notifyFirstLaunch(final String packageName, final String installerPackage,
14956            final int userId) {
14957        // Serialize this with the rest of the install-process message chain.  In the
14958        // restore-at-install case, this Runnable will necessarily run before the
14959        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14960        // are coherent.  In the non-restore case, the app has already completed install
14961        // and been launched through some other means, so it is not in a problematic
14962        // state for observers to see the FIRST_LAUNCH signal.
14963        mHandler.post(new Runnable() {
14964            @Override
14965            public void run() {
14966                for (int i = 0; i < mRunningInstalls.size(); i++) {
14967                    final PostInstallData data = mRunningInstalls.valueAt(i);
14968                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14969                        continue;
14970                    }
14971                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14972                        // right package; but is it for the right user?
14973                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14974                            if (userId == data.res.newUsers[uIndex]) {
14975                                if (DEBUG_BACKUP) {
14976                                    Slog.i(TAG, "Package " + packageName
14977                                            + " being restored so deferring FIRST_LAUNCH");
14978                                }
14979                                return;
14980                            }
14981                        }
14982                    }
14983                }
14984                // didn't find it, so not being restored
14985                if (DEBUG_BACKUP) {
14986                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14987                }
14988                final boolean isInstantApp = isInstantApp(packageName, userId);
14989                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14990                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14991                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14992            }
14993        });
14994    }
14995
14996    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14997            int[] userIds, int[] instantUserIds) {
14998        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14999                installerPkg, null, userIds, instantUserIds);
15000    }
15001
15002    private abstract class HandlerParams {
15003        private static final int MAX_RETRIES = 4;
15004
15005        /**
15006         * Number of times startCopy() has been attempted and had a non-fatal
15007         * error.
15008         */
15009        private int mRetries = 0;
15010
15011        /** User handle for the user requesting the information or installation. */
15012        private final UserHandle mUser;
15013        String traceMethod;
15014        int traceCookie;
15015
15016        HandlerParams(UserHandle user) {
15017            mUser = user;
15018        }
15019
15020        UserHandle getUser() {
15021            return mUser;
15022        }
15023
15024        HandlerParams setTraceMethod(String traceMethod) {
15025            this.traceMethod = traceMethod;
15026            return this;
15027        }
15028
15029        HandlerParams setTraceCookie(int traceCookie) {
15030            this.traceCookie = traceCookie;
15031            return this;
15032        }
15033
15034        final boolean startCopy() {
15035            boolean res;
15036            try {
15037                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15038
15039                if (++mRetries > MAX_RETRIES) {
15040                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15041                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15042                    handleServiceError();
15043                    return false;
15044                } else {
15045                    handleStartCopy();
15046                    res = true;
15047                }
15048            } catch (RemoteException e) {
15049                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15050                mHandler.sendEmptyMessage(MCS_RECONNECT);
15051                res = false;
15052            }
15053            handleReturnCode();
15054            return res;
15055        }
15056
15057        final void serviceError() {
15058            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15059            handleServiceError();
15060            handleReturnCode();
15061        }
15062
15063        abstract void handleStartCopy() throws RemoteException;
15064        abstract void handleServiceError();
15065        abstract void handleReturnCode();
15066    }
15067
15068    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15069        for (File path : paths) {
15070            try {
15071                mcs.clearDirectory(path.getAbsolutePath());
15072            } catch (RemoteException e) {
15073            }
15074        }
15075    }
15076
15077    static class OriginInfo {
15078        /**
15079         * Location where install is coming from, before it has been
15080         * copied/renamed into place. This could be a single monolithic APK
15081         * file, or a cluster directory. This location may be untrusted.
15082         */
15083        final File file;
15084
15085        /**
15086         * Flag indicating that {@link #file} or {@link #cid} has already been
15087         * staged, meaning downstream users don't need to defensively copy the
15088         * contents.
15089         */
15090        final boolean staged;
15091
15092        /**
15093         * Flag indicating that {@link #file} or {@link #cid} is an already
15094         * installed app that is being moved.
15095         */
15096        final boolean existing;
15097
15098        final String resolvedPath;
15099        final File resolvedFile;
15100
15101        static OriginInfo fromNothing() {
15102            return new OriginInfo(null, false, false);
15103        }
15104
15105        static OriginInfo fromUntrustedFile(File file) {
15106            return new OriginInfo(file, false, false);
15107        }
15108
15109        static OriginInfo fromExistingFile(File file) {
15110            return new OriginInfo(file, false, true);
15111        }
15112
15113        static OriginInfo fromStagedFile(File file) {
15114            return new OriginInfo(file, true, false);
15115        }
15116
15117        private OriginInfo(File file, boolean staged, boolean existing) {
15118            this.file = file;
15119            this.staged = staged;
15120            this.existing = existing;
15121
15122            if (file != null) {
15123                resolvedPath = file.getAbsolutePath();
15124                resolvedFile = file;
15125            } else {
15126                resolvedPath = null;
15127                resolvedFile = null;
15128            }
15129        }
15130    }
15131
15132    static class MoveInfo {
15133        final int moveId;
15134        final String fromUuid;
15135        final String toUuid;
15136        final String packageName;
15137        final String dataAppName;
15138        final int appId;
15139        final String seinfo;
15140        final int targetSdkVersion;
15141
15142        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15143                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15144            this.moveId = moveId;
15145            this.fromUuid = fromUuid;
15146            this.toUuid = toUuid;
15147            this.packageName = packageName;
15148            this.dataAppName = dataAppName;
15149            this.appId = appId;
15150            this.seinfo = seinfo;
15151            this.targetSdkVersion = targetSdkVersion;
15152        }
15153    }
15154
15155    static class VerificationInfo {
15156        /** A constant used to indicate that a uid value is not present. */
15157        public static final int NO_UID = -1;
15158
15159        /** URI referencing where the package was downloaded from. */
15160        final Uri originatingUri;
15161
15162        /** HTTP referrer URI associated with the originatingURI. */
15163        final Uri referrer;
15164
15165        /** UID of the application that the install request originated from. */
15166        final int originatingUid;
15167
15168        /** UID of application requesting the install */
15169        final int installerUid;
15170
15171        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15172            this.originatingUri = originatingUri;
15173            this.referrer = referrer;
15174            this.originatingUid = originatingUid;
15175            this.installerUid = installerUid;
15176        }
15177    }
15178
15179    class InstallParams extends HandlerParams {
15180        final OriginInfo origin;
15181        final MoveInfo move;
15182        final IPackageInstallObserver2 observer;
15183        int installFlags;
15184        final String installerPackageName;
15185        final String volumeUuid;
15186        private InstallArgs mArgs;
15187        private int mRet;
15188        final String packageAbiOverride;
15189        final String[] grantedRuntimePermissions;
15190        final VerificationInfo verificationInfo;
15191        final PackageParser.SigningDetails signingDetails;
15192        final int installReason;
15193
15194        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15195                int installFlags, String installerPackageName, String volumeUuid,
15196                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15197                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15198            super(user);
15199            this.origin = origin;
15200            this.move = move;
15201            this.observer = observer;
15202            this.installFlags = installFlags;
15203            this.installerPackageName = installerPackageName;
15204            this.volumeUuid = volumeUuid;
15205            this.verificationInfo = verificationInfo;
15206            this.packageAbiOverride = packageAbiOverride;
15207            this.grantedRuntimePermissions = grantedPermissions;
15208            this.signingDetails = signingDetails;
15209            this.installReason = installReason;
15210        }
15211
15212        @Override
15213        public String toString() {
15214            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15215                    + " file=" + origin.file + "}";
15216        }
15217
15218        private int installLocationPolicy(PackageInfoLite pkgLite) {
15219            String packageName = pkgLite.packageName;
15220            int installLocation = pkgLite.installLocation;
15221            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15222            // reader
15223            synchronized (mPackages) {
15224                // Currently installed package which the new package is attempting to replace or
15225                // null if no such package is installed.
15226                PackageParser.Package installedPkg = mPackages.get(packageName);
15227                // Package which currently owns the data which the new package will own if installed.
15228                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15229                // will be null whereas dataOwnerPkg will contain information about the package
15230                // which was uninstalled while keeping its data.
15231                PackageParser.Package dataOwnerPkg = installedPkg;
15232                if (dataOwnerPkg  == null) {
15233                    PackageSetting ps = mSettings.mPackages.get(packageName);
15234                    if (ps != null) {
15235                        dataOwnerPkg = ps.pkg;
15236                    }
15237                }
15238
15239                if (dataOwnerPkg != null) {
15240                    // If installed, the package will get access to data left on the device by its
15241                    // predecessor. As a security measure, this is permited only if this is not a
15242                    // version downgrade or if the predecessor package is marked as debuggable and
15243                    // a downgrade is explicitly requested.
15244                    //
15245                    // On debuggable platform builds, downgrades are permitted even for
15246                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15247                    // not offer security guarantees and thus it's OK to disable some security
15248                    // mechanisms to make debugging/testing easier on those builds. However, even on
15249                    // debuggable builds downgrades of packages are permitted only if requested via
15250                    // installFlags. This is because we aim to keep the behavior of debuggable
15251                    // platform builds as close as possible to the behavior of non-debuggable
15252                    // platform builds.
15253                    final boolean downgradeRequested =
15254                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15255                    final boolean packageDebuggable =
15256                                (dataOwnerPkg.applicationInfo.flags
15257                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15258                    final boolean downgradePermitted =
15259                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15260                    if (!downgradePermitted) {
15261                        try {
15262                            checkDowngrade(dataOwnerPkg, pkgLite);
15263                        } catch (PackageManagerException e) {
15264                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15265                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15266                        }
15267                    }
15268                }
15269
15270                if (installedPkg != null) {
15271                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15272                        // Check for updated system application.
15273                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15274                            if (onSd) {
15275                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15276                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15277                            }
15278                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15279                        } else {
15280                            if (onSd) {
15281                                // Install flag overrides everything.
15282                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15283                            }
15284                            // If current upgrade specifies particular preference
15285                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15286                                // Application explicitly specified internal.
15287                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15288                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15289                                // App explictly prefers external. Let policy decide
15290                            } else {
15291                                // Prefer previous location
15292                                if (isExternal(installedPkg)) {
15293                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15294                                }
15295                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15296                            }
15297                        }
15298                    } else {
15299                        // Invalid install. Return error code
15300                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15301                    }
15302                }
15303            }
15304            // All the special cases have been taken care of.
15305            // Return result based on recommended install location.
15306            if (onSd) {
15307                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15308            }
15309            return pkgLite.recommendedInstallLocation;
15310        }
15311
15312        /*
15313         * Invoke remote method to get package information and install
15314         * location values. Override install location based on default
15315         * policy if needed and then create install arguments based
15316         * on the install location.
15317         */
15318        public void handleStartCopy() throws RemoteException {
15319            int ret = PackageManager.INSTALL_SUCCEEDED;
15320
15321            // If we're already staged, we've firmly committed to an install location
15322            if (origin.staged) {
15323                if (origin.file != null) {
15324                    installFlags |= PackageManager.INSTALL_INTERNAL;
15325                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15326                } else {
15327                    throw new IllegalStateException("Invalid stage location");
15328                }
15329            }
15330
15331            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15332            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15333            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15334            PackageInfoLite pkgLite = null;
15335
15336            if (onInt && onSd) {
15337                // Check if both bits are set.
15338                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15339                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15340            } else if (onSd && ephemeral) {
15341                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15342                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15343            } else {
15344                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15345                        packageAbiOverride);
15346
15347                if (DEBUG_INSTANT && ephemeral) {
15348                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15349                }
15350
15351                /*
15352                 * If we have too little free space, try to free cache
15353                 * before giving up.
15354                 */
15355                if (!origin.staged && pkgLite.recommendedInstallLocation
15356                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15357                    // TODO: focus freeing disk space on the target device
15358                    final StorageManager storage = StorageManager.from(mContext);
15359                    final long lowThreshold = storage.getStorageLowBytes(
15360                            Environment.getDataDirectory());
15361
15362                    final long sizeBytes = mContainerService.calculateInstalledSize(
15363                            origin.resolvedPath, packageAbiOverride);
15364
15365                    try {
15366                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15367                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15368                                installFlags, packageAbiOverride);
15369                    } catch (InstallerException e) {
15370                        Slog.w(TAG, "Failed to free cache", e);
15371                    }
15372
15373                    /*
15374                     * The cache free must have deleted the file we
15375                     * downloaded to install.
15376                     *
15377                     * TODO: fix the "freeCache" call to not delete
15378                     *       the file we care about.
15379                     */
15380                    if (pkgLite.recommendedInstallLocation
15381                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15382                        pkgLite.recommendedInstallLocation
15383                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15384                    }
15385                }
15386            }
15387
15388            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15389                int loc = pkgLite.recommendedInstallLocation;
15390                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15391                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15392                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15393                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15394                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15395                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15396                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15397                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15398                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15399                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15400                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15401                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15402                } else {
15403                    // Override with defaults if needed.
15404                    loc = installLocationPolicy(pkgLite);
15405                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15406                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15407                    } else if (!onSd && !onInt) {
15408                        // Override install location with flags
15409                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15410                            // Set the flag to install on external media.
15411                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15412                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15413                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15414                            if (DEBUG_INSTANT) {
15415                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15416                            }
15417                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15418                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15419                                    |PackageManager.INSTALL_INTERNAL);
15420                        } else {
15421                            // Make sure the flag for installing on external
15422                            // media is unset
15423                            installFlags |= PackageManager.INSTALL_INTERNAL;
15424                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15425                        }
15426                    }
15427                }
15428            }
15429
15430            final InstallArgs args = createInstallArgs(this);
15431            mArgs = args;
15432
15433            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15434                // TODO: http://b/22976637
15435                // Apps installed for "all" users use the device owner to verify the app
15436                UserHandle verifierUser = getUser();
15437                if (verifierUser == UserHandle.ALL) {
15438                    verifierUser = UserHandle.SYSTEM;
15439                }
15440
15441                /*
15442                 * Determine if we have any installed package verifiers. If we
15443                 * do, then we'll defer to them to verify the packages.
15444                 */
15445                final int requiredUid = mRequiredVerifierPackage == null ? -1
15446                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15447                                verifierUser.getIdentifier());
15448                final int installerUid =
15449                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15450                if (!origin.existing && requiredUid != -1
15451                        && isVerificationEnabled(
15452                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15453                    final Intent verification = new Intent(
15454                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15455                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15456                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15457                            PACKAGE_MIME_TYPE);
15458                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15459
15460                    // Query all live verifiers based on current user state
15461                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15462                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15463                            false /*allowDynamicSplits*/);
15464
15465                    if (DEBUG_VERIFY) {
15466                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15467                                + verification.toString() + " with " + pkgLite.verifiers.length
15468                                + " optional verifiers");
15469                    }
15470
15471                    final int verificationId = mPendingVerificationToken++;
15472
15473                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15474
15475                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15476                            installerPackageName);
15477
15478                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15479                            installFlags);
15480
15481                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15482                            pkgLite.packageName);
15483
15484                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15485                            pkgLite.versionCode);
15486
15487                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15488                            pkgLite.getLongVersionCode());
15489
15490                    if (verificationInfo != null) {
15491                        if (verificationInfo.originatingUri != null) {
15492                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15493                                    verificationInfo.originatingUri);
15494                        }
15495                        if (verificationInfo.referrer != null) {
15496                            verification.putExtra(Intent.EXTRA_REFERRER,
15497                                    verificationInfo.referrer);
15498                        }
15499                        if (verificationInfo.originatingUid >= 0) {
15500                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15501                                    verificationInfo.originatingUid);
15502                        }
15503                        if (verificationInfo.installerUid >= 0) {
15504                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15505                                    verificationInfo.installerUid);
15506                        }
15507                    }
15508
15509                    final PackageVerificationState verificationState = new PackageVerificationState(
15510                            requiredUid, args);
15511
15512                    mPendingVerification.append(verificationId, verificationState);
15513
15514                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15515                            receivers, verificationState);
15516
15517                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15518                    final long idleDuration = getVerificationTimeout();
15519
15520                    /*
15521                     * If any sufficient verifiers were listed in the package
15522                     * manifest, attempt to ask them.
15523                     */
15524                    if (sufficientVerifiers != null) {
15525                        final int N = sufficientVerifiers.size();
15526                        if (N == 0) {
15527                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15528                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15529                        } else {
15530                            for (int i = 0; i < N; i++) {
15531                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15532                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15533                                        verifierComponent.getPackageName(), idleDuration,
15534                                        verifierUser.getIdentifier(), false, "package verifier");
15535
15536                                final Intent sufficientIntent = new Intent(verification);
15537                                sufficientIntent.setComponent(verifierComponent);
15538                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15539                            }
15540                        }
15541                    }
15542
15543                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15544                            mRequiredVerifierPackage, receivers);
15545                    if (ret == PackageManager.INSTALL_SUCCEEDED
15546                            && mRequiredVerifierPackage != null) {
15547                        Trace.asyncTraceBegin(
15548                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15549                        /*
15550                         * Send the intent to the required verification agent,
15551                         * but only start the verification timeout after the
15552                         * target BroadcastReceivers have run.
15553                         */
15554                        verification.setComponent(requiredVerifierComponent);
15555                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15556                                mRequiredVerifierPackage, idleDuration,
15557                                verifierUser.getIdentifier(), false, "package verifier");
15558                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15559                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15560                                new BroadcastReceiver() {
15561                                    @Override
15562                                    public void onReceive(Context context, Intent intent) {
15563                                        final Message msg = mHandler
15564                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15565                                        msg.arg1 = verificationId;
15566                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15567                                    }
15568                                }, null, 0, null, null);
15569
15570                        /*
15571                         * We don't want the copy to proceed until verification
15572                         * succeeds, so null out this field.
15573                         */
15574                        mArgs = null;
15575                    }
15576                } else {
15577                    /*
15578                     * No package verification is enabled, so immediately start
15579                     * the remote call to initiate copy using temporary file.
15580                     */
15581                    ret = args.copyApk(mContainerService, true);
15582                }
15583            }
15584
15585            mRet = ret;
15586        }
15587
15588        @Override
15589        void handleReturnCode() {
15590            // If mArgs is null, then MCS couldn't be reached. When it
15591            // reconnects, it will try again to install. At that point, this
15592            // will succeed.
15593            if (mArgs != null) {
15594                processPendingInstall(mArgs, mRet);
15595            }
15596        }
15597
15598        @Override
15599        void handleServiceError() {
15600            mArgs = createInstallArgs(this);
15601            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15602        }
15603    }
15604
15605    private InstallArgs createInstallArgs(InstallParams params) {
15606        if (params.move != null) {
15607            return new MoveInstallArgs(params);
15608        } else {
15609            return new FileInstallArgs(params);
15610        }
15611    }
15612
15613    /**
15614     * Create args that describe an existing installed package. Typically used
15615     * when cleaning up old installs, or used as a move source.
15616     */
15617    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15618            String resourcePath, String[] instructionSets) {
15619        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15620    }
15621
15622    static abstract class InstallArgs {
15623        /** @see InstallParams#origin */
15624        final OriginInfo origin;
15625        /** @see InstallParams#move */
15626        final MoveInfo move;
15627
15628        final IPackageInstallObserver2 observer;
15629        // Always refers to PackageManager flags only
15630        final int installFlags;
15631        final String installerPackageName;
15632        final String volumeUuid;
15633        final UserHandle user;
15634        final String abiOverride;
15635        final String[] installGrantPermissions;
15636        /** If non-null, drop an async trace when the install completes */
15637        final String traceMethod;
15638        final int traceCookie;
15639        final PackageParser.SigningDetails signingDetails;
15640        final int installReason;
15641
15642        // The list of instruction sets supported by this app. This is currently
15643        // only used during the rmdex() phase to clean up resources. We can get rid of this
15644        // if we move dex files under the common app path.
15645        /* nullable */ String[] instructionSets;
15646
15647        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15648                int installFlags, String installerPackageName, String volumeUuid,
15649                UserHandle user, String[] instructionSets,
15650                String abiOverride, String[] installGrantPermissions,
15651                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15652                int installReason) {
15653            this.origin = origin;
15654            this.move = move;
15655            this.installFlags = installFlags;
15656            this.observer = observer;
15657            this.installerPackageName = installerPackageName;
15658            this.volumeUuid = volumeUuid;
15659            this.user = user;
15660            this.instructionSets = instructionSets;
15661            this.abiOverride = abiOverride;
15662            this.installGrantPermissions = installGrantPermissions;
15663            this.traceMethod = traceMethod;
15664            this.traceCookie = traceCookie;
15665            this.signingDetails = signingDetails;
15666            this.installReason = installReason;
15667        }
15668
15669        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15670        abstract int doPreInstall(int status);
15671
15672        /**
15673         * Rename package into final resting place. All paths on the given
15674         * scanned package should be updated to reflect the rename.
15675         */
15676        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15677        abstract int doPostInstall(int status, int uid);
15678
15679        /** @see PackageSettingBase#codePathString */
15680        abstract String getCodePath();
15681        /** @see PackageSettingBase#resourcePathString */
15682        abstract String getResourcePath();
15683
15684        // Need installer lock especially for dex file removal.
15685        abstract void cleanUpResourcesLI();
15686        abstract boolean doPostDeleteLI(boolean delete);
15687
15688        /**
15689         * Called before the source arguments are copied. This is used mostly
15690         * for MoveParams when it needs to read the source file to put it in the
15691         * destination.
15692         */
15693        int doPreCopy() {
15694            return PackageManager.INSTALL_SUCCEEDED;
15695        }
15696
15697        /**
15698         * Called after the source arguments are copied. This is used mostly for
15699         * MoveParams when it needs to read the source file to put it in the
15700         * destination.
15701         */
15702        int doPostCopy(int uid) {
15703            return PackageManager.INSTALL_SUCCEEDED;
15704        }
15705
15706        protected boolean isFwdLocked() {
15707            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15708        }
15709
15710        protected boolean isExternalAsec() {
15711            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15712        }
15713
15714        protected boolean isEphemeral() {
15715            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15716        }
15717
15718        UserHandle getUser() {
15719            return user;
15720        }
15721    }
15722
15723    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15724        if (!allCodePaths.isEmpty()) {
15725            if (instructionSets == null) {
15726                throw new IllegalStateException("instructionSet == null");
15727            }
15728            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15729            for (String codePath : allCodePaths) {
15730                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15731                    try {
15732                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15733                    } catch (InstallerException ignored) {
15734                    }
15735                }
15736            }
15737        }
15738    }
15739
15740    /**
15741     * Logic to handle installation of non-ASEC applications, including copying
15742     * and renaming logic.
15743     */
15744    class FileInstallArgs extends InstallArgs {
15745        private File codeFile;
15746        private File resourceFile;
15747
15748        // Example topology:
15749        // /data/app/com.example/base.apk
15750        // /data/app/com.example/split_foo.apk
15751        // /data/app/com.example/lib/arm/libfoo.so
15752        // /data/app/com.example/lib/arm64/libfoo.so
15753        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15754
15755        /** New install */
15756        FileInstallArgs(InstallParams params) {
15757            super(params.origin, params.move, params.observer, params.installFlags,
15758                    params.installerPackageName, params.volumeUuid,
15759                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15760                    params.grantedRuntimePermissions,
15761                    params.traceMethod, params.traceCookie, params.signingDetails,
15762                    params.installReason);
15763            if (isFwdLocked()) {
15764                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15765            }
15766        }
15767
15768        /** Existing install */
15769        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15770            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15771                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15772                    PackageManager.INSTALL_REASON_UNKNOWN);
15773            this.codeFile = (codePath != null) ? new File(codePath) : null;
15774            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15775        }
15776
15777        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15778            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15779            try {
15780                return doCopyApk(imcs, temp);
15781            } finally {
15782                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15783            }
15784        }
15785
15786        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15787            if (origin.staged) {
15788                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15789                codeFile = origin.file;
15790                resourceFile = origin.file;
15791                return PackageManager.INSTALL_SUCCEEDED;
15792            }
15793
15794            try {
15795                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15796                final File tempDir =
15797                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15798                codeFile = tempDir;
15799                resourceFile = tempDir;
15800            } catch (IOException e) {
15801                Slog.w(TAG, "Failed to create copy file: " + e);
15802                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15803            }
15804
15805            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15806                @Override
15807                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15808                    if (!FileUtils.isValidExtFilename(name)) {
15809                        throw new IllegalArgumentException("Invalid filename: " + name);
15810                    }
15811                    try {
15812                        final File file = new File(codeFile, name);
15813                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15814                                O_RDWR | O_CREAT, 0644);
15815                        Os.chmod(file.getAbsolutePath(), 0644);
15816                        return new ParcelFileDescriptor(fd);
15817                    } catch (ErrnoException e) {
15818                        throw new RemoteException("Failed to open: " + e.getMessage());
15819                    }
15820                }
15821            };
15822
15823            int ret = PackageManager.INSTALL_SUCCEEDED;
15824            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15825            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15826                Slog.e(TAG, "Failed to copy package");
15827                return ret;
15828            }
15829
15830            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15831            NativeLibraryHelper.Handle handle = null;
15832            try {
15833                handle = NativeLibraryHelper.Handle.create(codeFile);
15834                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15835                        abiOverride);
15836            } catch (IOException e) {
15837                Slog.e(TAG, "Copying native libraries failed", e);
15838                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15839            } finally {
15840                IoUtils.closeQuietly(handle);
15841            }
15842
15843            return ret;
15844        }
15845
15846        int doPreInstall(int status) {
15847            if (status != PackageManager.INSTALL_SUCCEEDED) {
15848                cleanUp();
15849            }
15850            return status;
15851        }
15852
15853        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15854            if (status != PackageManager.INSTALL_SUCCEEDED) {
15855                cleanUp();
15856                return false;
15857            }
15858
15859            final File targetDir = codeFile.getParentFile();
15860            final File beforeCodeFile = codeFile;
15861            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15862
15863            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15864            try {
15865                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15866            } catch (ErrnoException e) {
15867                Slog.w(TAG, "Failed to rename", e);
15868                return false;
15869            }
15870
15871            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15872                Slog.w(TAG, "Failed to restorecon");
15873                return false;
15874            }
15875
15876            // Reflect the rename internally
15877            codeFile = afterCodeFile;
15878            resourceFile = afterCodeFile;
15879
15880            // Reflect the rename in scanned details
15881            try {
15882                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15883            } catch (IOException e) {
15884                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15885                return false;
15886            }
15887            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15888                    afterCodeFile, pkg.baseCodePath));
15889            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15890                    afterCodeFile, pkg.splitCodePaths));
15891
15892            // Reflect the rename in app info
15893            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15894            pkg.setApplicationInfoCodePath(pkg.codePath);
15895            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15896            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15897            pkg.setApplicationInfoResourcePath(pkg.codePath);
15898            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15899            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15900
15901            return true;
15902        }
15903
15904        int doPostInstall(int status, int uid) {
15905            if (status != PackageManager.INSTALL_SUCCEEDED) {
15906                cleanUp();
15907            }
15908            return status;
15909        }
15910
15911        @Override
15912        String getCodePath() {
15913            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15914        }
15915
15916        @Override
15917        String getResourcePath() {
15918            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15919        }
15920
15921        private boolean cleanUp() {
15922            if (codeFile == null || !codeFile.exists()) {
15923                return false;
15924            }
15925
15926            removeCodePathLI(codeFile);
15927
15928            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15929                resourceFile.delete();
15930            }
15931
15932            return true;
15933        }
15934
15935        void cleanUpResourcesLI() {
15936            // Try enumerating all code paths before deleting
15937            List<String> allCodePaths = Collections.EMPTY_LIST;
15938            if (codeFile != null && codeFile.exists()) {
15939                try {
15940                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15941                    allCodePaths = pkg.getAllCodePaths();
15942                } catch (PackageParserException e) {
15943                    // Ignored; we tried our best
15944                }
15945            }
15946
15947            cleanUp();
15948            removeDexFiles(allCodePaths, instructionSets);
15949        }
15950
15951        boolean doPostDeleteLI(boolean delete) {
15952            // XXX err, shouldn't we respect the delete flag?
15953            cleanUpResourcesLI();
15954            return true;
15955        }
15956    }
15957
15958    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15959            PackageManagerException {
15960        if (copyRet < 0) {
15961            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15962                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15963                throw new PackageManagerException(copyRet, message);
15964            }
15965        }
15966    }
15967
15968    /**
15969     * Extract the StorageManagerService "container ID" from the full code path of an
15970     * .apk.
15971     */
15972    static String cidFromCodePath(String fullCodePath) {
15973        int eidx = fullCodePath.lastIndexOf("/");
15974        String subStr1 = fullCodePath.substring(0, eidx);
15975        int sidx = subStr1.lastIndexOf("/");
15976        return subStr1.substring(sidx+1, eidx);
15977    }
15978
15979    /**
15980     * Logic to handle movement of existing installed applications.
15981     */
15982    class MoveInstallArgs extends InstallArgs {
15983        private File codeFile;
15984        private File resourceFile;
15985
15986        /** New install */
15987        MoveInstallArgs(InstallParams params) {
15988            super(params.origin, params.move, params.observer, params.installFlags,
15989                    params.installerPackageName, params.volumeUuid,
15990                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15991                    params.grantedRuntimePermissions,
15992                    params.traceMethod, params.traceCookie, params.signingDetails,
15993                    params.installReason);
15994        }
15995
15996        int copyApk(IMediaContainerService imcs, boolean temp) {
15997            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15998                    + move.fromUuid + " to " + move.toUuid);
15999            synchronized (mInstaller) {
16000                try {
16001                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16002                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16003                } catch (InstallerException e) {
16004                    Slog.w(TAG, "Failed to move app", e);
16005                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16006                }
16007            }
16008
16009            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16010            resourceFile = codeFile;
16011            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16012
16013            return PackageManager.INSTALL_SUCCEEDED;
16014        }
16015
16016        int doPreInstall(int status) {
16017            if (status != PackageManager.INSTALL_SUCCEEDED) {
16018                cleanUp(move.toUuid);
16019            }
16020            return status;
16021        }
16022
16023        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16024            if (status != PackageManager.INSTALL_SUCCEEDED) {
16025                cleanUp(move.toUuid);
16026                return false;
16027            }
16028
16029            // Reflect the move in app info
16030            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16031            pkg.setApplicationInfoCodePath(pkg.codePath);
16032            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16033            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16034            pkg.setApplicationInfoResourcePath(pkg.codePath);
16035            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16036            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16037
16038            return true;
16039        }
16040
16041        int doPostInstall(int status, int uid) {
16042            if (status == PackageManager.INSTALL_SUCCEEDED) {
16043                cleanUp(move.fromUuid);
16044            } else {
16045                cleanUp(move.toUuid);
16046            }
16047            return status;
16048        }
16049
16050        @Override
16051        String getCodePath() {
16052            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16053        }
16054
16055        @Override
16056        String getResourcePath() {
16057            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16058        }
16059
16060        private boolean cleanUp(String volumeUuid) {
16061            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16062                    move.dataAppName);
16063            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16064            final int[] userIds = sUserManager.getUserIds();
16065            synchronized (mInstallLock) {
16066                // Clean up both app data and code
16067                // All package moves are frozen until finished
16068                for (int userId : userIds) {
16069                    try {
16070                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16071                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16072                    } catch (InstallerException e) {
16073                        Slog.w(TAG, String.valueOf(e));
16074                    }
16075                }
16076                removeCodePathLI(codeFile);
16077            }
16078            return true;
16079        }
16080
16081        void cleanUpResourcesLI() {
16082            throw new UnsupportedOperationException();
16083        }
16084
16085        boolean doPostDeleteLI(boolean delete) {
16086            throw new UnsupportedOperationException();
16087        }
16088    }
16089
16090    static String getAsecPackageName(String packageCid) {
16091        int idx = packageCid.lastIndexOf("-");
16092        if (idx == -1) {
16093            return packageCid;
16094        }
16095        return packageCid.substring(0, idx);
16096    }
16097
16098    // Utility method used to create code paths based on package name and available index.
16099    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16100        String idxStr = "";
16101        int idx = 1;
16102        // Fall back to default value of idx=1 if prefix is not
16103        // part of oldCodePath
16104        if (oldCodePath != null) {
16105            String subStr = oldCodePath;
16106            // Drop the suffix right away
16107            if (suffix != null && subStr.endsWith(suffix)) {
16108                subStr = subStr.substring(0, subStr.length() - suffix.length());
16109            }
16110            // If oldCodePath already contains prefix find out the
16111            // ending index to either increment or decrement.
16112            int sidx = subStr.lastIndexOf(prefix);
16113            if (sidx != -1) {
16114                subStr = subStr.substring(sidx + prefix.length());
16115                if (subStr != null) {
16116                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16117                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16118                    }
16119                    try {
16120                        idx = Integer.parseInt(subStr);
16121                        if (idx <= 1) {
16122                            idx++;
16123                        } else {
16124                            idx--;
16125                        }
16126                    } catch(NumberFormatException e) {
16127                    }
16128                }
16129            }
16130        }
16131        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16132        return prefix + idxStr;
16133    }
16134
16135    private File getNextCodePath(File targetDir, String packageName) {
16136        File result;
16137        SecureRandom random = new SecureRandom();
16138        byte[] bytes = new byte[16];
16139        do {
16140            random.nextBytes(bytes);
16141            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16142            result = new File(targetDir, packageName + "-" + suffix);
16143        } while (result.exists());
16144        return result;
16145    }
16146
16147    // Utility method that returns the relative package path with respect
16148    // to the installation directory. Like say for /data/data/com.test-1.apk
16149    // string com.test-1 is returned.
16150    static String deriveCodePathName(String codePath) {
16151        if (codePath == null) {
16152            return null;
16153        }
16154        final File codeFile = new File(codePath);
16155        final String name = codeFile.getName();
16156        if (codeFile.isDirectory()) {
16157            return name;
16158        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16159            final int lastDot = name.lastIndexOf('.');
16160            return name.substring(0, lastDot);
16161        } else {
16162            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16163            return null;
16164        }
16165    }
16166
16167    static class PackageInstalledInfo {
16168        String name;
16169        int uid;
16170        // The set of users that originally had this package installed.
16171        int[] origUsers;
16172        // The set of users that now have this package installed.
16173        int[] newUsers;
16174        PackageParser.Package pkg;
16175        int returnCode;
16176        String returnMsg;
16177        String installerPackageName;
16178        PackageRemovedInfo removedInfo;
16179        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16180
16181        public void setError(int code, String msg) {
16182            setReturnCode(code);
16183            setReturnMessage(msg);
16184            Slog.w(TAG, msg);
16185        }
16186
16187        public void setError(String msg, PackageParserException e) {
16188            setReturnCode(e.error);
16189            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16190            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16191            for (int i = 0; i < childCount; i++) {
16192                addedChildPackages.valueAt(i).setError(msg, e);
16193            }
16194            Slog.w(TAG, msg, e);
16195        }
16196
16197        public void setError(String msg, PackageManagerException e) {
16198            returnCode = e.error;
16199            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16200            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16201            for (int i = 0; i < childCount; i++) {
16202                addedChildPackages.valueAt(i).setError(msg, e);
16203            }
16204            Slog.w(TAG, msg, e);
16205        }
16206
16207        public void setReturnCode(int returnCode) {
16208            this.returnCode = returnCode;
16209            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16210            for (int i = 0; i < childCount; i++) {
16211                addedChildPackages.valueAt(i).returnCode = returnCode;
16212            }
16213        }
16214
16215        private void setReturnMessage(String returnMsg) {
16216            this.returnMsg = returnMsg;
16217            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16218            for (int i = 0; i < childCount; i++) {
16219                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16220            }
16221        }
16222
16223        // In some error cases we want to convey more info back to the observer
16224        String origPackage;
16225        String origPermission;
16226    }
16227
16228    /*
16229     * Install a non-existing package.
16230     */
16231    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16232            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16233            String volumeUuid, PackageInstalledInfo res, int installReason) {
16234        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16235
16236        // Remember this for later, in case we need to rollback this install
16237        String pkgName = pkg.packageName;
16238
16239        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16240
16241        synchronized(mPackages) {
16242            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16243            if (renamedPackage != null) {
16244                // A package with the same name is already installed, though
16245                // it has been renamed to an older name.  The package we
16246                // are trying to install should be installed as an update to
16247                // the existing one, but that has not been requested, so bail.
16248                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16249                        + " without first uninstalling package running as "
16250                        + renamedPackage);
16251                return;
16252            }
16253            if (mPackages.containsKey(pkgName)) {
16254                // Don't allow installation over an existing package with the same name.
16255                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16256                        + " without first uninstalling.");
16257                return;
16258            }
16259        }
16260
16261        try {
16262            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16263                    System.currentTimeMillis(), user);
16264
16265            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16266
16267            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16268                prepareAppDataAfterInstallLIF(newPackage);
16269
16270            } else {
16271                // Remove package from internal structures, but keep around any
16272                // data that might have already existed
16273                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16274                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16275            }
16276        } catch (PackageManagerException e) {
16277            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16278        }
16279
16280        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16281    }
16282
16283    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16284        try (DigestInputStream digestStream =
16285                new DigestInputStream(new FileInputStream(file), digest)) {
16286            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16287        }
16288    }
16289
16290    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16291            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16292            PackageInstalledInfo res, int installReason) {
16293        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16294
16295        final PackageParser.Package oldPackage;
16296        final PackageSetting ps;
16297        final String pkgName = pkg.packageName;
16298        final int[] allUsers;
16299        final int[] installedUsers;
16300
16301        synchronized(mPackages) {
16302            oldPackage = mPackages.get(pkgName);
16303            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16304
16305            // don't allow upgrade to target a release SDK from a pre-release SDK
16306            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16307                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16308            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16309                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16310            if (oldTargetsPreRelease
16311                    && !newTargetsPreRelease
16312                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16313                Slog.w(TAG, "Can't install package targeting released sdk");
16314                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16315                return;
16316            }
16317
16318            ps = mSettings.mPackages.get(pkgName);
16319
16320            // verify signatures are valid
16321            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16322            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16323                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16324                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16325                            "New package not signed by keys specified by upgrade-keysets: "
16326                                    + pkgName);
16327                    return;
16328                }
16329            } else {
16330
16331                // default to original signature matching
16332                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16333                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16334                                && !oldPackage.mSigningDetails.checkCapability(
16335                                        pkg.mSigningDetails,
16336                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16337                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16338                            "New package has a different signature: " + pkgName);
16339                    return;
16340                }
16341            }
16342
16343            // don't allow a system upgrade unless the upgrade hash matches
16344            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16345                byte[] digestBytes = null;
16346                try {
16347                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16348                    updateDigest(digest, new File(pkg.baseCodePath));
16349                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16350                        for (String path : pkg.splitCodePaths) {
16351                            updateDigest(digest, new File(path));
16352                        }
16353                    }
16354                    digestBytes = digest.digest();
16355                } catch (NoSuchAlgorithmException | IOException e) {
16356                    res.setError(INSTALL_FAILED_INVALID_APK,
16357                            "Could not compute hash: " + pkgName);
16358                    return;
16359                }
16360                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16361                    res.setError(INSTALL_FAILED_INVALID_APK,
16362                            "New package fails restrict-update check: " + pkgName);
16363                    return;
16364                }
16365                // retain upgrade restriction
16366                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16367            }
16368
16369            // Check for shared user id changes
16370            String invalidPackageName =
16371                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16372            if (invalidPackageName != null) {
16373                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16374                        "Package " + invalidPackageName + " tried to change user "
16375                                + oldPackage.mSharedUserId);
16376                return;
16377            }
16378
16379            // check if the new package supports all of the abis which the old package supports
16380            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16381            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16382            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16383                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16384                        "Update to package " + pkgName + " doesn't support multi arch");
16385                return;
16386            }
16387
16388            // In case of rollback, remember per-user/profile install state
16389            allUsers = sUserManager.getUserIds();
16390            installedUsers = ps.queryInstalledUsers(allUsers, true);
16391
16392            // don't allow an upgrade from full to ephemeral
16393            if (isInstantApp) {
16394                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16395                    for (int currentUser : allUsers) {
16396                        if (!ps.getInstantApp(currentUser)) {
16397                            // can't downgrade from full to instant
16398                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16399                                    + " for user: " + currentUser);
16400                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16401                            return;
16402                        }
16403                    }
16404                } else if (!ps.getInstantApp(user.getIdentifier())) {
16405                    // can't downgrade from full to instant
16406                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16407                            + " for user: " + user.getIdentifier());
16408                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16409                    return;
16410                }
16411            }
16412        }
16413
16414        // Update what is removed
16415        res.removedInfo = new PackageRemovedInfo(this);
16416        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16417        res.removedInfo.removedPackage = oldPackage.packageName;
16418        res.removedInfo.installerPackageName = ps.installerPackageName;
16419        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16420        res.removedInfo.isUpdate = true;
16421        res.removedInfo.origUsers = installedUsers;
16422        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16423        for (int i = 0; i < installedUsers.length; i++) {
16424            final int userId = installedUsers[i];
16425            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16426        }
16427
16428        final int childCount = (oldPackage.childPackages != null)
16429                ? oldPackage.childPackages.size() : 0;
16430        for (int i = 0; i < childCount; i++) {
16431            boolean childPackageUpdated = false;
16432            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16433            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16434            if (res.addedChildPackages != null) {
16435                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16436                if (childRes != null) {
16437                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16438                    childRes.removedInfo.removedPackage = childPkg.packageName;
16439                    if (childPs != null) {
16440                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16441                    }
16442                    childRes.removedInfo.isUpdate = true;
16443                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16444                    childPackageUpdated = true;
16445                }
16446            }
16447            if (!childPackageUpdated) {
16448                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16449                childRemovedRes.removedPackage = childPkg.packageName;
16450                if (childPs != null) {
16451                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16452                }
16453                childRemovedRes.isUpdate = false;
16454                childRemovedRes.dataRemoved = true;
16455                synchronized (mPackages) {
16456                    if (childPs != null) {
16457                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16458                    }
16459                }
16460                if (res.removedInfo.removedChildPackages == null) {
16461                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16462                }
16463                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16464            }
16465        }
16466
16467        boolean sysPkg = (isSystemApp(oldPackage));
16468        if (sysPkg) {
16469            // Set the system/privileged/oem/vendor/product flags as needed
16470            final boolean privileged =
16471                    (oldPackage.applicationInfo.privateFlags
16472                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16473            final boolean oem =
16474                    (oldPackage.applicationInfo.privateFlags
16475                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16476            final boolean vendor =
16477                    (oldPackage.applicationInfo.privateFlags
16478                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16479            final boolean product =
16480                    (oldPackage.applicationInfo.privateFlags
16481                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16482            final @ParseFlags int systemParseFlags = parseFlags;
16483            final @ScanFlags int systemScanFlags = scanFlags
16484                    | SCAN_AS_SYSTEM
16485                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16486                    | (oem ? SCAN_AS_OEM : 0)
16487                    | (vendor ? SCAN_AS_VENDOR : 0)
16488                    | (product ? SCAN_AS_PRODUCT : 0);
16489
16490            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16491                    user, allUsers, installerPackageName, res, installReason);
16492        } else {
16493            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16494                    user, allUsers, installerPackageName, res, installReason);
16495        }
16496    }
16497
16498    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16499            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16500            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16501            String installerPackageName, PackageInstalledInfo res, int installReason) {
16502        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16503                + deletedPackage);
16504
16505        String pkgName = deletedPackage.packageName;
16506        boolean deletedPkg = true;
16507        boolean addedPkg = false;
16508        boolean updatedSettings = false;
16509        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16510        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16511                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16512
16513        final long origUpdateTime = (pkg.mExtras != null)
16514                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16515
16516        // First delete the existing package while retaining the data directory
16517        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16518                res.removedInfo, true, pkg)) {
16519            // If the existing package wasn't successfully deleted
16520            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16521            deletedPkg = false;
16522        } else {
16523            // Successfully deleted the old package; proceed with replace.
16524
16525            // If deleted package lived in a container, give users a chance to
16526            // relinquish resources before killing.
16527            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16528                if (DEBUG_INSTALL) {
16529                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16530                }
16531                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16532                final ArrayList<String> pkgList = new ArrayList<String>(1);
16533                pkgList.add(deletedPackage.applicationInfo.packageName);
16534                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16535            }
16536
16537            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16538                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16539
16540            try {
16541                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16542                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16543                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16544                        installReason);
16545
16546                // Update the in-memory copy of the previous code paths.
16547                PackageSetting ps = mSettings.mPackages.get(pkgName);
16548                if (!killApp) {
16549                    if (ps.oldCodePaths == null) {
16550                        ps.oldCodePaths = new ArraySet<>();
16551                    }
16552                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16553                    if (deletedPackage.splitCodePaths != null) {
16554                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16555                    }
16556                } else {
16557                    ps.oldCodePaths = null;
16558                }
16559                if (ps.childPackageNames != null) {
16560                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16561                        final String childPkgName = ps.childPackageNames.get(i);
16562                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16563                        childPs.oldCodePaths = ps.oldCodePaths;
16564                    }
16565                }
16566                prepareAppDataAfterInstallLIF(newPackage);
16567                addedPkg = true;
16568                mDexManager.notifyPackageUpdated(newPackage.packageName,
16569                        newPackage.baseCodePath, newPackage.splitCodePaths);
16570            } catch (PackageManagerException e) {
16571                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16572            }
16573        }
16574
16575        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16576            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16577
16578            // Revert all internal state mutations and added folders for the failed install
16579            if (addedPkg) {
16580                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16581                        res.removedInfo, true, null);
16582            }
16583
16584            // Restore the old package
16585            if (deletedPkg) {
16586                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16587                File restoreFile = new File(deletedPackage.codePath);
16588                // Parse old package
16589                boolean oldExternal = isExternal(deletedPackage);
16590                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16591                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16592                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16593                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16594                try {
16595                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16596                            null);
16597                } catch (PackageManagerException e) {
16598                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16599                            + e.getMessage());
16600                    return;
16601                }
16602
16603                synchronized (mPackages) {
16604                    // Ensure the installer package name up to date
16605                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16606
16607                    // Update permissions for restored package
16608                    mPermissionManager.updatePermissions(
16609                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16610                            mPermissionCallback);
16611
16612                    mSettings.writeLPr();
16613                }
16614
16615                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16616            }
16617        } else {
16618            synchronized (mPackages) {
16619                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16620                if (ps != null) {
16621                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16622                    if (res.removedInfo.removedChildPackages != null) {
16623                        final int childCount = res.removedInfo.removedChildPackages.size();
16624                        // Iterate in reverse as we may modify the collection
16625                        for (int i = childCount - 1; i >= 0; i--) {
16626                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16627                            if (res.addedChildPackages.containsKey(childPackageName)) {
16628                                res.removedInfo.removedChildPackages.removeAt(i);
16629                            } else {
16630                                PackageRemovedInfo childInfo = res.removedInfo
16631                                        .removedChildPackages.valueAt(i);
16632                                childInfo.removedForAllUsers = mPackages.get(
16633                                        childInfo.removedPackage) == null;
16634                            }
16635                        }
16636                    }
16637                }
16638            }
16639        }
16640    }
16641
16642    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16643            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16644            final @ScanFlags int scanFlags, UserHandle user,
16645            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16646            int installReason) {
16647        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16648                + ", old=" + deletedPackage);
16649
16650        final boolean disabledSystem;
16651
16652        // Remove existing system package
16653        removePackageLI(deletedPackage, true);
16654
16655        synchronized (mPackages) {
16656            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16657        }
16658        if (!disabledSystem) {
16659            // We didn't need to disable the .apk as a current system package,
16660            // which means we are replacing another update that is already
16661            // installed.  We need to make sure to delete the older one's .apk.
16662            res.removedInfo.args = createInstallArgsForExisting(0,
16663                    deletedPackage.applicationInfo.getCodePath(),
16664                    deletedPackage.applicationInfo.getResourcePath(),
16665                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16666        } else {
16667            res.removedInfo.args = null;
16668        }
16669
16670        // Successfully disabled the old package. Now proceed with re-installation
16671        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16672                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16673
16674        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16675        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16676                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16677
16678        PackageParser.Package newPackage = null;
16679        try {
16680            // Add the package to the internal data structures
16681            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16682
16683            // Set the update and install times
16684            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16685            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16686                    System.currentTimeMillis());
16687
16688            // Update the package dynamic state if succeeded
16689            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16690                // Now that the install succeeded make sure we remove data
16691                // directories for any child package the update removed.
16692                final int deletedChildCount = (deletedPackage.childPackages != null)
16693                        ? deletedPackage.childPackages.size() : 0;
16694                final int newChildCount = (newPackage.childPackages != null)
16695                        ? newPackage.childPackages.size() : 0;
16696                for (int i = 0; i < deletedChildCount; i++) {
16697                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16698                    boolean childPackageDeleted = true;
16699                    for (int j = 0; j < newChildCount; j++) {
16700                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16701                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16702                            childPackageDeleted = false;
16703                            break;
16704                        }
16705                    }
16706                    if (childPackageDeleted) {
16707                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16708                                deletedChildPkg.packageName);
16709                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16710                            PackageRemovedInfo removedChildRes = res.removedInfo
16711                                    .removedChildPackages.get(deletedChildPkg.packageName);
16712                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16713                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16714                        }
16715                    }
16716                }
16717
16718                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16719                        installReason);
16720                prepareAppDataAfterInstallLIF(newPackage);
16721
16722                mDexManager.notifyPackageUpdated(newPackage.packageName,
16723                            newPackage.baseCodePath, newPackage.splitCodePaths);
16724            }
16725        } catch (PackageManagerException e) {
16726            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16727            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16728        }
16729
16730        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16731            // Re installation failed. Restore old information
16732            // Remove new pkg information
16733            if (newPackage != null) {
16734                removeInstalledPackageLI(newPackage, true);
16735            }
16736            // Add back the old system package
16737            try {
16738                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16739            } catch (PackageManagerException e) {
16740                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16741            }
16742
16743            synchronized (mPackages) {
16744                if (disabledSystem) {
16745                    enableSystemPackageLPw(deletedPackage);
16746                }
16747
16748                // Ensure the installer package name up to date
16749                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16750
16751                // Update permissions for restored package
16752                mPermissionManager.updatePermissions(
16753                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16754                        mPermissionCallback);
16755
16756                mSettings.writeLPr();
16757            }
16758
16759            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16760                    + " after failed upgrade");
16761        }
16762    }
16763
16764    /**
16765     * Checks whether the parent or any of the child packages have a change shared
16766     * user. For a package to be a valid update the shred users of the parent and
16767     * the children should match. We may later support changing child shared users.
16768     * @param oldPkg The updated package.
16769     * @param newPkg The update package.
16770     * @return The shared user that change between the versions.
16771     */
16772    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16773            PackageParser.Package newPkg) {
16774        // Check parent shared user
16775        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16776            return newPkg.packageName;
16777        }
16778        // Check child shared users
16779        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16780        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16781        for (int i = 0; i < newChildCount; i++) {
16782            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16783            // If this child was present, did it have the same shared user?
16784            for (int j = 0; j < oldChildCount; j++) {
16785                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16786                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16787                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16788                    return newChildPkg.packageName;
16789                }
16790            }
16791        }
16792        return null;
16793    }
16794
16795    private void removeNativeBinariesLI(PackageSetting ps) {
16796        // Remove the lib path for the parent package
16797        if (ps != null) {
16798            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16799            // Remove the lib path for the child packages
16800            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16801            for (int i = 0; i < childCount; i++) {
16802                PackageSetting childPs = null;
16803                synchronized (mPackages) {
16804                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16805                }
16806                if (childPs != null) {
16807                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16808                            .legacyNativeLibraryPathString);
16809                }
16810            }
16811        }
16812    }
16813
16814    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16815        // Enable the parent package
16816        mSettings.enableSystemPackageLPw(pkg.packageName);
16817        // Enable the child packages
16818        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16819        for (int i = 0; i < childCount; i++) {
16820            PackageParser.Package childPkg = pkg.childPackages.get(i);
16821            mSettings.enableSystemPackageLPw(childPkg.packageName);
16822        }
16823    }
16824
16825    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16826            PackageParser.Package newPkg) {
16827        // Disable the parent package (parent always replaced)
16828        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16829        // Disable the child packages
16830        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16831        for (int i = 0; i < childCount; i++) {
16832            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16833            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16834            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16835        }
16836        return disabled;
16837    }
16838
16839    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16840            String installerPackageName) {
16841        // Enable the parent package
16842        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16843        // Enable the child packages
16844        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16845        for (int i = 0; i < childCount; i++) {
16846            PackageParser.Package childPkg = pkg.childPackages.get(i);
16847            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16848        }
16849    }
16850
16851    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16852            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16853        // Update the parent package setting
16854        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16855                res, user, installReason);
16856        // Update the child packages setting
16857        final int childCount = (newPackage.childPackages != null)
16858                ? newPackage.childPackages.size() : 0;
16859        for (int i = 0; i < childCount; i++) {
16860            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16861            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16862            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16863                    childRes.origUsers, childRes, user, installReason);
16864        }
16865    }
16866
16867    private void updateSettingsInternalLI(PackageParser.Package pkg,
16868            String installerPackageName, int[] allUsers, int[] installedForUsers,
16869            PackageInstalledInfo res, UserHandle user, int installReason) {
16870        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16871
16872        final String pkgName = pkg.packageName;
16873
16874        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16875        synchronized (mPackages) {
16876// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16877            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16878                    mPermissionCallback);
16879            // For system-bundled packages, we assume that installing an upgraded version
16880            // of the package implies that the user actually wants to run that new code,
16881            // so we enable the package.
16882            PackageSetting ps = mSettings.mPackages.get(pkgName);
16883            final int userId = user.getIdentifier();
16884            if (ps != null) {
16885                if (isSystemApp(pkg)) {
16886                    if (DEBUG_INSTALL) {
16887                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16888                    }
16889                    // Enable system package for requested users
16890                    if (res.origUsers != null) {
16891                        for (int origUserId : res.origUsers) {
16892                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16893                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16894                                        origUserId, installerPackageName);
16895                            }
16896                        }
16897                    }
16898                    // Also convey the prior install/uninstall state
16899                    if (allUsers != null && installedForUsers != null) {
16900                        for (int currentUserId : allUsers) {
16901                            final boolean installed = ArrayUtils.contains(
16902                                    installedForUsers, currentUserId);
16903                            if (DEBUG_INSTALL) {
16904                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16905                            }
16906                            ps.setInstalled(installed, currentUserId);
16907                        }
16908                        // these install state changes will be persisted in the
16909                        // upcoming call to mSettings.writeLPr().
16910                    }
16911                }
16912                // It's implied that when a user requests installation, they want the app to be
16913                // installed and enabled.
16914                if (userId != UserHandle.USER_ALL) {
16915                    ps.setInstalled(true, userId);
16916                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16917                }
16918
16919                // When replacing an existing package, preserve the original install reason for all
16920                // users that had the package installed before.
16921                final Set<Integer> previousUserIds = new ArraySet<>();
16922                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16923                    final int installReasonCount = res.removedInfo.installReasons.size();
16924                    for (int i = 0; i < installReasonCount; i++) {
16925                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16926                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16927                        ps.setInstallReason(previousInstallReason, previousUserId);
16928                        previousUserIds.add(previousUserId);
16929                    }
16930                }
16931
16932                // Set install reason for users that are having the package newly installed.
16933                if (userId == UserHandle.USER_ALL) {
16934                    for (int currentUserId : sUserManager.getUserIds()) {
16935                        if (!previousUserIds.contains(currentUserId)) {
16936                            ps.setInstallReason(installReason, currentUserId);
16937                        }
16938                    }
16939                } else if (!previousUserIds.contains(userId)) {
16940                    ps.setInstallReason(installReason, userId);
16941                }
16942                mSettings.writeKernelMappingLPr(ps);
16943            }
16944            res.name = pkgName;
16945            res.uid = pkg.applicationInfo.uid;
16946            res.pkg = pkg;
16947            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16948            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16949            //to update install status
16950            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16951            mSettings.writeLPr();
16952            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16953        }
16954
16955        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16956    }
16957
16958    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16959        try {
16960            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16961            installPackageLI(args, res);
16962        } finally {
16963            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16964        }
16965    }
16966
16967    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16968        final int installFlags = args.installFlags;
16969        final String installerPackageName = args.installerPackageName;
16970        final String volumeUuid = args.volumeUuid;
16971        final File tmpPackageFile = new File(args.getCodePath());
16972        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16973        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16974                || (args.volumeUuid != null));
16975        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16976        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16977        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16978        final boolean virtualPreload =
16979                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16980        boolean replace = false;
16981        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16982        if (args.move != null) {
16983            // moving a complete application; perform an initial scan on the new install location
16984            scanFlags |= SCAN_INITIAL;
16985        }
16986        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16987            scanFlags |= SCAN_DONT_KILL_APP;
16988        }
16989        if (instantApp) {
16990            scanFlags |= SCAN_AS_INSTANT_APP;
16991        }
16992        if (fullApp) {
16993            scanFlags |= SCAN_AS_FULL_APP;
16994        }
16995        if (virtualPreload) {
16996            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16997        }
16998
16999        // Result object to be returned
17000        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17001        res.installerPackageName = installerPackageName;
17002
17003        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17004
17005        // Sanity check
17006        if (instantApp && (forwardLocked || onExternal)) {
17007            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17008                    + " external=" + onExternal);
17009            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17010            return;
17011        }
17012
17013        // Retrieve PackageSettings and parse package
17014        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17015                | PackageParser.PARSE_ENFORCE_CODE
17016                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17017                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17018                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17019        PackageParser pp = new PackageParser();
17020        pp.setSeparateProcesses(mSeparateProcesses);
17021        pp.setDisplayMetrics(mMetrics);
17022        pp.setCallback(mPackageParserCallback);
17023
17024        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17025        final PackageParser.Package pkg;
17026        try {
17027            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17028            DexMetadataHelper.validatePackageDexMetadata(pkg);
17029        } catch (PackageParserException e) {
17030            res.setError("Failed parse during installPackageLI", e);
17031            return;
17032        } finally {
17033            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17034        }
17035
17036        // Instant apps have several additional install-time checks.
17037        if (instantApp) {
17038            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
17039                Slog.w(TAG,
17040                        "Instant app package " + pkg.packageName + " does not target at least O");
17041                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17042                        "Instant app package must target at least O");
17043                return;
17044            }
17045            if (pkg.applicationInfo.targetSandboxVersion != 2) {
17046                Slog.w(TAG, "Instant app package " + pkg.packageName
17047                        + " does not target targetSandboxVersion 2");
17048                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17049                        "Instant app package must use targetSandboxVersion 2");
17050                return;
17051            }
17052            if (pkg.mSharedUserId != null) {
17053                Slog.w(TAG, "Instant app package " + pkg.packageName
17054                        + " may not declare sharedUserId.");
17055                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17056                        "Instant app package may not declare a sharedUserId");
17057                return;
17058            }
17059        }
17060
17061        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17062            // Static shared libraries have synthetic package names
17063            renameStaticSharedLibraryPackage(pkg);
17064
17065            // No static shared libs on external storage
17066            if (onExternal) {
17067                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17068                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17069                        "Packages declaring static-shared libs cannot be updated");
17070                return;
17071            }
17072        }
17073
17074        // If we are installing a clustered package add results for the children
17075        if (pkg.childPackages != null) {
17076            synchronized (mPackages) {
17077                final int childCount = pkg.childPackages.size();
17078                for (int i = 0; i < childCount; i++) {
17079                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17080                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17081                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17082                    childRes.pkg = childPkg;
17083                    childRes.name = childPkg.packageName;
17084                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17085                    if (childPs != null) {
17086                        childRes.origUsers = childPs.queryInstalledUsers(
17087                                sUserManager.getUserIds(), true);
17088                    }
17089                    if ((mPackages.containsKey(childPkg.packageName))) {
17090                        childRes.removedInfo = new PackageRemovedInfo(this);
17091                        childRes.removedInfo.removedPackage = childPkg.packageName;
17092                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17093                    }
17094                    if (res.addedChildPackages == null) {
17095                        res.addedChildPackages = new ArrayMap<>();
17096                    }
17097                    res.addedChildPackages.put(childPkg.packageName, childRes);
17098                }
17099            }
17100        }
17101
17102        // If package doesn't declare API override, mark that we have an install
17103        // time CPU ABI override.
17104        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17105            pkg.cpuAbiOverride = args.abiOverride;
17106        }
17107
17108        String pkgName = res.name = pkg.packageName;
17109        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17110            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17111                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17112                return;
17113            }
17114        }
17115
17116        try {
17117            // either use what we've been given or parse directly from the APK
17118            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17119                pkg.setSigningDetails(args.signingDetails);
17120            } else {
17121                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17122            }
17123        } catch (PackageParserException e) {
17124            res.setError("Failed collect during installPackageLI", e);
17125            return;
17126        }
17127
17128        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17129                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17130            Slog.w(TAG, "Instant app package " + pkg.packageName
17131                    + " is not signed with at least APK Signature Scheme v2");
17132            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17133                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17134            return;
17135        }
17136
17137        // Get rid of all references to package scan path via parser.
17138        pp = null;
17139        String oldCodePath = null;
17140        boolean systemApp = false;
17141        synchronized (mPackages) {
17142            // Check if installing already existing package
17143            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17144                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17145                if (pkg.mOriginalPackages != null
17146                        && pkg.mOriginalPackages.contains(oldName)
17147                        && mPackages.containsKey(oldName)) {
17148                    // This package is derived from an original package,
17149                    // and this device has been updating from that original
17150                    // name.  We must continue using the original name, so
17151                    // rename the new package here.
17152                    pkg.setPackageName(oldName);
17153                    pkgName = pkg.packageName;
17154                    replace = true;
17155                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17156                            + oldName + " pkgName=" + pkgName);
17157                } else if (mPackages.containsKey(pkgName)) {
17158                    // This package, under its official name, already exists
17159                    // on the device; we should replace it.
17160                    replace = true;
17161                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17162                }
17163
17164                // Child packages are installed through the parent package
17165                if (pkg.parentPackage != null) {
17166                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17167                            "Package " + pkg.packageName + " is child of package "
17168                                    + pkg.parentPackage.parentPackage + ". Child packages "
17169                                    + "can be updated only through the parent package.");
17170                    return;
17171                }
17172
17173                if (replace) {
17174                    // Prevent apps opting out from runtime permissions
17175                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17176                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17177                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17178                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17179                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17180                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17181                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17182                                        + " doesn't support runtime permissions but the old"
17183                                        + " target SDK " + oldTargetSdk + " does.");
17184                        return;
17185                    }
17186                    // Prevent persistent apps from being updated
17187                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17188                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17189                                "Package " + oldPackage.packageName + " is a persistent app. "
17190                                        + "Persistent apps are not updateable.");
17191                        return;
17192                    }
17193                    // Prevent apps from downgrading their targetSandbox.
17194                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17195                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17196                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17197                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17198                                "Package " + pkg.packageName + " new target sandbox "
17199                                + newTargetSandbox + " is incompatible with the previous value of"
17200                                + oldTargetSandbox + ".");
17201                        return;
17202                    }
17203
17204                    // Prevent installing of child packages
17205                    if (oldPackage.parentPackage != null) {
17206                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17207                                "Package " + pkg.packageName + " is child of package "
17208                                        + oldPackage.parentPackage + ". Child packages "
17209                                        + "can be updated only through the parent package.");
17210                        return;
17211                    }
17212                }
17213            }
17214
17215            PackageSetting ps = mSettings.mPackages.get(pkgName);
17216            if (ps != null) {
17217                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17218
17219                // Static shared libs have same package with different versions where
17220                // we internally use a synthetic package name to allow multiple versions
17221                // of the same package, therefore we need to compare signatures against
17222                // the package setting for the latest library version.
17223                PackageSetting signatureCheckPs = ps;
17224                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17225                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17226                    if (libraryEntry != null) {
17227                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17228                    }
17229                }
17230
17231                // Quick sanity check that we're signed correctly if updating;
17232                // we'll check this again later when scanning, but we want to
17233                // bail early here before tripping over redefined permissions.
17234                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17235                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17236                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17237                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17238                                + pkg.packageName + " upgrade keys do not match the "
17239                                + "previously installed version");
17240                        return;
17241                    }
17242                } else {
17243                    try {
17244                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17245                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17246                        // We don't care about disabledPkgSetting on install for now.
17247                        final boolean compatMatch = verifySignatures(
17248                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17249                                compareRecover);
17250                        // The new KeySets will be re-added later in the scanning process.
17251                        if (compatMatch) {
17252                            synchronized (mPackages) {
17253                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17254                            }
17255                        }
17256                    } catch (PackageManagerException e) {
17257                        res.setError(e.error, e.getMessage());
17258                        return;
17259                    }
17260                }
17261
17262                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17263                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17264                    systemApp = (ps.pkg.applicationInfo.flags &
17265                            ApplicationInfo.FLAG_SYSTEM) != 0;
17266                }
17267                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17268            }
17269
17270            int N = pkg.permissions.size();
17271            for (int i = N-1; i >= 0; i--) {
17272                final PackageParser.Permission perm = pkg.permissions.get(i);
17273                final BasePermission bp =
17274                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17275
17276                // Don't allow anyone but the system to define ephemeral permissions.
17277                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17278                        && !systemApp) {
17279                    Slog.w(TAG, "Non-System package " + pkg.packageName
17280                            + " attempting to delcare ephemeral permission "
17281                            + perm.info.name + "; Removing ephemeral.");
17282                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17283                }
17284
17285                // Check whether the newly-scanned package wants to define an already-defined perm
17286                if (bp != null) {
17287                    // If the defining package is signed with our cert, it's okay.  This
17288                    // also includes the "updating the same package" case, of course.
17289                    // "updating same package" could also involve key-rotation.
17290                    final boolean sigsOk;
17291                    final String sourcePackageName = bp.getSourcePackageName();
17292                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17293                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17294                    if (sourcePackageName.equals(pkg.packageName)
17295                            && (ksms.shouldCheckUpgradeKeySetLocked(
17296                                    sourcePackageSetting, scanFlags))) {
17297                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17298                    } else {
17299
17300                        // in the event of signing certificate rotation, we need to see if the
17301                        // package's certificate has rotated from the current one, or if it is an
17302                        // older certificate with which the current is ok with sharing permissions
17303                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17304                                        pkg.mSigningDetails,
17305                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17306                            sigsOk = true;
17307                        } else if (pkg.mSigningDetails.checkCapability(
17308                                        sourcePackageSetting.signatures.mSigningDetails,
17309                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17310
17311                            // the scanned package checks out, has signing certificate rotation
17312                            // history, and is newer; bring it over
17313                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17314                            sigsOk = true;
17315                        } else {
17316                            sigsOk = false;
17317                        }
17318                    }
17319                    if (!sigsOk) {
17320                        // If the owning package is the system itself, we log but allow
17321                        // install to proceed; we fail the install on all other permission
17322                        // redefinitions.
17323                        if (!sourcePackageName.equals("android")) {
17324                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17325                                    + pkg.packageName + " attempting to redeclare permission "
17326                                    + perm.info.name + " already owned by " + sourcePackageName);
17327                            res.origPermission = perm.info.name;
17328                            res.origPackage = sourcePackageName;
17329                            return;
17330                        } else {
17331                            Slog.w(TAG, "Package " + pkg.packageName
17332                                    + " attempting to redeclare system permission "
17333                                    + perm.info.name + "; ignoring new declaration");
17334                            pkg.permissions.remove(i);
17335                        }
17336                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17337                        // Prevent apps to change protection level to dangerous from any other
17338                        // type as this would allow a privilege escalation where an app adds a
17339                        // normal/signature permission in other app's group and later redefines
17340                        // it as dangerous leading to the group auto-grant.
17341                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17342                                == PermissionInfo.PROTECTION_DANGEROUS) {
17343                            if (bp != null && !bp.isRuntime()) {
17344                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17345                                        + "non-runtime permission " + perm.info.name
17346                                        + " to runtime; keeping old protection level");
17347                                perm.info.protectionLevel = bp.getProtectionLevel();
17348                            }
17349                        }
17350                    }
17351                }
17352            }
17353        }
17354
17355        if (systemApp) {
17356            if (onExternal) {
17357                // Abort update; system app can't be replaced with app on sdcard
17358                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17359                        "Cannot install updates to system apps on sdcard");
17360                return;
17361            } else if (instantApp) {
17362                // Abort update; system app can't be replaced with an instant app
17363                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17364                        "Cannot update a system app with an instant app");
17365                return;
17366            }
17367        }
17368
17369        if (args.move != null) {
17370            // We did an in-place move, so dex is ready to roll
17371            scanFlags |= SCAN_NO_DEX;
17372            scanFlags |= SCAN_MOVE;
17373
17374            synchronized (mPackages) {
17375                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17376                if (ps == null) {
17377                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17378                            "Missing settings for moved package " + pkgName);
17379                }
17380
17381                // We moved the entire application as-is, so bring over the
17382                // previously derived ABI information.
17383                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17384                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17385            }
17386
17387        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17388            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17389            scanFlags |= SCAN_NO_DEX;
17390
17391            try {
17392                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17393                    args.abiOverride : pkg.cpuAbiOverride);
17394                final boolean extractNativeLibs = !pkg.isLibrary();
17395                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17396            } catch (PackageManagerException pme) {
17397                Slog.e(TAG, "Error deriving application ABI", pme);
17398                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17399                return;
17400            }
17401
17402            // Shared libraries for the package need to be updated.
17403            synchronized (mPackages) {
17404                try {
17405                    updateSharedLibrariesLPr(pkg, null);
17406                } catch (PackageManagerException e) {
17407                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17408                }
17409            }
17410        }
17411
17412        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17413            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17414            return;
17415        }
17416
17417        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17418            String apkPath = null;
17419            synchronized (mPackages) {
17420                // Note that if the attacker managed to skip verify setup, for example by tampering
17421                // with the package settings, upon reboot we will do full apk verification when
17422                // verity is not detected.
17423                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17424                if (ps != null && ps.isPrivileged()) {
17425                    apkPath = pkg.baseCodePath;
17426                }
17427            }
17428
17429            if (apkPath != null) {
17430                final VerityUtils.SetupResult result =
17431                        VerityUtils.generateApkVeritySetupData(apkPath);
17432                if (result.isOk()) {
17433                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17434                    FileDescriptor fd = result.getUnownedFileDescriptor();
17435                    try {
17436                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17437                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17438                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17439                    } catch (InstallerException | IOException | DigestException |
17440                             NoSuchAlgorithmException e) {
17441                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17442                                "Failed to set up verity: " + e);
17443                        return;
17444                    } finally {
17445                        IoUtils.closeQuietly(fd);
17446                    }
17447                } else if (result.isFailed()) {
17448                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17449                    return;
17450                } else {
17451                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17452                    // reboot.
17453                }
17454            }
17455        }
17456
17457        if (!instantApp) {
17458            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17459        } else {
17460            if (DEBUG_DOMAIN_VERIFICATION) {
17461                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17462            }
17463        }
17464
17465        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17466                "installPackageLI")) {
17467            if (replace) {
17468                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17469                    // Static libs have a synthetic package name containing the version
17470                    // and cannot be updated as an update would get a new package name,
17471                    // unless this is the exact same version code which is useful for
17472                    // development.
17473                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17474                    if (existingPkg != null &&
17475                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17476                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17477                                + "static-shared libs cannot be updated");
17478                        return;
17479                    }
17480                }
17481                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17482                        installerPackageName, res, args.installReason);
17483            } else {
17484                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17485                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17486            }
17487        }
17488
17489        // Prepare the application profiles for the new code paths.
17490        // This needs to be done before invoking dexopt so that any install-time profile
17491        // can be used for optimizations.
17492        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17493
17494        // Check whether we need to dexopt the app.
17495        //
17496        // NOTE: it is IMPORTANT to call dexopt:
17497        //   - after doRename which will sync the package data from PackageParser.Package and its
17498        //     corresponding ApplicationInfo.
17499        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17500        //     uid of the application (pkg.applicationInfo.uid).
17501        //     This update happens in place!
17502        //
17503        // We only need to dexopt if the package meets ALL of the following conditions:
17504        //   1) it is not forward locked.
17505        //   2) it is not on on an external ASEC container.
17506        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17507        //   4) it is not debuggable.
17508        //
17509        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17510        // complete, so we skip this step during installation. Instead, we'll take extra time
17511        // the first time the instant app starts. It's preferred to do it this way to provide
17512        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17513        // middle of running an instant app. The default behaviour can be overridden
17514        // via gservices.
17515        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17516                && !forwardLocked
17517                && !pkg.applicationInfo.isExternalAsec()
17518                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17519                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
17520                && ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0);
17521
17522        if (performDexopt) {
17523            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17524            // Do not run PackageDexOptimizer through the local performDexOpt
17525            // method because `pkg` may not be in `mPackages` yet.
17526            //
17527            // Also, don't fail application installs if the dexopt step fails.
17528            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17529                    REASON_INSTALL,
17530                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17531                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17532            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17533                    null /* instructionSets */,
17534                    getOrCreateCompilerPackageStats(pkg),
17535                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17536                    dexoptOptions);
17537            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17538        }
17539
17540        // Notify BackgroundDexOptService that the package has been changed.
17541        // If this is an update of a package which used to fail to compile,
17542        // BackgroundDexOptService will remove it from its blacklist.
17543        // TODO: Layering violation
17544        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17545
17546        synchronized (mPackages) {
17547            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17548            if (ps != null) {
17549                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17550                ps.setUpdateAvailable(false /*updateAvailable*/);
17551            }
17552
17553            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17554            for (int i = 0; i < childCount; i++) {
17555                PackageParser.Package childPkg = pkg.childPackages.get(i);
17556                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17557                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17558                if (childPs != null) {
17559                    childRes.newUsers = childPs.queryInstalledUsers(
17560                            sUserManager.getUserIds(), true);
17561                }
17562            }
17563
17564            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17565                updateSequenceNumberLP(ps, res.newUsers);
17566                updateInstantAppInstallerLocked(pkgName);
17567            }
17568        }
17569    }
17570
17571    private void startIntentFilterVerifications(int userId, boolean replacing,
17572            PackageParser.Package pkg) {
17573        if (mIntentFilterVerifierComponent == null) {
17574            Slog.w(TAG, "No IntentFilter verification will not be done as "
17575                    + "there is no IntentFilterVerifier available!");
17576            return;
17577        }
17578
17579        final int verifierUid = getPackageUid(
17580                mIntentFilterVerifierComponent.getPackageName(),
17581                MATCH_DEBUG_TRIAGED_MISSING,
17582                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17583
17584        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17585        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17586        mHandler.sendMessage(msg);
17587
17588        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17589        for (int i = 0; i < childCount; i++) {
17590            PackageParser.Package childPkg = pkg.childPackages.get(i);
17591            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17592            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17593            mHandler.sendMessage(msg);
17594        }
17595    }
17596
17597    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17598            PackageParser.Package pkg) {
17599        int size = pkg.activities.size();
17600        if (size == 0) {
17601            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17602                    "No activity, so no need to verify any IntentFilter!");
17603            return;
17604        }
17605
17606        final boolean hasDomainURLs = hasDomainURLs(pkg);
17607        if (!hasDomainURLs) {
17608            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17609                    "No domain URLs, so no need to verify any IntentFilter!");
17610            return;
17611        }
17612
17613        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17614                + " if any IntentFilter from the " + size
17615                + " Activities needs verification ...");
17616
17617        int count = 0;
17618        final String packageName = pkg.packageName;
17619
17620        synchronized (mPackages) {
17621            // If this is a new install and we see that we've already run verification for this
17622            // package, we have nothing to do: it means the state was restored from backup.
17623            if (!replacing) {
17624                IntentFilterVerificationInfo ivi =
17625                        mSettings.getIntentFilterVerificationLPr(packageName);
17626                if (ivi != null) {
17627                    if (DEBUG_DOMAIN_VERIFICATION) {
17628                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17629                                + ivi.getStatusString());
17630                    }
17631                    return;
17632                }
17633            }
17634
17635            // If any filters need to be verified, then all need to be.
17636            boolean needToVerify = false;
17637            for (PackageParser.Activity a : pkg.activities) {
17638                for (ActivityIntentInfo filter : a.intents) {
17639                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17640                        if (DEBUG_DOMAIN_VERIFICATION) {
17641                            Slog.d(TAG,
17642                                    "Intent filter needs verification, so processing all filters");
17643                        }
17644                        needToVerify = true;
17645                        break;
17646                    }
17647                }
17648            }
17649
17650            if (needToVerify) {
17651                final int verificationId = mIntentFilterVerificationToken++;
17652                for (PackageParser.Activity a : pkg.activities) {
17653                    for (ActivityIntentInfo filter : a.intents) {
17654                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17655                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17656                                    "Verification needed for IntentFilter:" + filter.toString());
17657                            mIntentFilterVerifier.addOneIntentFilterVerification(
17658                                    verifierUid, userId, verificationId, filter, packageName);
17659                            count++;
17660                        }
17661                    }
17662                }
17663            }
17664        }
17665
17666        if (count > 0) {
17667            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17668                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17669                    +  " for userId:" + userId);
17670            mIntentFilterVerifier.startVerifications(userId);
17671        } else {
17672            if (DEBUG_DOMAIN_VERIFICATION) {
17673                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17674            }
17675        }
17676    }
17677
17678    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17679        final ComponentName cn  = filter.activity.getComponentName();
17680        final String packageName = cn.getPackageName();
17681
17682        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17683                packageName);
17684        if (ivi == null) {
17685            return true;
17686        }
17687        int status = ivi.getStatus();
17688        switch (status) {
17689            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17690            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17691                return true;
17692
17693            default:
17694                // Nothing to do
17695                return false;
17696        }
17697    }
17698
17699    private static boolean isMultiArch(ApplicationInfo info) {
17700        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17701    }
17702
17703    private static boolean isExternal(PackageParser.Package pkg) {
17704        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17705    }
17706
17707    private static boolean isExternal(PackageSetting ps) {
17708        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17709    }
17710
17711    private static boolean isSystemApp(PackageParser.Package pkg) {
17712        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17713    }
17714
17715    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17716        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17717    }
17718
17719    private static boolean isOemApp(PackageParser.Package pkg) {
17720        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17721    }
17722
17723    private static boolean isVendorApp(PackageParser.Package pkg) {
17724        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17725    }
17726
17727    private static boolean isProductApp(PackageParser.Package pkg) {
17728        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17729    }
17730
17731    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17732        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17733    }
17734
17735    private static boolean isSystemApp(PackageSetting ps) {
17736        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17737    }
17738
17739    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17740        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17741    }
17742
17743    private int packageFlagsToInstallFlags(PackageSetting ps) {
17744        int installFlags = 0;
17745        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17746            // This existing package was an external ASEC install when we have
17747            // the external flag without a UUID
17748            installFlags |= PackageManager.INSTALL_EXTERNAL;
17749        }
17750        if (ps.isForwardLocked()) {
17751            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17752        }
17753        return installFlags;
17754    }
17755
17756    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17757        if (isExternal(pkg)) {
17758            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17759                return mSettings.getExternalVersion();
17760            } else {
17761                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17762            }
17763        } else {
17764            return mSettings.getInternalVersion();
17765        }
17766    }
17767
17768    private void deleteTempPackageFiles() {
17769        final FilenameFilter filter = new FilenameFilter() {
17770            public boolean accept(File dir, String name) {
17771                return name.startsWith("vmdl") && name.endsWith(".tmp");
17772            }
17773        };
17774        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17775            file.delete();
17776        }
17777    }
17778
17779    @Override
17780    public void deletePackageAsUser(String packageName, int versionCode,
17781            IPackageDeleteObserver observer, int userId, int flags) {
17782        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17783                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17784    }
17785
17786    @Override
17787    public void deletePackageVersioned(VersionedPackage versionedPackage,
17788            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17789        final int callingUid = Binder.getCallingUid();
17790        mContext.enforceCallingOrSelfPermission(
17791                android.Manifest.permission.DELETE_PACKAGES, null);
17792        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17793        Preconditions.checkNotNull(versionedPackage);
17794        Preconditions.checkNotNull(observer);
17795        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17796                PackageManager.VERSION_CODE_HIGHEST,
17797                Long.MAX_VALUE, "versionCode must be >= -1");
17798
17799        final String packageName = versionedPackage.getPackageName();
17800        final long versionCode = versionedPackage.getLongVersionCode();
17801        final String internalPackageName;
17802        synchronized (mPackages) {
17803            // Normalize package name to handle renamed packages and static libs
17804            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17805        }
17806
17807        final int uid = Binder.getCallingUid();
17808        if (!isOrphaned(internalPackageName)
17809                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17810            try {
17811                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17812                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17813                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17814                observer.onUserActionRequired(intent);
17815            } catch (RemoteException re) {
17816            }
17817            return;
17818        }
17819        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17820        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17821        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17822            mContext.enforceCallingOrSelfPermission(
17823                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17824                    "deletePackage for user " + userId);
17825        }
17826
17827        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17828            try {
17829                observer.onPackageDeleted(packageName,
17830                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17831            } catch (RemoteException re) {
17832            }
17833            return;
17834        }
17835
17836        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17837            try {
17838                observer.onPackageDeleted(packageName,
17839                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17840            } catch (RemoteException re) {
17841            }
17842            return;
17843        }
17844
17845        if (DEBUG_REMOVE) {
17846            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17847                    + " deleteAllUsers: " + deleteAllUsers + " version="
17848                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17849                    ? "VERSION_CODE_HIGHEST" : versionCode));
17850        }
17851        // Queue up an async operation since the package deletion may take a little while.
17852        mHandler.post(new Runnable() {
17853            public void run() {
17854                mHandler.removeCallbacks(this);
17855                int returnCode;
17856                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17857                boolean doDeletePackage = true;
17858                if (ps != null) {
17859                    final boolean targetIsInstantApp =
17860                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17861                    doDeletePackage = !targetIsInstantApp
17862                            || canViewInstantApps;
17863                }
17864                if (doDeletePackage) {
17865                    if (!deleteAllUsers) {
17866                        returnCode = deletePackageX(internalPackageName, versionCode,
17867                                userId, deleteFlags);
17868                    } else {
17869                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17870                                internalPackageName, users);
17871                        // If nobody is blocking uninstall, proceed with delete for all users
17872                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17873                            returnCode = deletePackageX(internalPackageName, versionCode,
17874                                    userId, deleteFlags);
17875                        } else {
17876                            // Otherwise uninstall individually for users with blockUninstalls=false
17877                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17878                            for (int userId : users) {
17879                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17880                                    returnCode = deletePackageX(internalPackageName, versionCode,
17881                                            userId, userFlags);
17882                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17883                                        Slog.w(TAG, "Package delete failed for user " + userId
17884                                                + ", returnCode " + returnCode);
17885                                    }
17886                                }
17887                            }
17888                            // The app has only been marked uninstalled for certain users.
17889                            // We still need to report that delete was blocked
17890                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17891                        }
17892                    }
17893                } else {
17894                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17895                }
17896                try {
17897                    observer.onPackageDeleted(packageName, returnCode, null);
17898                } catch (RemoteException e) {
17899                    Log.i(TAG, "Observer no longer exists.");
17900                } //end catch
17901            } //end run
17902        });
17903    }
17904
17905    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17906        if (pkg.staticSharedLibName != null) {
17907            return pkg.manifestPackageName;
17908        }
17909        return pkg.packageName;
17910    }
17911
17912    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17913        // Handle renamed packages
17914        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17915        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17916
17917        // Is this a static library?
17918        LongSparseArray<SharedLibraryEntry> versionedLib =
17919                mStaticLibsByDeclaringPackage.get(packageName);
17920        if (versionedLib == null || versionedLib.size() <= 0) {
17921            return packageName;
17922        }
17923
17924        // Figure out which lib versions the caller can see
17925        LongSparseLongArray versionsCallerCanSee = null;
17926        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17927        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17928                && callingAppId != Process.ROOT_UID) {
17929            versionsCallerCanSee = new LongSparseLongArray();
17930            String libName = versionedLib.valueAt(0).info.getName();
17931            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17932            if (uidPackages != null) {
17933                for (String uidPackage : uidPackages) {
17934                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17935                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17936                    if (libIdx >= 0) {
17937                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17938                        versionsCallerCanSee.append(libVersion, libVersion);
17939                    }
17940                }
17941            }
17942        }
17943
17944        // Caller can see nothing - done
17945        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17946            return packageName;
17947        }
17948
17949        // Find the version the caller can see and the app version code
17950        SharedLibraryEntry highestVersion = null;
17951        final int versionCount = versionedLib.size();
17952        for (int i = 0; i < versionCount; i++) {
17953            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17954            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17955                    libEntry.info.getLongVersion()) < 0) {
17956                continue;
17957            }
17958            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17959            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17960                if (libVersionCode == versionCode) {
17961                    return libEntry.apk;
17962                }
17963            } else if (highestVersion == null) {
17964                highestVersion = libEntry;
17965            } else if (libVersionCode  > highestVersion.info
17966                    .getDeclaringPackage().getLongVersionCode()) {
17967                highestVersion = libEntry;
17968            }
17969        }
17970
17971        if (highestVersion != null) {
17972            return highestVersion.apk;
17973        }
17974
17975        return packageName;
17976    }
17977
17978    boolean isCallerVerifier(int callingUid) {
17979        final int callingUserId = UserHandle.getUserId(callingUid);
17980        return mRequiredVerifierPackage != null &&
17981                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17982    }
17983
17984    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17985        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17986              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17987            return true;
17988        }
17989        final int callingUserId = UserHandle.getUserId(callingUid);
17990        // If the caller installed the pkgName, then allow it to silently uninstall.
17991        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17992            return true;
17993        }
17994
17995        // Allow package verifier to silently uninstall.
17996        if (mRequiredVerifierPackage != null &&
17997                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17998            return true;
17999        }
18000
18001        // Allow package uninstaller to silently uninstall.
18002        if (mRequiredUninstallerPackage != null &&
18003                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18004            return true;
18005        }
18006
18007        // Allow storage manager to silently uninstall.
18008        if (mStorageManagerPackage != null &&
18009                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18010            return true;
18011        }
18012
18013        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18014        // uninstall for device owner provisioning.
18015        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18016                == PERMISSION_GRANTED) {
18017            return true;
18018        }
18019
18020        return false;
18021    }
18022
18023    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18024        int[] result = EMPTY_INT_ARRAY;
18025        for (int userId : userIds) {
18026            if (getBlockUninstallForUser(packageName, userId)) {
18027                result = ArrayUtils.appendInt(result, userId);
18028            }
18029        }
18030        return result;
18031    }
18032
18033    @Override
18034    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18035        final int callingUid = Binder.getCallingUid();
18036        if (getInstantAppPackageName(callingUid) != null
18037                && !isCallerSameApp(packageName, callingUid)) {
18038            return false;
18039        }
18040        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18041    }
18042
18043    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18044        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18045                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18046        try {
18047            if (dpm != null) {
18048                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18049                        /* callingUserOnly =*/ false);
18050                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18051                        : deviceOwnerComponentName.getPackageName();
18052                // Does the package contains the device owner?
18053                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18054                // this check is probably not needed, since DO should be registered as a device
18055                // admin on some user too. (Original bug for this: b/17657954)
18056                if (packageName.equals(deviceOwnerPackageName)) {
18057                    return true;
18058                }
18059                // Does it contain a device admin for any user?
18060                int[] users;
18061                if (userId == UserHandle.USER_ALL) {
18062                    users = sUserManager.getUserIds();
18063                } else {
18064                    users = new int[]{userId};
18065                }
18066                for (int i = 0; i < users.length; ++i) {
18067                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18068                        return true;
18069                    }
18070                }
18071            }
18072        } catch (RemoteException e) {
18073        }
18074        return false;
18075    }
18076
18077    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18078        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18079    }
18080
18081    /**
18082     *  This method is an internal method that could be get invoked either
18083     *  to delete an installed package or to clean up a failed installation.
18084     *  After deleting an installed package, a broadcast is sent to notify any
18085     *  listeners that the package has been removed. For cleaning up a failed
18086     *  installation, the broadcast is not necessary since the package's
18087     *  installation wouldn't have sent the initial broadcast either
18088     *  The key steps in deleting a package are
18089     *  deleting the package information in internal structures like mPackages,
18090     *  deleting the packages base directories through installd
18091     *  updating mSettings to reflect current status
18092     *  persisting settings for later use
18093     *  sending a broadcast if necessary
18094     */
18095    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18096        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18097        final boolean res;
18098
18099        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18100                ? UserHandle.USER_ALL : userId;
18101
18102        if (isPackageDeviceAdmin(packageName, removeUser)) {
18103            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18104            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18105        }
18106
18107        PackageSetting uninstalledPs = null;
18108        PackageParser.Package pkg = null;
18109
18110        // for the uninstall-updates case and restricted profiles, remember the per-
18111        // user handle installed state
18112        int[] allUsers;
18113        synchronized (mPackages) {
18114            uninstalledPs = mSettings.mPackages.get(packageName);
18115            if (uninstalledPs == null) {
18116                Slog.w(TAG, "Not removing non-existent package " + packageName);
18117                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18118            }
18119
18120            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18121                    && uninstalledPs.versionCode != versionCode) {
18122                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18123                        + uninstalledPs.versionCode + " != " + versionCode);
18124                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18125            }
18126
18127            // Static shared libs can be declared by any package, so let us not
18128            // allow removing a package if it provides a lib others depend on.
18129            pkg = mPackages.get(packageName);
18130
18131            allUsers = sUserManager.getUserIds();
18132
18133            if (pkg != null && pkg.staticSharedLibName != null) {
18134                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18135                        pkg.staticSharedLibVersion);
18136                if (libEntry != null) {
18137                    for (int currUserId : allUsers) {
18138                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18139                            continue;
18140                        }
18141                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18142                                libEntry.info, 0, currUserId);
18143                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18144                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18145                                    + " hosting lib " + libEntry.info.getName() + " version "
18146                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18147                                    + " for user " + currUserId);
18148                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18149                        }
18150                    }
18151                }
18152            }
18153
18154            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18155        }
18156
18157        final int freezeUser;
18158        if (isUpdatedSystemApp(uninstalledPs)
18159                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18160            // We're downgrading a system app, which will apply to all users, so
18161            // freeze them all during the downgrade
18162            freezeUser = UserHandle.USER_ALL;
18163        } else {
18164            freezeUser = removeUser;
18165        }
18166
18167        synchronized (mInstallLock) {
18168            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18169            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18170                    deleteFlags, "deletePackageX")) {
18171                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18172                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18173            }
18174            synchronized (mPackages) {
18175                if (res) {
18176                    if (pkg != null) {
18177                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18178                    }
18179                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18180                    updateInstantAppInstallerLocked(packageName);
18181                }
18182            }
18183        }
18184
18185        if (res) {
18186            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18187            info.sendPackageRemovedBroadcasts(killApp);
18188            info.sendSystemPackageUpdatedBroadcasts();
18189            info.sendSystemPackageAppearedBroadcasts();
18190        }
18191        // Force a gc here.
18192        Runtime.getRuntime().gc();
18193        // Delete the resources here after sending the broadcast to let
18194        // other processes clean up before deleting resources.
18195        if (info.args != null) {
18196            synchronized (mInstallLock) {
18197                info.args.doPostDeleteLI(true);
18198            }
18199        }
18200
18201        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18202    }
18203
18204    static class PackageRemovedInfo {
18205        final PackageSender packageSender;
18206        String removedPackage;
18207        String installerPackageName;
18208        int uid = -1;
18209        int removedAppId = -1;
18210        int[] origUsers;
18211        int[] removedUsers = null;
18212        int[] broadcastUsers = null;
18213        int[] instantUserIds = null;
18214        SparseArray<Integer> installReasons;
18215        boolean isRemovedPackageSystemUpdate = false;
18216        boolean isUpdate;
18217        boolean dataRemoved;
18218        boolean removedForAllUsers;
18219        boolean isStaticSharedLib;
18220        // Clean up resources deleted packages.
18221        InstallArgs args = null;
18222        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18223        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18224
18225        PackageRemovedInfo(PackageSender packageSender) {
18226            this.packageSender = packageSender;
18227        }
18228
18229        void sendPackageRemovedBroadcasts(boolean killApp) {
18230            sendPackageRemovedBroadcastInternal(killApp);
18231            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18232            for (int i = 0; i < childCount; i++) {
18233                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18234                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18235            }
18236        }
18237
18238        void sendSystemPackageUpdatedBroadcasts() {
18239            if (isRemovedPackageSystemUpdate) {
18240                sendSystemPackageUpdatedBroadcastsInternal();
18241                final int childCount = (removedChildPackages != null)
18242                        ? removedChildPackages.size() : 0;
18243                for (int i = 0; i < childCount; i++) {
18244                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18245                    if (childInfo.isRemovedPackageSystemUpdate) {
18246                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18247                    }
18248                }
18249            }
18250        }
18251
18252        void sendSystemPackageAppearedBroadcasts() {
18253            final int packageCount = (appearedChildPackages != null)
18254                    ? appearedChildPackages.size() : 0;
18255            for (int i = 0; i < packageCount; i++) {
18256                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18257                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18258                    true /*sendBootCompleted*/, false /*startReceiver*/,
18259                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18260            }
18261        }
18262
18263        private void sendSystemPackageUpdatedBroadcastsInternal() {
18264            Bundle extras = new Bundle(2);
18265            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18266            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18267            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18268                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18269            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18270                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18271            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18272                null, null, 0, removedPackage, null, null, null);
18273            if (installerPackageName != null) {
18274                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18275                        removedPackage, extras, 0 /*flags*/,
18276                        installerPackageName, null, null, null);
18277                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18278                        removedPackage, extras, 0 /*flags*/,
18279                        installerPackageName, null, null, null);
18280            }
18281        }
18282
18283        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18284            // Don't send static shared library removal broadcasts as these
18285            // libs are visible only the the apps that depend on them an one
18286            // cannot remove the library if it has a dependency.
18287            if (isStaticSharedLib) {
18288                return;
18289            }
18290            Bundle extras = new Bundle(2);
18291            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18292            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18293            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18294            if (isUpdate || isRemovedPackageSystemUpdate) {
18295                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18296            }
18297            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18298            if (removedPackage != null) {
18299                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18300                    removedPackage, extras, 0, null /*targetPackage*/, null,
18301                    broadcastUsers, instantUserIds);
18302                if (installerPackageName != null) {
18303                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18304                            removedPackage, extras, 0 /*flags*/,
18305                            installerPackageName, null, broadcastUsers, instantUserIds);
18306                }
18307                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18308                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18309                        removedPackage, extras,
18310                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18311                        null, null, broadcastUsers, instantUserIds);
18312                    packageSender.notifyPackageRemoved(removedPackage);
18313                }
18314            }
18315            if (removedAppId >= 0) {
18316                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18317                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18318                    null, null, broadcastUsers, instantUserIds);
18319            }
18320        }
18321
18322        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18323            removedUsers = userIds;
18324            if (removedUsers == null) {
18325                broadcastUsers = null;
18326                return;
18327            }
18328
18329            broadcastUsers = EMPTY_INT_ARRAY;
18330            instantUserIds = EMPTY_INT_ARRAY;
18331            for (int i = userIds.length - 1; i >= 0; --i) {
18332                final int userId = userIds[i];
18333                if (deletedPackageSetting.getInstantApp(userId)) {
18334                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18335                } else {
18336                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18337                }
18338            }
18339        }
18340    }
18341
18342    /*
18343     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18344     * flag is not set, the data directory is removed as well.
18345     * make sure this flag is set for partially installed apps. If not its meaningless to
18346     * delete a partially installed application.
18347     */
18348    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18349            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18350        String packageName = ps.name;
18351        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18352        // Retrieve object to delete permissions for shared user later on
18353        final PackageParser.Package deletedPkg;
18354        final PackageSetting deletedPs;
18355        // reader
18356        synchronized (mPackages) {
18357            deletedPkg = mPackages.get(packageName);
18358            deletedPs = mSettings.mPackages.get(packageName);
18359            if (outInfo != null) {
18360                outInfo.removedPackage = packageName;
18361                outInfo.installerPackageName = ps.installerPackageName;
18362                outInfo.isStaticSharedLib = deletedPkg != null
18363                        && deletedPkg.staticSharedLibName != null;
18364                outInfo.populateUsers(deletedPs == null ? null
18365                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18366            }
18367        }
18368
18369        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18370
18371        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18372            final PackageParser.Package resolvedPkg;
18373            if (deletedPkg != null) {
18374                resolvedPkg = deletedPkg;
18375            } else {
18376                // We don't have a parsed package when it lives on an ejected
18377                // adopted storage device, so fake something together
18378                resolvedPkg = new PackageParser.Package(ps.name);
18379                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18380            }
18381            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18382                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18383            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18384            if (outInfo != null) {
18385                outInfo.dataRemoved = true;
18386            }
18387            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18388        }
18389
18390        int removedAppId = -1;
18391
18392        // writer
18393        synchronized (mPackages) {
18394            boolean installedStateChanged = false;
18395            if (deletedPs != null) {
18396                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18397                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18398                    clearDefaultBrowserIfNeeded(packageName);
18399                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18400                    removedAppId = mSettings.removePackageLPw(packageName);
18401                    if (outInfo != null) {
18402                        outInfo.removedAppId = removedAppId;
18403                    }
18404                    mPermissionManager.updatePermissions(
18405                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18406                    if (deletedPs.sharedUser != null) {
18407                        // Remove permissions associated with package. Since runtime
18408                        // permissions are per user we have to kill the removed package
18409                        // or packages running under the shared user of the removed
18410                        // package if revoking the permissions requested only by the removed
18411                        // package is successful and this causes a change in gids.
18412                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18413                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18414                                    userId);
18415                            if (userIdToKill == UserHandle.USER_ALL
18416                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18417                                // If gids changed for this user, kill all affected packages.
18418                                mHandler.post(new Runnable() {
18419                                    @Override
18420                                    public void run() {
18421                                        // This has to happen with no lock held.
18422                                        killApplication(deletedPs.name, deletedPs.appId,
18423                                                KILL_APP_REASON_GIDS_CHANGED);
18424                                    }
18425                                });
18426                                break;
18427                            }
18428                        }
18429                    }
18430                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18431                }
18432                // make sure to preserve per-user disabled state if this removal was just
18433                // a downgrade of a system app to the factory package
18434                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18435                    if (DEBUG_REMOVE) {
18436                        Slog.d(TAG, "Propagating install state across downgrade");
18437                    }
18438                    for (int userId : allUserHandles) {
18439                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18440                        if (DEBUG_REMOVE) {
18441                            Slog.d(TAG, "    user " + userId + " => " + installed);
18442                        }
18443                        if (installed != ps.getInstalled(userId)) {
18444                            installedStateChanged = true;
18445                        }
18446                        ps.setInstalled(installed, userId);
18447                    }
18448                }
18449            }
18450            // can downgrade to reader
18451            if (writeSettings) {
18452                // Save settings now
18453                mSettings.writeLPr();
18454            }
18455            if (installedStateChanged) {
18456                mSettings.writeKernelMappingLPr(ps);
18457            }
18458        }
18459        if (removedAppId != -1) {
18460            // A user ID was deleted here. Go through all users and remove it
18461            // from KeyStore.
18462            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18463        }
18464    }
18465
18466    static boolean locationIsPrivileged(String path) {
18467        try {
18468            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18469            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18470            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18471            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18472            return path.startsWith(privilegedAppDir.getCanonicalPath())
18473                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18474                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18475                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18476        } catch (IOException e) {
18477            Slog.e(TAG, "Unable to access code path " + path);
18478        }
18479        return false;
18480    }
18481
18482    static boolean locationIsOem(String path) {
18483        try {
18484            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18485        } catch (IOException e) {
18486            Slog.e(TAG, "Unable to access code path " + path);
18487        }
18488        return false;
18489    }
18490
18491    static boolean locationIsVendor(String path) {
18492        try {
18493            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18494                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18495        } catch (IOException e) {
18496            Slog.e(TAG, "Unable to access code path " + path);
18497        }
18498        return false;
18499    }
18500
18501    static boolean locationIsProduct(String path) {
18502        try {
18503            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18504        } catch (IOException e) {
18505            Slog.e(TAG, "Unable to access code path " + path);
18506        }
18507        return false;
18508    }
18509
18510    /*
18511     * Tries to delete system package.
18512     */
18513    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18514            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18515            boolean writeSettings) {
18516        if (deletedPs.parentPackageName != null) {
18517            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18518            return false;
18519        }
18520
18521        final boolean applyUserRestrictions
18522                = (allUserHandles != null) && (outInfo.origUsers != null);
18523        final PackageSetting disabledPs;
18524        // Confirm if the system package has been updated
18525        // An updated system app can be deleted. This will also have to restore
18526        // the system pkg from system partition
18527        // reader
18528        synchronized (mPackages) {
18529            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18530        }
18531
18532        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18533                + " disabledPs=" + disabledPs);
18534
18535        if (disabledPs == null) {
18536            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18537            return false;
18538        } else if (DEBUG_REMOVE) {
18539            Slog.d(TAG, "Deleting system pkg from data partition");
18540        }
18541
18542        if (DEBUG_REMOVE) {
18543            if (applyUserRestrictions) {
18544                Slog.d(TAG, "Remembering install states:");
18545                for (int userId : allUserHandles) {
18546                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18547                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18548                }
18549            }
18550        }
18551
18552        // Delete the updated package
18553        outInfo.isRemovedPackageSystemUpdate = true;
18554        if (outInfo.removedChildPackages != null) {
18555            final int childCount = (deletedPs.childPackageNames != null)
18556                    ? deletedPs.childPackageNames.size() : 0;
18557            for (int i = 0; i < childCount; i++) {
18558                String childPackageName = deletedPs.childPackageNames.get(i);
18559                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18560                        .contains(childPackageName)) {
18561                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18562                            childPackageName);
18563                    if (childInfo != null) {
18564                        childInfo.isRemovedPackageSystemUpdate = true;
18565                    }
18566                }
18567            }
18568        }
18569
18570        if (disabledPs.versionCode < deletedPs.versionCode) {
18571            // Delete data for downgrades
18572            flags &= ~PackageManager.DELETE_KEEP_DATA;
18573        } else {
18574            // Preserve data by setting flag
18575            flags |= PackageManager.DELETE_KEEP_DATA;
18576        }
18577
18578        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18579                outInfo, writeSettings, disabledPs.pkg);
18580        if (!ret) {
18581            return false;
18582        }
18583
18584        // writer
18585        synchronized (mPackages) {
18586            // NOTE: The system package always needs to be enabled; even if it's for
18587            // a compressed stub. If we don't, installing the system package fails
18588            // during scan [scanning checks the disabled packages]. We will reverse
18589            // this later, after we've "installed" the stub.
18590            // Reinstate the old system package
18591            enableSystemPackageLPw(disabledPs.pkg);
18592            // Remove any native libraries from the upgraded package.
18593            removeNativeBinariesLI(deletedPs);
18594        }
18595
18596        // Install the system package
18597        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18598        try {
18599            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18600                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18601        } catch (PackageManagerException e) {
18602            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18603                    + e.getMessage());
18604            return false;
18605        } finally {
18606            if (disabledPs.pkg.isStub) {
18607                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18608            }
18609        }
18610        return true;
18611    }
18612
18613    /**
18614     * Installs a package that's already on the system partition.
18615     */
18616    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18617            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18618            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18619                    throws PackageManagerException {
18620        @ParseFlags int parseFlags =
18621                mDefParseFlags
18622                | PackageParser.PARSE_MUST_BE_APK
18623                | PackageParser.PARSE_IS_SYSTEM_DIR;
18624        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18625        if (isPrivileged || locationIsPrivileged(codePathString)) {
18626            scanFlags |= SCAN_AS_PRIVILEGED;
18627        }
18628        if (locationIsOem(codePathString)) {
18629            scanFlags |= SCAN_AS_OEM;
18630        }
18631        if (locationIsVendor(codePathString)) {
18632            scanFlags |= SCAN_AS_VENDOR;
18633        }
18634        if (locationIsProduct(codePathString)) {
18635            scanFlags |= SCAN_AS_PRODUCT;
18636        }
18637
18638        final File codePath = new File(codePathString);
18639        final PackageParser.Package pkg =
18640                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18641
18642        try {
18643            // update shared libraries for the newly re-installed system package
18644            updateSharedLibrariesLPr(pkg, null);
18645        } catch (PackageManagerException e) {
18646            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18647        }
18648
18649        prepareAppDataAfterInstallLIF(pkg);
18650
18651        // writer
18652        synchronized (mPackages) {
18653            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18654
18655            // Propagate the permissions state as we do not want to drop on the floor
18656            // runtime permissions. The update permissions method below will take
18657            // care of removing obsolete permissions and grant install permissions.
18658            if (origPermissionState != null) {
18659                ps.getPermissionsState().copyFrom(origPermissionState);
18660            }
18661            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18662                    mPermissionCallback);
18663
18664            final boolean applyUserRestrictions
18665                    = (allUserHandles != null) && (origUserHandles != null);
18666            if (applyUserRestrictions) {
18667                boolean installedStateChanged = false;
18668                if (DEBUG_REMOVE) {
18669                    Slog.d(TAG, "Propagating install state across reinstall");
18670                }
18671                for (int userId : allUserHandles) {
18672                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18673                    if (DEBUG_REMOVE) {
18674                        Slog.d(TAG, "    user " + userId + " => " + installed);
18675                    }
18676                    if (installed != ps.getInstalled(userId)) {
18677                        installedStateChanged = true;
18678                    }
18679                    ps.setInstalled(installed, userId);
18680
18681                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18682                }
18683                // Regardless of writeSettings we need to ensure that this restriction
18684                // state propagation is persisted
18685                mSettings.writeAllUsersPackageRestrictionsLPr();
18686                if (installedStateChanged) {
18687                    mSettings.writeKernelMappingLPr(ps);
18688                }
18689            }
18690            // can downgrade to reader here
18691            if (writeSettings) {
18692                mSettings.writeLPr();
18693            }
18694        }
18695        return pkg;
18696    }
18697
18698    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18699            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18700            PackageRemovedInfo outInfo, boolean writeSettings,
18701            PackageParser.Package replacingPackage) {
18702        synchronized (mPackages) {
18703            if (outInfo != null) {
18704                outInfo.uid = ps.appId;
18705            }
18706
18707            if (outInfo != null && outInfo.removedChildPackages != null) {
18708                final int childCount = (ps.childPackageNames != null)
18709                        ? ps.childPackageNames.size() : 0;
18710                for (int i = 0; i < childCount; i++) {
18711                    String childPackageName = ps.childPackageNames.get(i);
18712                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18713                    if (childPs == null) {
18714                        return false;
18715                    }
18716                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18717                            childPackageName);
18718                    if (childInfo != null) {
18719                        childInfo.uid = childPs.appId;
18720                    }
18721                }
18722            }
18723        }
18724
18725        // Delete package data from internal structures and also remove data if flag is set
18726        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18727
18728        // Delete the child packages data
18729        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18730        for (int i = 0; i < childCount; i++) {
18731            PackageSetting childPs;
18732            synchronized (mPackages) {
18733                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18734            }
18735            if (childPs != null) {
18736                PackageRemovedInfo childOutInfo = (outInfo != null
18737                        && outInfo.removedChildPackages != null)
18738                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18739                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18740                        && (replacingPackage != null
18741                        && !replacingPackage.hasChildPackage(childPs.name))
18742                        ? flags & ~DELETE_KEEP_DATA : flags;
18743                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18744                        deleteFlags, writeSettings);
18745            }
18746        }
18747
18748        // Delete application code and resources only for parent packages
18749        if (ps.parentPackageName == null) {
18750            if (deleteCodeAndResources && (outInfo != null)) {
18751                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18752                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18753                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18754            }
18755        }
18756
18757        return true;
18758    }
18759
18760    @Override
18761    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18762            int userId) {
18763        mContext.enforceCallingOrSelfPermission(
18764                android.Manifest.permission.DELETE_PACKAGES, null);
18765        synchronized (mPackages) {
18766            // Cannot block uninstall of static shared libs as they are
18767            // considered a part of the using app (emulating static linking).
18768            // Also static libs are installed always on internal storage.
18769            PackageParser.Package pkg = mPackages.get(packageName);
18770            if (pkg != null && pkg.staticSharedLibName != null) {
18771                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18772                        + " providing static shared library: " + pkg.staticSharedLibName);
18773                return false;
18774            }
18775            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18776            mSettings.writePackageRestrictionsLPr(userId);
18777        }
18778        return true;
18779    }
18780
18781    @Override
18782    public boolean getBlockUninstallForUser(String packageName, int userId) {
18783        synchronized (mPackages) {
18784            final PackageSetting ps = mSettings.mPackages.get(packageName);
18785            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18786                return false;
18787            }
18788            return mSettings.getBlockUninstallLPr(userId, packageName);
18789        }
18790    }
18791
18792    @Override
18793    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18794        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18795        synchronized (mPackages) {
18796            PackageSetting ps = mSettings.mPackages.get(packageName);
18797            if (ps == null) {
18798                Log.w(TAG, "Package doesn't exist: " + packageName);
18799                return false;
18800            }
18801            if (systemUserApp) {
18802                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18803            } else {
18804                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18805            }
18806            mSettings.writeLPr();
18807        }
18808        return true;
18809    }
18810
18811    /*
18812     * This method handles package deletion in general
18813     */
18814    private boolean deletePackageLIF(String packageName, UserHandle user,
18815            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18816            PackageRemovedInfo outInfo, boolean writeSettings,
18817            PackageParser.Package replacingPackage) {
18818        if (packageName == null) {
18819            Slog.w(TAG, "Attempt to delete null packageName.");
18820            return false;
18821        }
18822
18823        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18824
18825        PackageSetting ps;
18826        synchronized (mPackages) {
18827            ps = mSettings.mPackages.get(packageName);
18828            if (ps == null) {
18829                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18830                return false;
18831            }
18832
18833            if (ps.parentPackageName != null && (!isSystemApp(ps)
18834                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18835                if (DEBUG_REMOVE) {
18836                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18837                            + ((user == null) ? UserHandle.USER_ALL : user));
18838                }
18839                final int removedUserId = (user != null) ? user.getIdentifier()
18840                        : UserHandle.USER_ALL;
18841
18842                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18843                    return false;
18844                }
18845                markPackageUninstalledForUserLPw(ps, user);
18846                scheduleWritePackageRestrictionsLocked(user);
18847                return true;
18848            }
18849        }
18850
18851        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18852        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18853            unsuspendForSuspendingPackage(packageName, userId);
18854        }
18855
18856
18857        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18858                && user.getIdentifier() != UserHandle.USER_ALL)) {
18859            // The caller is asking that the package only be deleted for a single
18860            // user.  To do this, we just mark its uninstalled state and delete
18861            // its data. If this is a system app, we only allow this to happen if
18862            // they have set the special DELETE_SYSTEM_APP which requests different
18863            // semantics than normal for uninstalling system apps.
18864            markPackageUninstalledForUserLPw(ps, user);
18865
18866            if (!isSystemApp(ps)) {
18867                // Do not uninstall the APK if an app should be cached
18868                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18869                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18870                    // Other user still have this package installed, so all
18871                    // we need to do is clear this user's data and save that
18872                    // it is uninstalled.
18873                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18874                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18875                        return false;
18876                    }
18877                    scheduleWritePackageRestrictionsLocked(user);
18878                    return true;
18879                } else {
18880                    // We need to set it back to 'installed' so the uninstall
18881                    // broadcasts will be sent correctly.
18882                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18883                    ps.setInstalled(true, user.getIdentifier());
18884                    mSettings.writeKernelMappingLPr(ps);
18885                }
18886            } else {
18887                // This is a system app, so we assume that the
18888                // other users still have this package installed, so all
18889                // we need to do is clear this user's data and save that
18890                // it is uninstalled.
18891                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18892                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18893                    return false;
18894                }
18895                scheduleWritePackageRestrictionsLocked(user);
18896                return true;
18897            }
18898        }
18899
18900        // If we are deleting a composite package for all users, keep track
18901        // of result for each child.
18902        if (ps.childPackageNames != null && outInfo != null) {
18903            synchronized (mPackages) {
18904                final int childCount = ps.childPackageNames.size();
18905                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18906                for (int i = 0; i < childCount; i++) {
18907                    String childPackageName = ps.childPackageNames.get(i);
18908                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18909                    childInfo.removedPackage = childPackageName;
18910                    childInfo.installerPackageName = ps.installerPackageName;
18911                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18912                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18913                    if (childPs != null) {
18914                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18915                    }
18916                }
18917            }
18918        }
18919
18920        boolean ret = false;
18921        if (isSystemApp(ps)) {
18922            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18923            // When an updated system application is deleted we delete the existing resources
18924            // as well and fall back to existing code in system partition
18925            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18926        } else {
18927            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18928            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18929                    outInfo, writeSettings, replacingPackage);
18930        }
18931
18932        // Take a note whether we deleted the package for all users
18933        if (outInfo != null) {
18934            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18935            if (outInfo.removedChildPackages != null) {
18936                synchronized (mPackages) {
18937                    final int childCount = outInfo.removedChildPackages.size();
18938                    for (int i = 0; i < childCount; i++) {
18939                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18940                        if (childInfo != null) {
18941                            childInfo.removedForAllUsers = mPackages.get(
18942                                    childInfo.removedPackage) == null;
18943                        }
18944                    }
18945                }
18946            }
18947            // If we uninstalled an update to a system app there may be some
18948            // child packages that appeared as they are declared in the system
18949            // app but were not declared in the update.
18950            if (isSystemApp(ps)) {
18951                synchronized (mPackages) {
18952                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18953                    final int childCount = (updatedPs.childPackageNames != null)
18954                            ? updatedPs.childPackageNames.size() : 0;
18955                    for (int i = 0; i < childCount; i++) {
18956                        String childPackageName = updatedPs.childPackageNames.get(i);
18957                        if (outInfo.removedChildPackages == null
18958                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18959                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18960                            if (childPs == null) {
18961                                continue;
18962                            }
18963                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18964                            installRes.name = childPackageName;
18965                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18966                            installRes.pkg = mPackages.get(childPackageName);
18967                            installRes.uid = childPs.pkg.applicationInfo.uid;
18968                            if (outInfo.appearedChildPackages == null) {
18969                                outInfo.appearedChildPackages = new ArrayMap<>();
18970                            }
18971                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18972                        }
18973                    }
18974                }
18975            }
18976        }
18977
18978        return ret;
18979    }
18980
18981    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18982        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18983                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18984        for (int nextUserId : userIds) {
18985            if (DEBUG_REMOVE) {
18986                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18987            }
18988            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18989                    false /*installed*/,
18990                    true /*stopped*/,
18991                    true /*notLaunched*/,
18992                    false /*hidden*/,
18993                    false /*suspended*/,
18994                    null /*suspendingPackage*/,
18995                    null /*dialogMessage*/,
18996                    null /*suspendedAppExtras*/,
18997                    null /*suspendedLauncherExtras*/,
18998                    false /*instantApp*/,
18999                    false /*virtualPreload*/,
19000                    null /*lastDisableAppCaller*/,
19001                    null /*enabledComponents*/,
19002                    null /*disabledComponents*/,
19003                    ps.readUserState(nextUserId).domainVerificationStatus,
19004                    0, PackageManager.INSTALL_REASON_UNKNOWN,
19005                    null /*harmfulAppWarning*/);
19006        }
19007        mSettings.writeKernelMappingLPr(ps);
19008    }
19009
19010    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19011            PackageRemovedInfo outInfo) {
19012        final PackageParser.Package pkg;
19013        synchronized (mPackages) {
19014            pkg = mPackages.get(ps.name);
19015        }
19016
19017        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19018                : new int[] {userId};
19019        for (int nextUserId : userIds) {
19020            if (DEBUG_REMOVE) {
19021                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19022                        + nextUserId);
19023            }
19024
19025            destroyAppDataLIF(pkg, userId,
19026                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19027            destroyAppProfilesLIF(pkg, userId);
19028            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19029            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19030            schedulePackageCleaning(ps.name, nextUserId, false);
19031            synchronized (mPackages) {
19032                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19033                    scheduleWritePackageRestrictionsLocked(nextUserId);
19034                }
19035                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19036            }
19037        }
19038
19039        if (outInfo != null) {
19040            outInfo.removedPackage = ps.name;
19041            outInfo.installerPackageName = ps.installerPackageName;
19042            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19043            outInfo.removedAppId = ps.appId;
19044            outInfo.removedUsers = userIds;
19045            outInfo.broadcastUsers = userIds;
19046        }
19047
19048        return true;
19049    }
19050
19051    private final class ClearStorageConnection implements ServiceConnection {
19052        IMediaContainerService mContainerService;
19053
19054        @Override
19055        public void onServiceConnected(ComponentName name, IBinder service) {
19056            synchronized (this) {
19057                mContainerService = IMediaContainerService.Stub
19058                        .asInterface(Binder.allowBlocking(service));
19059                notifyAll();
19060            }
19061        }
19062
19063        @Override
19064        public void onServiceDisconnected(ComponentName name) {
19065        }
19066    }
19067
19068    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19069        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19070
19071        final boolean mounted;
19072        if (Environment.isExternalStorageEmulated()) {
19073            mounted = true;
19074        } else {
19075            final String status = Environment.getExternalStorageState();
19076
19077            mounted = status.equals(Environment.MEDIA_MOUNTED)
19078                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19079        }
19080
19081        if (!mounted) {
19082            return;
19083        }
19084
19085        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19086        int[] users;
19087        if (userId == UserHandle.USER_ALL) {
19088            users = sUserManager.getUserIds();
19089        } else {
19090            users = new int[] { userId };
19091        }
19092        final ClearStorageConnection conn = new ClearStorageConnection();
19093        if (mContext.bindServiceAsUser(
19094                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19095            try {
19096                for (int curUser : users) {
19097                    long timeout = SystemClock.uptimeMillis() + 5000;
19098                    synchronized (conn) {
19099                        long now;
19100                        while (conn.mContainerService == null &&
19101                                (now = SystemClock.uptimeMillis()) < timeout) {
19102                            try {
19103                                conn.wait(timeout - now);
19104                            } catch (InterruptedException e) {
19105                            }
19106                        }
19107                    }
19108                    if (conn.mContainerService == null) {
19109                        return;
19110                    }
19111
19112                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19113                    clearDirectory(conn.mContainerService,
19114                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19115                    if (allData) {
19116                        clearDirectory(conn.mContainerService,
19117                                userEnv.buildExternalStorageAppDataDirs(packageName));
19118                        clearDirectory(conn.mContainerService,
19119                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19120                    }
19121                }
19122            } finally {
19123                mContext.unbindService(conn);
19124            }
19125        }
19126    }
19127
19128    @Override
19129    public void clearApplicationProfileData(String packageName) {
19130        enforceSystemOrRoot("Only the system can clear all profile data");
19131
19132        final PackageParser.Package pkg;
19133        synchronized (mPackages) {
19134            pkg = mPackages.get(packageName);
19135        }
19136
19137        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19138            synchronized (mInstallLock) {
19139                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19140            }
19141        }
19142    }
19143
19144    @Override
19145    public void clearApplicationUserData(final String packageName,
19146            final IPackageDataObserver observer, final int userId) {
19147        mContext.enforceCallingOrSelfPermission(
19148                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19149
19150        final int callingUid = Binder.getCallingUid();
19151        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19152                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19153
19154        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19155        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19156        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19157            throw new SecurityException("Cannot clear data for a protected package: "
19158                    + packageName);
19159        }
19160        // Queue up an async operation since the package deletion may take a little while.
19161        mHandler.post(new Runnable() {
19162            public void run() {
19163                mHandler.removeCallbacks(this);
19164                final boolean succeeded;
19165                if (!filterApp) {
19166                    try (PackageFreezer freezer = freezePackage(packageName,
19167                            "clearApplicationUserData")) {
19168                        synchronized (mInstallLock) {
19169                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19170                        }
19171                        clearExternalStorageDataSync(packageName, userId, true);
19172                        synchronized (mPackages) {
19173                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19174                                    packageName, userId);
19175                        }
19176                    }
19177                    if (succeeded) {
19178                        // invoke DeviceStorageMonitor's update method to clear any notifications
19179                        DeviceStorageMonitorInternal dsm = LocalServices
19180                                .getService(DeviceStorageMonitorInternal.class);
19181                        if (dsm != null) {
19182                            dsm.checkMemory();
19183                        }
19184                        if (checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId)
19185                                == PERMISSION_GRANTED) {
19186                            unsuspendForSuspendingPackage(packageName, userId);
19187                        }
19188                    }
19189                } else {
19190                    succeeded = false;
19191                }
19192                if (observer != null) {
19193                    try {
19194                        observer.onRemoveCompleted(packageName, succeeded);
19195                    } catch (RemoteException e) {
19196                        Log.i(TAG, "Observer no longer exists.");
19197                    }
19198                } //end if observer
19199            } //end run
19200        });
19201    }
19202
19203    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19204        if (packageName == null) {
19205            Slog.w(TAG, "Attempt to delete null packageName.");
19206            return false;
19207        }
19208
19209        // Try finding details about the requested package
19210        PackageParser.Package pkg;
19211        synchronized (mPackages) {
19212            pkg = mPackages.get(packageName);
19213            if (pkg == null) {
19214                final PackageSetting ps = mSettings.mPackages.get(packageName);
19215                if (ps != null) {
19216                    pkg = ps.pkg;
19217                }
19218            }
19219
19220            if (pkg == null) {
19221                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19222                return false;
19223            }
19224
19225            PackageSetting ps = (PackageSetting) pkg.mExtras;
19226            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19227        }
19228
19229        clearAppDataLIF(pkg, userId,
19230                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19231
19232        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19233        removeKeystoreDataIfNeeded(userId, appId);
19234
19235        UserManagerInternal umInternal = getUserManagerInternal();
19236        final int flags;
19237        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19238            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19239        } else if (umInternal.isUserRunning(userId)) {
19240            flags = StorageManager.FLAG_STORAGE_DE;
19241        } else {
19242            flags = 0;
19243        }
19244        prepareAppDataContentsLIF(pkg, userId, flags);
19245
19246        return true;
19247    }
19248
19249    /**
19250     * Reverts user permission state changes (permissions and flags) in
19251     * all packages for a given user.
19252     *
19253     * @param userId The device user for which to do a reset.
19254     */
19255    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19256        final int packageCount = mPackages.size();
19257        for (int i = 0; i < packageCount; i++) {
19258            PackageParser.Package pkg = mPackages.valueAt(i);
19259            PackageSetting ps = (PackageSetting) pkg.mExtras;
19260            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19261        }
19262    }
19263
19264    private void resetNetworkPolicies(int userId) {
19265        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19266    }
19267
19268    /**
19269     * Reverts user permission state changes (permissions and flags).
19270     *
19271     * @param ps The package for which to reset.
19272     * @param userId The device user for which to do a reset.
19273     */
19274    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19275            final PackageSetting ps, final int userId) {
19276        if (ps.pkg == null) {
19277            return;
19278        }
19279
19280        // These are flags that can change base on user actions.
19281        final int userSettableMask = FLAG_PERMISSION_USER_SET
19282                | FLAG_PERMISSION_USER_FIXED
19283                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19284                | FLAG_PERMISSION_REVIEW_REQUIRED;
19285
19286        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19287                | FLAG_PERMISSION_POLICY_FIXED;
19288
19289        boolean writeInstallPermissions = false;
19290        boolean writeRuntimePermissions = false;
19291
19292        final int permissionCount = ps.pkg.requestedPermissions.size();
19293        for (int i = 0; i < permissionCount; i++) {
19294            final String permName = ps.pkg.requestedPermissions.get(i);
19295            final BasePermission bp =
19296                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19297            if (bp == null) {
19298                continue;
19299            }
19300
19301            // If shared user we just reset the state to which only this app contributed.
19302            if (ps.sharedUser != null) {
19303                boolean used = false;
19304                final int packageCount = ps.sharedUser.packages.size();
19305                for (int j = 0; j < packageCount; j++) {
19306                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19307                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19308                            && pkg.pkg.requestedPermissions.contains(permName)) {
19309                        used = true;
19310                        break;
19311                    }
19312                }
19313                if (used) {
19314                    continue;
19315                }
19316            }
19317
19318            final PermissionsState permissionsState = ps.getPermissionsState();
19319
19320            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19321
19322            // Always clear the user settable flags.
19323            final boolean hasInstallState =
19324                    permissionsState.getInstallPermissionState(permName) != null;
19325            // If permission review is enabled and this is a legacy app, mark the
19326            // permission as requiring a review as this is the initial state.
19327            int flags = 0;
19328            if (mSettings.mPermissions.mPermissionReviewRequired
19329                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19330                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19331            }
19332            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19333                if (hasInstallState) {
19334                    writeInstallPermissions = true;
19335                } else {
19336                    writeRuntimePermissions = true;
19337                }
19338            }
19339
19340            // Below is only runtime permission handling.
19341            if (!bp.isRuntime()) {
19342                continue;
19343            }
19344
19345            // Never clobber system or policy.
19346            if ((oldFlags & policyOrSystemFlags) != 0) {
19347                continue;
19348            }
19349
19350            // If this permission was granted by default, make sure it is.
19351            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19352                if (permissionsState.grantRuntimePermission(bp, userId)
19353                        != PERMISSION_OPERATION_FAILURE) {
19354                    writeRuntimePermissions = true;
19355                }
19356            // If permission review is enabled the permissions for a legacy apps
19357            // are represented as constantly granted runtime ones, so don't revoke.
19358            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19359                // Otherwise, reset the permission.
19360                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19361                switch (revokeResult) {
19362                    case PERMISSION_OPERATION_SUCCESS:
19363                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19364                        writeRuntimePermissions = true;
19365                        final int appId = ps.appId;
19366                        mHandler.post(new Runnable() {
19367                            @Override
19368                            public void run() {
19369                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19370                            }
19371                        });
19372                    } break;
19373                }
19374            }
19375        }
19376
19377        // Synchronously write as we are taking permissions away.
19378        if (writeRuntimePermissions) {
19379            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19380        }
19381
19382        // Synchronously write as we are taking permissions away.
19383        if (writeInstallPermissions) {
19384            mSettings.writeLPr();
19385        }
19386    }
19387
19388    /**
19389     * Remove entries from the keystore daemon. Will only remove it if the
19390     * {@code appId} is valid.
19391     */
19392    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19393        if (appId < 0) {
19394            return;
19395        }
19396
19397        final KeyStore keyStore = KeyStore.getInstance();
19398        if (keyStore != null) {
19399            if (userId == UserHandle.USER_ALL) {
19400                for (final int individual : sUserManager.getUserIds()) {
19401                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19402                }
19403            } else {
19404                keyStore.clearUid(UserHandle.getUid(userId, appId));
19405            }
19406        } else {
19407            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19408        }
19409    }
19410
19411    @Override
19412    public void deleteApplicationCacheFiles(final String packageName,
19413            final IPackageDataObserver observer) {
19414        final int userId = UserHandle.getCallingUserId();
19415        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19416    }
19417
19418    @Override
19419    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19420            final IPackageDataObserver observer) {
19421        final int callingUid = Binder.getCallingUid();
19422        if (mContext.checkCallingOrSelfPermission(
19423                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19424                != PackageManager.PERMISSION_GRANTED) {
19425            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19426            if (mContext.checkCallingOrSelfPermission(
19427                    android.Manifest.permission.DELETE_CACHE_FILES)
19428                    == PackageManager.PERMISSION_GRANTED) {
19429                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19430                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19431                        ", silently ignoring");
19432                return;
19433            }
19434            mContext.enforceCallingOrSelfPermission(
19435                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19436        }
19437        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19438                /* requireFullPermission= */ true, /* checkShell= */ false,
19439                "delete application cache files");
19440        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19441                android.Manifest.permission.ACCESS_INSTANT_APPS);
19442
19443        final PackageParser.Package pkg;
19444        synchronized (mPackages) {
19445            pkg = mPackages.get(packageName);
19446        }
19447
19448        // Queue up an async operation since the package deletion may take a little while.
19449        mHandler.post(new Runnable() {
19450            public void run() {
19451                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19452                boolean doClearData = true;
19453                if (ps != null) {
19454                    final boolean targetIsInstantApp =
19455                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19456                    doClearData = !targetIsInstantApp
19457                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19458                }
19459                if (doClearData) {
19460                    synchronized (mInstallLock) {
19461                        final int flags = StorageManager.FLAG_STORAGE_DE
19462                                | StorageManager.FLAG_STORAGE_CE;
19463                        // We're only clearing cache files, so we don't care if the
19464                        // app is unfrozen and still able to run
19465                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19466                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19467                    }
19468                    clearExternalStorageDataSync(packageName, userId, false);
19469                }
19470                if (observer != null) {
19471                    try {
19472                        observer.onRemoveCompleted(packageName, true);
19473                    } catch (RemoteException e) {
19474                        Log.i(TAG, "Observer no longer exists.");
19475                    }
19476                }
19477            }
19478        });
19479    }
19480
19481    @Override
19482    public void getPackageSizeInfo(final String packageName, int userHandle,
19483            final IPackageStatsObserver observer) {
19484        throw new UnsupportedOperationException(
19485                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19486    }
19487
19488    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19489        final PackageSetting ps;
19490        synchronized (mPackages) {
19491            ps = mSettings.mPackages.get(packageName);
19492            if (ps == null) {
19493                Slog.w(TAG, "Failed to find settings for " + packageName);
19494                return false;
19495            }
19496        }
19497
19498        final String[] packageNames = { packageName };
19499        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19500        final String[] codePaths = { ps.codePathString };
19501
19502        try {
19503            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19504                    ps.appId, ceDataInodes, codePaths, stats);
19505
19506            // For now, ignore code size of packages on system partition
19507            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19508                stats.codeSize = 0;
19509            }
19510
19511            // External clients expect these to be tracked separately
19512            stats.dataSize -= stats.cacheSize;
19513
19514        } catch (InstallerException e) {
19515            Slog.w(TAG, String.valueOf(e));
19516            return false;
19517        }
19518
19519        return true;
19520    }
19521
19522    private int getUidTargetSdkVersionLockedLPr(int uid) {
19523        Object obj = mSettings.getUserIdLPr(uid);
19524        if (obj instanceof SharedUserSetting) {
19525            final SharedUserSetting sus = (SharedUserSetting) obj;
19526            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19527            final Iterator<PackageSetting> it = sus.packages.iterator();
19528            while (it.hasNext()) {
19529                final PackageSetting ps = it.next();
19530                if (ps.pkg != null) {
19531                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19532                    if (v < vers) vers = v;
19533                }
19534            }
19535            return vers;
19536        } else if (obj instanceof PackageSetting) {
19537            final PackageSetting ps = (PackageSetting) obj;
19538            if (ps.pkg != null) {
19539                return ps.pkg.applicationInfo.targetSdkVersion;
19540            }
19541        }
19542        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19543    }
19544
19545    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19546        final PackageParser.Package p = mPackages.get(packageName);
19547        if (p != null) {
19548            return p.applicationInfo.targetSdkVersion;
19549        }
19550        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19551    }
19552
19553    @Override
19554    public void addPreferredActivity(IntentFilter filter, int match,
19555            ComponentName[] set, ComponentName activity, int userId) {
19556        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19557                "Adding preferred");
19558    }
19559
19560    private void addPreferredActivityInternal(IntentFilter filter, int match,
19561            ComponentName[] set, ComponentName activity, boolean always, int userId,
19562            String opname) {
19563        // writer
19564        int callingUid = Binder.getCallingUid();
19565        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19566                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19567        if (filter.countActions() == 0) {
19568            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19569            return;
19570        }
19571        synchronized (mPackages) {
19572            if (mContext.checkCallingOrSelfPermission(
19573                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19574                    != PackageManager.PERMISSION_GRANTED) {
19575                if (getUidTargetSdkVersionLockedLPr(callingUid)
19576                        < Build.VERSION_CODES.FROYO) {
19577                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19578                            + callingUid);
19579                    return;
19580                }
19581                mContext.enforceCallingOrSelfPermission(
19582                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19583            }
19584
19585            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19586            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19587                    + userId + ":");
19588            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19589            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19590            scheduleWritePackageRestrictionsLocked(userId);
19591            postPreferredActivityChangedBroadcast(userId);
19592        }
19593    }
19594
19595    private void postPreferredActivityChangedBroadcast(int userId) {
19596        mHandler.post(() -> {
19597            final IActivityManager am = ActivityManager.getService();
19598            if (am == null) {
19599                return;
19600            }
19601
19602            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19603            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19604            try {
19605                am.broadcastIntent(null, intent, null, null,
19606                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19607                        null, false, false, userId);
19608            } catch (RemoteException e) {
19609            }
19610        });
19611    }
19612
19613    @Override
19614    public void replacePreferredActivity(IntentFilter filter, int match,
19615            ComponentName[] set, ComponentName activity, int userId) {
19616        if (filter.countActions() != 1) {
19617            throw new IllegalArgumentException(
19618                    "replacePreferredActivity expects filter to have only 1 action.");
19619        }
19620        if (filter.countDataAuthorities() != 0
19621                || filter.countDataPaths() != 0
19622                || filter.countDataSchemes() > 1
19623                || filter.countDataTypes() != 0) {
19624            throw new IllegalArgumentException(
19625                    "replacePreferredActivity expects filter to have no data authorities, " +
19626                    "paths, or types; and at most one scheme.");
19627        }
19628
19629        final int callingUid = Binder.getCallingUid();
19630        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19631                true /* requireFullPermission */, false /* checkShell */,
19632                "replace preferred activity");
19633        synchronized (mPackages) {
19634            if (mContext.checkCallingOrSelfPermission(
19635                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19636                    != PackageManager.PERMISSION_GRANTED) {
19637                if (getUidTargetSdkVersionLockedLPr(callingUid)
19638                        < Build.VERSION_CODES.FROYO) {
19639                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19640                            + Binder.getCallingUid());
19641                    return;
19642                }
19643                mContext.enforceCallingOrSelfPermission(
19644                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19645            }
19646
19647            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19648            if (pir != null) {
19649                // Get all of the existing entries that exactly match this filter.
19650                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19651                if (existing != null && existing.size() == 1) {
19652                    PreferredActivity cur = existing.get(0);
19653                    if (DEBUG_PREFERRED) {
19654                        Slog.i(TAG, "Checking replace of preferred:");
19655                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19656                        if (!cur.mPref.mAlways) {
19657                            Slog.i(TAG, "  -- CUR; not mAlways!");
19658                        } else {
19659                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19660                            Slog.i(TAG, "  -- CUR: mSet="
19661                                    + Arrays.toString(cur.mPref.mSetComponents));
19662                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19663                            Slog.i(TAG, "  -- NEW: mMatch="
19664                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19665                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19666                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19667                        }
19668                    }
19669                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19670                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19671                            && cur.mPref.sameSet(set)) {
19672                        // Setting the preferred activity to what it happens to be already
19673                        if (DEBUG_PREFERRED) {
19674                            Slog.i(TAG, "Replacing with same preferred activity "
19675                                    + cur.mPref.mShortComponent + " for user "
19676                                    + userId + ":");
19677                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19678                        }
19679                        return;
19680                    }
19681                }
19682
19683                if (existing != null) {
19684                    if (DEBUG_PREFERRED) {
19685                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19686                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19687                    }
19688                    for (int i = 0; i < existing.size(); i++) {
19689                        PreferredActivity pa = existing.get(i);
19690                        if (DEBUG_PREFERRED) {
19691                            Slog.i(TAG, "Removing existing preferred activity "
19692                                    + pa.mPref.mComponent + ":");
19693                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19694                        }
19695                        pir.removeFilter(pa);
19696                    }
19697                }
19698            }
19699            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19700                    "Replacing preferred");
19701        }
19702    }
19703
19704    @Override
19705    public void clearPackagePreferredActivities(String packageName) {
19706        final int callingUid = Binder.getCallingUid();
19707        if (getInstantAppPackageName(callingUid) != null) {
19708            return;
19709        }
19710        // writer
19711        synchronized (mPackages) {
19712            PackageParser.Package pkg = mPackages.get(packageName);
19713            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19714                if (mContext.checkCallingOrSelfPermission(
19715                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19716                        != PackageManager.PERMISSION_GRANTED) {
19717                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19718                            < Build.VERSION_CODES.FROYO) {
19719                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19720                                + callingUid);
19721                        return;
19722                    }
19723                    mContext.enforceCallingOrSelfPermission(
19724                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19725                }
19726            }
19727            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19728            if (ps != null
19729                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19730                return;
19731            }
19732            int user = UserHandle.getCallingUserId();
19733            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19734                scheduleWritePackageRestrictionsLocked(user);
19735            }
19736        }
19737    }
19738
19739    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19740    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19741        ArrayList<PreferredActivity> removed = null;
19742        boolean changed = false;
19743        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19744            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19745            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19746            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19747                continue;
19748            }
19749            Iterator<PreferredActivity> it = pir.filterIterator();
19750            while (it.hasNext()) {
19751                PreferredActivity pa = it.next();
19752                // Mark entry for removal only if it matches the package name
19753                // and the entry is of type "always".
19754                if (packageName == null ||
19755                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19756                                && pa.mPref.mAlways)) {
19757                    if (removed == null) {
19758                        removed = new ArrayList<PreferredActivity>();
19759                    }
19760                    removed.add(pa);
19761                }
19762            }
19763            if (removed != null) {
19764                for (int j=0; j<removed.size(); j++) {
19765                    PreferredActivity pa = removed.get(j);
19766                    pir.removeFilter(pa);
19767                }
19768                changed = true;
19769            }
19770        }
19771        if (changed) {
19772            postPreferredActivityChangedBroadcast(userId);
19773        }
19774        return changed;
19775    }
19776
19777    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19778    private void clearIntentFilterVerificationsLPw(int userId) {
19779        final int packageCount = mPackages.size();
19780        for (int i = 0; i < packageCount; i++) {
19781            PackageParser.Package pkg = mPackages.valueAt(i);
19782            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19783        }
19784    }
19785
19786    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19787    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19788        if (userId == UserHandle.USER_ALL) {
19789            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19790                    sUserManager.getUserIds())) {
19791                for (int oneUserId : sUserManager.getUserIds()) {
19792                    scheduleWritePackageRestrictionsLocked(oneUserId);
19793                }
19794            }
19795        } else {
19796            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19797                scheduleWritePackageRestrictionsLocked(userId);
19798            }
19799        }
19800    }
19801
19802    /** Clears state for all users, and touches intent filter verification policy */
19803    void clearDefaultBrowserIfNeeded(String packageName) {
19804        for (int oneUserId : sUserManager.getUserIds()) {
19805            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19806        }
19807    }
19808
19809    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19810        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19811        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19812            if (packageName.equals(defaultBrowserPackageName)) {
19813                setDefaultBrowserPackageName(null, userId);
19814            }
19815        }
19816    }
19817
19818    @Override
19819    public void resetApplicationPreferences(int userId) {
19820        mContext.enforceCallingOrSelfPermission(
19821                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19822        final long identity = Binder.clearCallingIdentity();
19823        // writer
19824        try {
19825            synchronized (mPackages) {
19826                clearPackagePreferredActivitiesLPw(null, userId);
19827                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19828                // TODO: We have to reset the default SMS and Phone. This requires
19829                // significant refactoring to keep all default apps in the package
19830                // manager (cleaner but more work) or have the services provide
19831                // callbacks to the package manager to request a default app reset.
19832                applyFactoryDefaultBrowserLPw(userId);
19833                clearIntentFilterVerificationsLPw(userId);
19834                primeDomainVerificationsLPw(userId);
19835                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19836                scheduleWritePackageRestrictionsLocked(userId);
19837            }
19838            resetNetworkPolicies(userId);
19839        } finally {
19840            Binder.restoreCallingIdentity(identity);
19841        }
19842    }
19843
19844    @Override
19845    public int getPreferredActivities(List<IntentFilter> outFilters,
19846            List<ComponentName> outActivities, String packageName) {
19847        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19848            return 0;
19849        }
19850        int num = 0;
19851        final int userId = UserHandle.getCallingUserId();
19852        // reader
19853        synchronized (mPackages) {
19854            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19855            if (pir != null) {
19856                final Iterator<PreferredActivity> it = pir.filterIterator();
19857                while (it.hasNext()) {
19858                    final PreferredActivity pa = it.next();
19859                    if (packageName == null
19860                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19861                                    && pa.mPref.mAlways)) {
19862                        if (outFilters != null) {
19863                            outFilters.add(new IntentFilter(pa));
19864                        }
19865                        if (outActivities != null) {
19866                            outActivities.add(pa.mPref.mComponent);
19867                        }
19868                    }
19869                }
19870            }
19871        }
19872
19873        return num;
19874    }
19875
19876    @Override
19877    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19878            int userId) {
19879        int callingUid = Binder.getCallingUid();
19880        if (callingUid != Process.SYSTEM_UID) {
19881            throw new SecurityException(
19882                    "addPersistentPreferredActivity can only be run by the system");
19883        }
19884        if (filter.countActions() == 0) {
19885            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19886            return;
19887        }
19888        synchronized (mPackages) {
19889            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19890                    ":");
19891            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19892            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19893                    new PersistentPreferredActivity(filter, activity));
19894            scheduleWritePackageRestrictionsLocked(userId);
19895            postPreferredActivityChangedBroadcast(userId);
19896        }
19897    }
19898
19899    @Override
19900    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19901        int callingUid = Binder.getCallingUid();
19902        if (callingUid != Process.SYSTEM_UID) {
19903            throw new SecurityException(
19904                    "clearPackagePersistentPreferredActivities can only be run by the system");
19905        }
19906        ArrayList<PersistentPreferredActivity> removed = null;
19907        boolean changed = false;
19908        synchronized (mPackages) {
19909            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19910                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19911                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19912                        .valueAt(i);
19913                if (userId != thisUserId) {
19914                    continue;
19915                }
19916                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19917                while (it.hasNext()) {
19918                    PersistentPreferredActivity ppa = it.next();
19919                    // Mark entry for removal only if it matches the package name.
19920                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19921                        if (removed == null) {
19922                            removed = new ArrayList<PersistentPreferredActivity>();
19923                        }
19924                        removed.add(ppa);
19925                    }
19926                }
19927                if (removed != null) {
19928                    for (int j=0; j<removed.size(); j++) {
19929                        PersistentPreferredActivity ppa = removed.get(j);
19930                        ppir.removeFilter(ppa);
19931                    }
19932                    changed = true;
19933                }
19934            }
19935
19936            if (changed) {
19937                scheduleWritePackageRestrictionsLocked(userId);
19938                postPreferredActivityChangedBroadcast(userId);
19939            }
19940        }
19941    }
19942
19943    /**
19944     * Common machinery for picking apart a restored XML blob and passing
19945     * it to a caller-supplied functor to be applied to the running system.
19946     */
19947    private void restoreFromXml(XmlPullParser parser, int userId,
19948            String expectedStartTag, BlobXmlRestorer functor)
19949            throws IOException, XmlPullParserException {
19950        int type;
19951        while ((type = parser.next()) != XmlPullParser.START_TAG
19952                && type != XmlPullParser.END_DOCUMENT) {
19953        }
19954        if (type != XmlPullParser.START_TAG) {
19955            // oops didn't find a start tag?!
19956            if (DEBUG_BACKUP) {
19957                Slog.e(TAG, "Didn't find start tag during restore");
19958            }
19959            return;
19960        }
19961Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19962        // this is supposed to be TAG_PREFERRED_BACKUP
19963        if (!expectedStartTag.equals(parser.getName())) {
19964            if (DEBUG_BACKUP) {
19965                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19966            }
19967            return;
19968        }
19969
19970        // skip interfering stuff, then we're aligned with the backing implementation
19971        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19972Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19973        functor.apply(parser, userId);
19974    }
19975
19976    private interface BlobXmlRestorer {
19977        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19978    }
19979
19980    /**
19981     * Non-Binder method, support for the backup/restore mechanism: write the
19982     * full set of preferred activities in its canonical XML format.  Returns the
19983     * XML output as a byte array, or null if there is none.
19984     */
19985    @Override
19986    public byte[] getPreferredActivityBackup(int userId) {
19987        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19988            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19989        }
19990
19991        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19992        try {
19993            final XmlSerializer serializer = new FastXmlSerializer();
19994            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19995            serializer.startDocument(null, true);
19996            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19997
19998            synchronized (mPackages) {
19999                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20000            }
20001
20002            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20003            serializer.endDocument();
20004            serializer.flush();
20005        } catch (Exception e) {
20006            if (DEBUG_BACKUP) {
20007                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20008            }
20009            return null;
20010        }
20011
20012        return dataStream.toByteArray();
20013    }
20014
20015    @Override
20016    public void restorePreferredActivities(byte[] backup, int userId) {
20017        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20018            throw new SecurityException("Only the system may call restorePreferredActivities()");
20019        }
20020
20021        try {
20022            final XmlPullParser parser = Xml.newPullParser();
20023            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20024            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20025                    new BlobXmlRestorer() {
20026                        @Override
20027                        public void apply(XmlPullParser parser, int userId)
20028                                throws XmlPullParserException, IOException {
20029                            synchronized (mPackages) {
20030                                mSettings.readPreferredActivitiesLPw(parser, userId);
20031                            }
20032                        }
20033                    } );
20034        } catch (Exception e) {
20035            if (DEBUG_BACKUP) {
20036                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20037            }
20038        }
20039    }
20040
20041    /**
20042     * Non-Binder method, support for the backup/restore mechanism: write the
20043     * default browser (etc) settings in its canonical XML format.  Returns the default
20044     * browser XML representation as a byte array, or null if there is none.
20045     */
20046    @Override
20047    public byte[] getDefaultAppsBackup(int userId) {
20048        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20049            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20050        }
20051
20052        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20053        try {
20054            final XmlSerializer serializer = new FastXmlSerializer();
20055            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20056            serializer.startDocument(null, true);
20057            serializer.startTag(null, TAG_DEFAULT_APPS);
20058
20059            synchronized (mPackages) {
20060                mSettings.writeDefaultAppsLPr(serializer, userId);
20061            }
20062
20063            serializer.endTag(null, TAG_DEFAULT_APPS);
20064            serializer.endDocument();
20065            serializer.flush();
20066        } catch (Exception e) {
20067            if (DEBUG_BACKUP) {
20068                Slog.e(TAG, "Unable to write default apps for backup", e);
20069            }
20070            return null;
20071        }
20072
20073        return dataStream.toByteArray();
20074    }
20075
20076    @Override
20077    public void restoreDefaultApps(byte[] backup, int userId) {
20078        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20079            throw new SecurityException("Only the system may call restoreDefaultApps()");
20080        }
20081
20082        try {
20083            final XmlPullParser parser = Xml.newPullParser();
20084            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20085            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20086                    new BlobXmlRestorer() {
20087                        @Override
20088                        public void apply(XmlPullParser parser, int userId)
20089                                throws XmlPullParserException, IOException {
20090                            synchronized (mPackages) {
20091                                mSettings.readDefaultAppsLPw(parser, userId);
20092                            }
20093                        }
20094                    } );
20095        } catch (Exception e) {
20096            if (DEBUG_BACKUP) {
20097                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20098            }
20099        }
20100    }
20101
20102    @Override
20103    public byte[] getIntentFilterVerificationBackup(int userId) {
20104        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20105            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20106        }
20107
20108        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20109        try {
20110            final XmlSerializer serializer = new FastXmlSerializer();
20111            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20112            serializer.startDocument(null, true);
20113            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20114
20115            synchronized (mPackages) {
20116                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20117            }
20118
20119            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20120            serializer.endDocument();
20121            serializer.flush();
20122        } catch (Exception e) {
20123            if (DEBUG_BACKUP) {
20124                Slog.e(TAG, "Unable to write default apps for backup", e);
20125            }
20126            return null;
20127        }
20128
20129        return dataStream.toByteArray();
20130    }
20131
20132    @Override
20133    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20134        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20135            throw new SecurityException("Only the system may call restorePreferredActivities()");
20136        }
20137
20138        try {
20139            final XmlPullParser parser = Xml.newPullParser();
20140            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20141            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20142                    new BlobXmlRestorer() {
20143                        @Override
20144                        public void apply(XmlPullParser parser, int userId)
20145                                throws XmlPullParserException, IOException {
20146                            synchronized (mPackages) {
20147                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20148                                mSettings.writeLPr();
20149                            }
20150                        }
20151                    } );
20152        } catch (Exception e) {
20153            if (DEBUG_BACKUP) {
20154                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20155            }
20156        }
20157    }
20158
20159    @Override
20160    public byte[] getPermissionGrantBackup(int userId) {
20161        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20162            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20163        }
20164
20165        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20166        try {
20167            final XmlSerializer serializer = new FastXmlSerializer();
20168            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20169            serializer.startDocument(null, true);
20170            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20171
20172            synchronized (mPackages) {
20173                serializeRuntimePermissionGrantsLPr(serializer, userId);
20174            }
20175
20176            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20177            serializer.endDocument();
20178            serializer.flush();
20179        } catch (Exception e) {
20180            if (DEBUG_BACKUP) {
20181                Slog.e(TAG, "Unable to write default apps for backup", e);
20182            }
20183            return null;
20184        }
20185
20186        return dataStream.toByteArray();
20187    }
20188
20189    @Override
20190    public void restorePermissionGrants(byte[] backup, int userId) {
20191        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20192            throw new SecurityException("Only the system may call restorePermissionGrants()");
20193        }
20194
20195        try {
20196            final XmlPullParser parser = Xml.newPullParser();
20197            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20198            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20199                    new BlobXmlRestorer() {
20200                        @Override
20201                        public void apply(XmlPullParser parser, int userId)
20202                                throws XmlPullParserException, IOException {
20203                            synchronized (mPackages) {
20204                                processRestoredPermissionGrantsLPr(parser, userId);
20205                            }
20206                        }
20207                    } );
20208        } catch (Exception e) {
20209            if (DEBUG_BACKUP) {
20210                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20211            }
20212        }
20213    }
20214
20215    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20216            throws IOException {
20217        serializer.startTag(null, TAG_ALL_GRANTS);
20218
20219        final int N = mSettings.mPackages.size();
20220        for (int i = 0; i < N; i++) {
20221            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20222            boolean pkgGrantsKnown = false;
20223
20224            PermissionsState packagePerms = ps.getPermissionsState();
20225
20226            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20227                final int grantFlags = state.getFlags();
20228                // only look at grants that are not system/policy fixed
20229                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20230                    final boolean isGranted = state.isGranted();
20231                    // And only back up the user-twiddled state bits
20232                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20233                        final String packageName = mSettings.mPackages.keyAt(i);
20234                        if (!pkgGrantsKnown) {
20235                            serializer.startTag(null, TAG_GRANT);
20236                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20237                            pkgGrantsKnown = true;
20238                        }
20239
20240                        final boolean userSet =
20241                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20242                        final boolean userFixed =
20243                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20244                        final boolean revoke =
20245                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20246
20247                        serializer.startTag(null, TAG_PERMISSION);
20248                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20249                        if (isGranted) {
20250                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20251                        }
20252                        if (userSet) {
20253                            serializer.attribute(null, ATTR_USER_SET, "true");
20254                        }
20255                        if (userFixed) {
20256                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20257                        }
20258                        if (revoke) {
20259                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20260                        }
20261                        serializer.endTag(null, TAG_PERMISSION);
20262                    }
20263                }
20264            }
20265
20266            if (pkgGrantsKnown) {
20267                serializer.endTag(null, TAG_GRANT);
20268            }
20269        }
20270
20271        serializer.endTag(null, TAG_ALL_GRANTS);
20272    }
20273
20274    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20275            throws XmlPullParserException, IOException {
20276        String pkgName = null;
20277        int outerDepth = parser.getDepth();
20278        int type;
20279        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20280                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20281            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20282                continue;
20283            }
20284
20285            final String tagName = parser.getName();
20286            if (tagName.equals(TAG_GRANT)) {
20287                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20288                if (DEBUG_BACKUP) {
20289                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20290                }
20291            } else if (tagName.equals(TAG_PERMISSION)) {
20292
20293                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20294                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20295
20296                int newFlagSet = 0;
20297                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20298                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20299                }
20300                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20301                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20302                }
20303                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20304                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20305                }
20306                if (DEBUG_BACKUP) {
20307                    Slog.v(TAG, "  + Restoring grant:"
20308                            + " pkg=" + pkgName
20309                            + " perm=" + permName
20310                            + " granted=" + isGranted
20311                            + " bits=0x" + Integer.toHexString(newFlagSet));
20312                }
20313                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20314                if (ps != null) {
20315                    // Already installed so we apply the grant immediately
20316                    if (DEBUG_BACKUP) {
20317                        Slog.v(TAG, "        + already installed; applying");
20318                    }
20319                    PermissionsState perms = ps.getPermissionsState();
20320                    BasePermission bp =
20321                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20322                    if (bp != null) {
20323                        if (isGranted) {
20324                            perms.grantRuntimePermission(bp, userId);
20325                        }
20326                        if (newFlagSet != 0) {
20327                            perms.updatePermissionFlags(
20328                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20329                        }
20330                    }
20331                } else {
20332                    // Need to wait for post-restore install to apply the grant
20333                    if (DEBUG_BACKUP) {
20334                        Slog.v(TAG, "        - not yet installed; saving for later");
20335                    }
20336                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20337                            isGranted, newFlagSet, userId);
20338                }
20339            } else {
20340                PackageManagerService.reportSettingsProblem(Log.WARN,
20341                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20342                XmlUtils.skipCurrentTag(parser);
20343            }
20344        }
20345
20346        scheduleWriteSettingsLocked();
20347        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20348    }
20349
20350    @Override
20351    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20352            int sourceUserId, int targetUserId, int flags) {
20353        mContext.enforceCallingOrSelfPermission(
20354                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20355        int callingUid = Binder.getCallingUid();
20356        enforceOwnerRights(ownerPackage, callingUid);
20357        PackageManagerServiceUtils.enforceShellRestriction(
20358                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20359        if (intentFilter.countActions() == 0) {
20360            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20361            return;
20362        }
20363        synchronized (mPackages) {
20364            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20365                    ownerPackage, targetUserId, flags);
20366            CrossProfileIntentResolver resolver =
20367                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20368            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20369            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20370            if (existing != null) {
20371                int size = existing.size();
20372                for (int i = 0; i < size; i++) {
20373                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20374                        return;
20375                    }
20376                }
20377            }
20378            resolver.addFilter(newFilter);
20379            scheduleWritePackageRestrictionsLocked(sourceUserId);
20380        }
20381    }
20382
20383    @Override
20384    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20385        mContext.enforceCallingOrSelfPermission(
20386                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20387        final int callingUid = Binder.getCallingUid();
20388        enforceOwnerRights(ownerPackage, callingUid);
20389        PackageManagerServiceUtils.enforceShellRestriction(
20390                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20391        synchronized (mPackages) {
20392            CrossProfileIntentResolver resolver =
20393                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20394            ArraySet<CrossProfileIntentFilter> set =
20395                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20396            for (CrossProfileIntentFilter filter : set) {
20397                if (filter.getOwnerPackage().equals(ownerPackage)) {
20398                    resolver.removeFilter(filter);
20399                }
20400            }
20401            scheduleWritePackageRestrictionsLocked(sourceUserId);
20402        }
20403    }
20404
20405    // Enforcing that callingUid is owning pkg on userId
20406    private void enforceOwnerRights(String pkg, int callingUid) {
20407        // The system owns everything.
20408        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20409            return;
20410        }
20411        final int callingUserId = UserHandle.getUserId(callingUid);
20412        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20413        if (pi == null) {
20414            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20415                    + callingUserId);
20416        }
20417        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20418            throw new SecurityException("Calling uid " + callingUid
20419                    + " does not own package " + pkg);
20420        }
20421    }
20422
20423    @Override
20424    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20425        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20426            return null;
20427        }
20428        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20429    }
20430
20431    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20432        UserManagerService ums = UserManagerService.getInstance();
20433        if (ums != null) {
20434            final UserInfo parent = ums.getProfileParent(userId);
20435            final int launcherUid = (parent != null) ? parent.id : userId;
20436            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20437            if (launcherComponent != null) {
20438                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20439                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20440                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20441                        .setPackage(launcherComponent.getPackageName());
20442                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20443            }
20444        }
20445    }
20446
20447    /**
20448     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20449     * then reports the most likely home activity or null if there are more than one.
20450     */
20451    private ComponentName getDefaultHomeActivity(int userId) {
20452        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20453        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20454        if (cn != null) {
20455            return cn;
20456        }
20457
20458        // Find the launcher with the highest priority and return that component if there are no
20459        // other home activity with the same priority.
20460        int lastPriority = Integer.MIN_VALUE;
20461        ComponentName lastComponent = null;
20462        final int size = allHomeCandidates.size();
20463        for (int i = 0; i < size; i++) {
20464            final ResolveInfo ri = allHomeCandidates.get(i);
20465            if (ri.priority > lastPriority) {
20466                lastComponent = ri.activityInfo.getComponentName();
20467                lastPriority = ri.priority;
20468            } else if (ri.priority == lastPriority) {
20469                // Two components found with same priority.
20470                lastComponent = null;
20471            }
20472        }
20473        return lastComponent;
20474    }
20475
20476    private Intent getHomeIntent() {
20477        Intent intent = new Intent(Intent.ACTION_MAIN);
20478        intent.addCategory(Intent.CATEGORY_HOME);
20479        intent.addCategory(Intent.CATEGORY_DEFAULT);
20480        return intent;
20481    }
20482
20483    private IntentFilter getHomeFilter() {
20484        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20485        filter.addCategory(Intent.CATEGORY_HOME);
20486        filter.addCategory(Intent.CATEGORY_DEFAULT);
20487        return filter;
20488    }
20489
20490    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20491            int userId) {
20492        Intent intent  = getHomeIntent();
20493        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20494                PackageManager.GET_META_DATA, userId);
20495        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20496                true, false, false, userId);
20497
20498        allHomeCandidates.clear();
20499        if (list != null) {
20500            for (ResolveInfo ri : list) {
20501                allHomeCandidates.add(ri);
20502            }
20503        }
20504        return (preferred == null || preferred.activityInfo == null)
20505                ? null
20506                : new ComponentName(preferred.activityInfo.packageName,
20507                        preferred.activityInfo.name);
20508    }
20509
20510    @Override
20511    public void setHomeActivity(ComponentName comp, int userId) {
20512        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20513            return;
20514        }
20515        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20516        getHomeActivitiesAsUser(homeActivities, userId);
20517
20518        boolean found = false;
20519
20520        final int size = homeActivities.size();
20521        final ComponentName[] set = new ComponentName[size];
20522        for (int i = 0; i < size; i++) {
20523            final ResolveInfo candidate = homeActivities.get(i);
20524            final ActivityInfo info = candidate.activityInfo;
20525            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20526            set[i] = activityName;
20527            if (!found && activityName.equals(comp)) {
20528                found = true;
20529            }
20530        }
20531        if (!found) {
20532            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20533                    + userId);
20534        }
20535        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20536                set, comp, userId);
20537    }
20538
20539    private @Nullable String getSetupWizardPackageName() {
20540        final Intent intent = new Intent(Intent.ACTION_MAIN);
20541        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20542
20543        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20544                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20545                        | MATCH_DISABLED_COMPONENTS,
20546                UserHandle.myUserId());
20547        if (matches.size() == 1) {
20548            return matches.get(0).getComponentInfo().packageName;
20549        } else {
20550            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20551                    + ": matches=" + matches);
20552            return null;
20553        }
20554    }
20555
20556    private @Nullable String getStorageManagerPackageName() {
20557        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20558
20559        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20560                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20561                        | MATCH_DISABLED_COMPONENTS,
20562                UserHandle.myUserId());
20563        if (matches.size() == 1) {
20564            return matches.get(0).getComponentInfo().packageName;
20565        } else {
20566            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20567                    + matches.size() + ": matches=" + matches);
20568            return null;
20569        }
20570    }
20571
20572    @Override
20573    public String getSystemTextClassifierPackageName() {
20574        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20575    }
20576
20577    @Override
20578    public void setApplicationEnabledSetting(String appPackageName,
20579            int newState, int flags, int userId, String callingPackage) {
20580        if (!sUserManager.exists(userId)) return;
20581        if (callingPackage == null) {
20582            callingPackage = Integer.toString(Binder.getCallingUid());
20583        }
20584        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20585    }
20586
20587    @Override
20588    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20589        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20590        synchronized (mPackages) {
20591            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20592            if (pkgSetting != null) {
20593                pkgSetting.setUpdateAvailable(updateAvailable);
20594            }
20595        }
20596    }
20597
20598    @Override
20599    public void setComponentEnabledSetting(ComponentName componentName,
20600            int newState, int flags, int userId) {
20601        if (!sUserManager.exists(userId)) return;
20602        setEnabledSetting(componentName.getPackageName(),
20603                componentName.getClassName(), newState, flags, userId, null);
20604    }
20605
20606    private void setEnabledSetting(final String packageName, String className, int newState,
20607            final int flags, int userId, String callingPackage) {
20608        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20609              || newState == COMPONENT_ENABLED_STATE_ENABLED
20610              || newState == COMPONENT_ENABLED_STATE_DISABLED
20611              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20612              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20613            throw new IllegalArgumentException("Invalid new component state: "
20614                    + newState);
20615        }
20616        PackageSetting pkgSetting;
20617        final int callingUid = Binder.getCallingUid();
20618        final int permission;
20619        if (callingUid == Process.SYSTEM_UID) {
20620            permission = PackageManager.PERMISSION_GRANTED;
20621        } else {
20622            permission = mContext.checkCallingOrSelfPermission(
20623                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20624        }
20625        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20626                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20627        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20628        boolean sendNow = false;
20629        boolean isApp = (className == null);
20630        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20631        String componentName = isApp ? packageName : className;
20632        int packageUid = -1;
20633        ArrayList<String> components;
20634
20635        // reader
20636        synchronized (mPackages) {
20637            pkgSetting = mSettings.mPackages.get(packageName);
20638            if (pkgSetting == null) {
20639                if (!isCallerInstantApp) {
20640                    if (className == null) {
20641                        throw new IllegalArgumentException("Unknown package: " + packageName);
20642                    }
20643                    throw new IllegalArgumentException(
20644                            "Unknown component: " + packageName + "/" + className);
20645                } else {
20646                    // throw SecurityException to prevent leaking package information
20647                    throw new SecurityException(
20648                            "Attempt to change component state; "
20649                            + "pid=" + Binder.getCallingPid()
20650                            + ", uid=" + callingUid
20651                            + (className == null
20652                                    ? ", package=" + packageName
20653                                    : ", component=" + packageName + "/" + className));
20654                }
20655            }
20656        }
20657
20658        // Limit who can change which apps
20659        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20660            // Don't allow apps that don't have permission to modify other apps
20661            if (!allowedByPermission
20662                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20663                throw new SecurityException(
20664                        "Attempt to change component state; "
20665                        + "pid=" + Binder.getCallingPid()
20666                        + ", uid=" + callingUid
20667                        + (className == null
20668                                ? ", package=" + packageName
20669                                : ", component=" + packageName + "/" + className));
20670            }
20671            // Don't allow changing protected packages.
20672            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20673                throw new SecurityException("Cannot disable a protected package: " + packageName);
20674            }
20675        }
20676
20677        synchronized (mPackages) {
20678            if (callingUid == Process.SHELL_UID
20679                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20680                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20681                // unless it is a test package.
20682                int oldState = pkgSetting.getEnabled(userId);
20683                if (className == null
20684                        &&
20685                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20686                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20687                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20688                        &&
20689                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20690                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20691                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20692                    // ok
20693                } else {
20694                    throw new SecurityException(
20695                            "Shell cannot change component state for " + packageName + "/"
20696                                    + className + " to " + newState);
20697                }
20698            }
20699        }
20700        if (className == null) {
20701            // We're dealing with an application/package level state change
20702            synchronized (mPackages) {
20703                if (pkgSetting.getEnabled(userId) == newState) {
20704                    // Nothing to do
20705                    return;
20706                }
20707            }
20708            // If we're enabling a system stub, there's a little more work to do.
20709            // Prior to enabling the package, we need to decompress the APK(s) to the
20710            // data partition and then replace the version on the system partition.
20711            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20712            final boolean isSystemStub = deletedPkg.isStub
20713                    && deletedPkg.isSystem();
20714            if (isSystemStub
20715                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20716                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20717                final File codePath = decompressPackage(deletedPkg);
20718                if (codePath == null) {
20719                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20720                    return;
20721                }
20722                // TODO remove direct parsing of the package object during internal cleanup
20723                // of scan package
20724                // We need to call parse directly here for no other reason than we need
20725                // the new package in order to disable the old one [we use the information
20726                // for some internal optimization to optionally create a new package setting
20727                // object on replace]. However, we can't get the package from the scan
20728                // because the scan modifies live structures and we need to remove the
20729                // old [system] package from the system before a scan can be attempted.
20730                // Once scan is indempotent we can remove this parse and use the package
20731                // object we scanned, prior to adding it to package settings.
20732                final PackageParser pp = new PackageParser();
20733                pp.setSeparateProcesses(mSeparateProcesses);
20734                pp.setDisplayMetrics(mMetrics);
20735                pp.setCallback(mPackageParserCallback);
20736                final PackageParser.Package tmpPkg;
20737                try {
20738                    final @ParseFlags int parseFlags = mDefParseFlags
20739                            | PackageParser.PARSE_MUST_BE_APK
20740                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20741                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20742                } catch (PackageParserException e) {
20743                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20744                    return;
20745                }
20746                synchronized (mInstallLock) {
20747                    // Disable the stub and remove any package entries
20748                    removePackageLI(deletedPkg, true);
20749                    synchronized (mPackages) {
20750                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20751                    }
20752                    final PackageParser.Package pkg;
20753                    try (PackageFreezer freezer =
20754                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20755                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20756                                | PackageParser.PARSE_ENFORCE_CODE;
20757                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20758                                0 /*currentTime*/, null /*user*/);
20759                        prepareAppDataAfterInstallLIF(pkg);
20760                        synchronized (mPackages) {
20761                            try {
20762                                updateSharedLibrariesLPr(pkg, null);
20763                            } catch (PackageManagerException e) {
20764                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20765                            }
20766                            mPermissionManager.updatePermissions(
20767                                    pkg.packageName, pkg, true, mPackages.values(),
20768                                    mPermissionCallback);
20769                            mSettings.writeLPr();
20770                        }
20771                    } catch (PackageManagerException e) {
20772                        // Whoops! Something went wrong; try to roll back to the stub
20773                        Slog.w(TAG, "Failed to install compressed system package:"
20774                                + pkgSetting.name, e);
20775                        // Remove the failed install
20776                        removeCodePathLI(codePath);
20777
20778                        // Install the system package
20779                        try (PackageFreezer freezer =
20780                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20781                            synchronized (mPackages) {
20782                                // NOTE: The system package always needs to be enabled; even
20783                                // if it's for a compressed stub. If we don't, installing the
20784                                // system package fails during scan [scanning checks the disabled
20785                                // packages]. We will reverse this later, after we've "installed"
20786                                // the stub.
20787                                // This leaves us in a fragile state; the stub should never be
20788                                // enabled, so, cross your fingers and hope nothing goes wrong
20789                                // until we can disable the package later.
20790                                enableSystemPackageLPw(deletedPkg);
20791                            }
20792                            installPackageFromSystemLIF(deletedPkg.codePath,
20793                                    false /*isPrivileged*/, null /*allUserHandles*/,
20794                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20795                                    true /*writeSettings*/);
20796                        } catch (PackageManagerException pme) {
20797                            Slog.w(TAG, "Failed to restore system package:"
20798                                    + deletedPkg.packageName, pme);
20799                        } finally {
20800                            synchronized (mPackages) {
20801                                mSettings.disableSystemPackageLPw(
20802                                        deletedPkg.packageName, true /*replaced*/);
20803                                mSettings.writeLPr();
20804                            }
20805                        }
20806                        return;
20807                    }
20808                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20809                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20810                    mDexManager.notifyPackageUpdated(pkg.packageName,
20811                            pkg.baseCodePath, pkg.splitCodePaths);
20812                }
20813            }
20814            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20815                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20816                // Don't care about who enables an app.
20817                callingPackage = null;
20818            }
20819            synchronized (mPackages) {
20820                pkgSetting.setEnabled(newState, userId, callingPackage);
20821            }
20822        } else {
20823            synchronized (mPackages) {
20824                // We're dealing with a component level state change
20825                // First, verify that this is a valid class name.
20826                PackageParser.Package pkg = pkgSetting.pkg;
20827                if (pkg == null || !pkg.hasComponentClassName(className)) {
20828                    if (pkg != null &&
20829                            pkg.applicationInfo.targetSdkVersion >=
20830                                    Build.VERSION_CODES.JELLY_BEAN) {
20831                        throw new IllegalArgumentException("Component class " + className
20832                                + " does not exist in " + packageName);
20833                    } else {
20834                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20835                                + className + " does not exist in " + packageName);
20836                    }
20837                }
20838                switch (newState) {
20839                    case COMPONENT_ENABLED_STATE_ENABLED:
20840                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20841                            return;
20842                        }
20843                        break;
20844                    case COMPONENT_ENABLED_STATE_DISABLED:
20845                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20846                            return;
20847                        }
20848                        break;
20849                    case COMPONENT_ENABLED_STATE_DEFAULT:
20850                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20851                            return;
20852                        }
20853                        break;
20854                    default:
20855                        Slog.e(TAG, "Invalid new component state: " + newState);
20856                        return;
20857                }
20858            }
20859        }
20860        synchronized (mPackages) {
20861            scheduleWritePackageRestrictionsLocked(userId);
20862            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20863            final long callingId = Binder.clearCallingIdentity();
20864            try {
20865                updateInstantAppInstallerLocked(packageName);
20866            } finally {
20867                Binder.restoreCallingIdentity(callingId);
20868            }
20869            components = mPendingBroadcasts.get(userId, packageName);
20870            final boolean newPackage = components == null;
20871            if (newPackage) {
20872                components = new ArrayList<String>();
20873            }
20874            if (!components.contains(componentName)) {
20875                components.add(componentName);
20876            }
20877            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20878                sendNow = true;
20879                // Purge entry from pending broadcast list if another one exists already
20880                // since we are sending one right away.
20881                mPendingBroadcasts.remove(userId, packageName);
20882            } else {
20883                if (newPackage) {
20884                    mPendingBroadcasts.put(userId, packageName, components);
20885                }
20886                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20887                    // Schedule a message
20888                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20889                }
20890            }
20891        }
20892
20893        long callingId = Binder.clearCallingIdentity();
20894        try {
20895            if (sendNow) {
20896                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20897                sendPackageChangedBroadcast(packageName,
20898                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20899            }
20900        } finally {
20901            Binder.restoreCallingIdentity(callingId);
20902        }
20903    }
20904
20905    @Override
20906    public void flushPackageRestrictionsAsUser(int userId) {
20907        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20908            return;
20909        }
20910        if (!sUserManager.exists(userId)) {
20911            return;
20912        }
20913        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20914                false /* checkShell */, "flushPackageRestrictions");
20915        synchronized (mPackages) {
20916            mSettings.writePackageRestrictionsLPr(userId);
20917            mDirtyUsers.remove(userId);
20918            if (mDirtyUsers.isEmpty()) {
20919                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20920            }
20921        }
20922    }
20923
20924    private void sendPackageChangedBroadcast(String packageName,
20925            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20926        if (DEBUG_INSTALL)
20927            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20928                    + componentNames);
20929        Bundle extras = new Bundle(4);
20930        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20931        String nameList[] = new String[componentNames.size()];
20932        componentNames.toArray(nameList);
20933        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20934        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20935        extras.putInt(Intent.EXTRA_UID, packageUid);
20936        // If this is not reporting a change of the overall package, then only send it
20937        // to registered receivers.  We don't want to launch a swath of apps for every
20938        // little component state change.
20939        final int flags = !componentNames.contains(packageName)
20940                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20941        final int userId = UserHandle.getUserId(packageUid);
20942        final boolean isInstantApp = isInstantApp(packageName, userId);
20943        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20944        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20945        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20946                userIds, instantUserIds);
20947    }
20948
20949    @Override
20950    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20951        if (!sUserManager.exists(userId)) return;
20952        final int callingUid = Binder.getCallingUid();
20953        if (getInstantAppPackageName(callingUid) != null) {
20954            return;
20955        }
20956        final int permission = mContext.checkCallingOrSelfPermission(
20957                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20958        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20959        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20960                true /* requireFullPermission */, true /* checkShell */, "stop package");
20961        // writer
20962        synchronized (mPackages) {
20963            final PackageSetting ps = mSettings.mPackages.get(packageName);
20964            if (!filterAppAccessLPr(ps, callingUid, userId)
20965                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20966                            allowedByPermission, callingUid, userId)) {
20967                scheduleWritePackageRestrictionsLocked(userId);
20968            }
20969        }
20970    }
20971
20972    @Override
20973    public String getInstallerPackageName(String packageName) {
20974        final int callingUid = Binder.getCallingUid();
20975        synchronized (mPackages) {
20976            final PackageSetting ps = mSettings.mPackages.get(packageName);
20977            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20978                return null;
20979            }
20980            return mSettings.getInstallerPackageNameLPr(packageName);
20981        }
20982    }
20983
20984    public boolean isOrphaned(String packageName) {
20985        // reader
20986        synchronized (mPackages) {
20987            return mSettings.isOrphaned(packageName);
20988        }
20989    }
20990
20991    @Override
20992    public int getApplicationEnabledSetting(String packageName, int userId) {
20993        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20994        int callingUid = Binder.getCallingUid();
20995        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20996                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20997        // reader
20998        synchronized (mPackages) {
20999            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21000                return COMPONENT_ENABLED_STATE_DISABLED;
21001            }
21002            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21003        }
21004    }
21005
21006    @Override
21007    public int getComponentEnabledSetting(ComponentName component, int userId) {
21008        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21009        int callingUid = Binder.getCallingUid();
21010        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21011                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21012        synchronized (mPackages) {
21013            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21014                    component, TYPE_UNKNOWN, userId)) {
21015                return COMPONENT_ENABLED_STATE_DISABLED;
21016            }
21017            return mSettings.getComponentEnabledSettingLPr(component, userId);
21018        }
21019    }
21020
21021    @Override
21022    public void enterSafeMode() {
21023        enforceSystemOrRoot("Only the system can request entering safe mode");
21024
21025        if (!mSystemReady) {
21026            mSafeMode = true;
21027        }
21028    }
21029
21030    @Override
21031    public void systemReady() {
21032        enforceSystemOrRoot("Only the system can claim the system is ready");
21033
21034        mSystemReady = true;
21035        final ContentResolver resolver = mContext.getContentResolver();
21036        ContentObserver co = new ContentObserver(mHandler) {
21037            @Override
21038            public void onChange(boolean selfChange) {
21039                mWebInstantAppsDisabled =
21040                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21041                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21042            }
21043        };
21044        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21045                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21046                false, co, UserHandle.USER_SYSTEM);
21047        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
21048                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21049        co.onChange(true);
21050
21051        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21052        // disabled after already being started.
21053        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21054                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21055
21056        // Read the compatibilty setting when the system is ready.
21057        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21058                mContext.getContentResolver(),
21059                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21060        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21061        if (DEBUG_SETTINGS) {
21062            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21063        }
21064
21065        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21066
21067        synchronized (mPackages) {
21068            // Verify that all of the preferred activity components actually
21069            // exist.  It is possible for applications to be updated and at
21070            // that point remove a previously declared activity component that
21071            // had been set as a preferred activity.  We try to clean this up
21072            // the next time we encounter that preferred activity, but it is
21073            // possible for the user flow to never be able to return to that
21074            // situation so here we do a sanity check to make sure we haven't
21075            // left any junk around.
21076            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21077            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21078                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21079                removed.clear();
21080                for (PreferredActivity pa : pir.filterSet()) {
21081                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21082                        removed.add(pa);
21083                    }
21084                }
21085                if (removed.size() > 0) {
21086                    for (int r=0; r<removed.size(); r++) {
21087                        PreferredActivity pa = removed.get(r);
21088                        Slog.w(TAG, "Removing dangling preferred activity: "
21089                                + pa.mPref.mComponent);
21090                        pir.removeFilter(pa);
21091                    }
21092                    mSettings.writePackageRestrictionsLPr(
21093                            mSettings.mPreferredActivities.keyAt(i));
21094                }
21095            }
21096
21097            for (int userId : UserManagerService.getInstance().getUserIds()) {
21098                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21099                    grantPermissionsUserIds = ArrayUtils.appendInt(
21100                            grantPermissionsUserIds, userId);
21101                }
21102            }
21103        }
21104        sUserManager.systemReady();
21105        // If we upgraded grant all default permissions before kicking off.
21106        for (int userId : grantPermissionsUserIds) {
21107            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21108        }
21109
21110        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21111            // If we did not grant default permissions, we preload from this the
21112            // default permission exceptions lazily to ensure we don't hit the
21113            // disk on a new user creation.
21114            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21115        }
21116
21117        // Now that we've scanned all packages, and granted any default
21118        // permissions, ensure permissions are updated. Beware of dragons if you
21119        // try optimizing this.
21120        synchronized (mPackages) {
21121            mPermissionManager.updateAllPermissions(
21122                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21123                    mPermissionCallback);
21124        }
21125
21126        // Kick off any messages waiting for system ready
21127        if (mPostSystemReadyMessages != null) {
21128            for (Message msg : mPostSystemReadyMessages) {
21129                msg.sendToTarget();
21130            }
21131            mPostSystemReadyMessages = null;
21132        }
21133
21134        // Watch for external volumes that come and go over time
21135        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21136        storage.registerListener(mStorageListener);
21137
21138        mInstallerService.systemReady();
21139        mDexManager.systemReady();
21140        mPackageDexOptimizer.systemReady();
21141
21142        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21143                StorageManagerInternal.class);
21144        StorageManagerInternal.addExternalStoragePolicy(
21145                new StorageManagerInternal.ExternalStorageMountPolicy() {
21146            @Override
21147            public int getMountMode(int uid, String packageName) {
21148                if (Process.isIsolated(uid)) {
21149                    return Zygote.MOUNT_EXTERNAL_NONE;
21150                }
21151                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21152                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21153                }
21154                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21155                    return Zygote.MOUNT_EXTERNAL_READ;
21156                }
21157                return Zygote.MOUNT_EXTERNAL_WRITE;
21158            }
21159
21160            @Override
21161            public boolean hasExternalStorage(int uid, String packageName) {
21162                return true;
21163            }
21164        });
21165
21166        // Now that we're mostly running, clean up stale users and apps
21167        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21168        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21169
21170        mPermissionManager.systemReady();
21171
21172        if (mInstantAppResolverConnection != null) {
21173            mContext.registerReceiver(new BroadcastReceiver() {
21174                @Override
21175                public void onReceive(Context context, Intent intent) {
21176                    mInstantAppResolverConnection.optimisticBind();
21177                    mContext.unregisterReceiver(this);
21178                }
21179            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21180        }
21181    }
21182
21183    public void waitForAppDataPrepared() {
21184        if (mPrepareAppDataFuture == null) {
21185            return;
21186        }
21187        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21188        mPrepareAppDataFuture = null;
21189    }
21190
21191    @Override
21192    public boolean isSafeMode() {
21193        // allow instant applications
21194        return mSafeMode;
21195    }
21196
21197    @Override
21198    public boolean hasSystemUidErrors() {
21199        // allow instant applications
21200        return mHasSystemUidErrors;
21201    }
21202
21203    static String arrayToString(int[] array) {
21204        StringBuffer buf = new StringBuffer(128);
21205        buf.append('[');
21206        if (array != null) {
21207            for (int i=0; i<array.length; i++) {
21208                if (i > 0) buf.append(", ");
21209                buf.append(array[i]);
21210            }
21211        }
21212        buf.append(']');
21213        return buf.toString();
21214    }
21215
21216    @Override
21217    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21218            FileDescriptor err, String[] args, ShellCallback callback,
21219            ResultReceiver resultReceiver) {
21220        (new PackageManagerShellCommand(this)).exec(
21221                this, in, out, err, args, callback, resultReceiver);
21222    }
21223
21224    @Override
21225    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21226        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21227
21228        DumpState dumpState = new DumpState();
21229        boolean fullPreferred = false;
21230        boolean checkin = false;
21231
21232        String packageName = null;
21233        ArraySet<String> permissionNames = null;
21234
21235        int opti = 0;
21236        while (opti < args.length) {
21237            String opt = args[opti];
21238            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21239                break;
21240            }
21241            opti++;
21242
21243            if ("-a".equals(opt)) {
21244                // Right now we only know how to print all.
21245            } else if ("-h".equals(opt)) {
21246                pw.println("Package manager dump options:");
21247                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21248                pw.println("    --checkin: dump for a checkin");
21249                pw.println("    -f: print details of intent filters");
21250                pw.println("    -h: print this help");
21251                pw.println("  cmd may be one of:");
21252                pw.println("    l[ibraries]: list known shared libraries");
21253                pw.println("    f[eatures]: list device features");
21254                pw.println("    k[eysets]: print known keysets");
21255                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21256                pw.println("    perm[issions]: dump permissions");
21257                pw.println("    permission [name ...]: dump declaration and use of given permission");
21258                pw.println("    pref[erred]: print preferred package settings");
21259                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21260                pw.println("    prov[iders]: dump content providers");
21261                pw.println("    p[ackages]: dump installed packages");
21262                pw.println("    s[hared-users]: dump shared user IDs");
21263                pw.println("    m[essages]: print collected runtime messages");
21264                pw.println("    v[erifiers]: print package verifier info");
21265                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21266                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21267                pw.println("    version: print database version info");
21268                pw.println("    write: write current settings now");
21269                pw.println("    installs: details about install sessions");
21270                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21271                pw.println("    dexopt: dump dexopt state");
21272                pw.println("    compiler-stats: dump compiler statistics");
21273                pw.println("    service-permissions: dump permissions required by services");
21274                pw.println("    <package.name>: info about given package");
21275                return;
21276            } else if ("--checkin".equals(opt)) {
21277                checkin = true;
21278            } else if ("-f".equals(opt)) {
21279                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21280            } else if ("--proto".equals(opt)) {
21281                dumpProto(fd);
21282                return;
21283            } else {
21284                pw.println("Unknown argument: " + opt + "; use -h for help");
21285            }
21286        }
21287
21288        // Is the caller requesting to dump a particular piece of data?
21289        if (opti < args.length) {
21290            String cmd = args[opti];
21291            opti++;
21292            // Is this a package name?
21293            if ("android".equals(cmd) || cmd.contains(".")) {
21294                packageName = cmd;
21295                // When dumping a single package, we always dump all of its
21296                // filter information since the amount of data will be reasonable.
21297                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21298            } else if ("check-permission".equals(cmd)) {
21299                if (opti >= args.length) {
21300                    pw.println("Error: check-permission missing permission argument");
21301                    return;
21302                }
21303                String perm = args[opti];
21304                opti++;
21305                if (opti >= args.length) {
21306                    pw.println("Error: check-permission missing package argument");
21307                    return;
21308                }
21309
21310                String pkg = args[opti];
21311                opti++;
21312                int user = UserHandle.getUserId(Binder.getCallingUid());
21313                if (opti < args.length) {
21314                    try {
21315                        user = Integer.parseInt(args[opti]);
21316                    } catch (NumberFormatException e) {
21317                        pw.println("Error: check-permission user argument is not a number: "
21318                                + args[opti]);
21319                        return;
21320                    }
21321                }
21322
21323                // Normalize package name to handle renamed packages and static libs
21324                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21325
21326                pw.println(checkPermission(perm, pkg, user));
21327                return;
21328            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21329                dumpState.setDump(DumpState.DUMP_LIBS);
21330            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21331                dumpState.setDump(DumpState.DUMP_FEATURES);
21332            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21333                if (opti >= args.length) {
21334                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21335                            | DumpState.DUMP_SERVICE_RESOLVERS
21336                            | DumpState.DUMP_RECEIVER_RESOLVERS
21337                            | DumpState.DUMP_CONTENT_RESOLVERS);
21338                } else {
21339                    while (opti < args.length) {
21340                        String name = args[opti];
21341                        if ("a".equals(name) || "activity".equals(name)) {
21342                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21343                        } else if ("s".equals(name) || "service".equals(name)) {
21344                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21345                        } else if ("r".equals(name) || "receiver".equals(name)) {
21346                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21347                        } else if ("c".equals(name) || "content".equals(name)) {
21348                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21349                        } else {
21350                            pw.println("Error: unknown resolver table type: " + name);
21351                            return;
21352                        }
21353                        opti++;
21354                    }
21355                }
21356            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21357                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21358            } else if ("permission".equals(cmd)) {
21359                if (opti >= args.length) {
21360                    pw.println("Error: permission requires permission name");
21361                    return;
21362                }
21363                permissionNames = new ArraySet<>();
21364                while (opti < args.length) {
21365                    permissionNames.add(args[opti]);
21366                    opti++;
21367                }
21368                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21369                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21370            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21371                dumpState.setDump(DumpState.DUMP_PREFERRED);
21372            } else if ("preferred-xml".equals(cmd)) {
21373                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21374                if (opti < args.length && "--full".equals(args[opti])) {
21375                    fullPreferred = true;
21376                    opti++;
21377                }
21378            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21379                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21380            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21381                dumpState.setDump(DumpState.DUMP_PACKAGES);
21382            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21383                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21384            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21385                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21386            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21387                dumpState.setDump(DumpState.DUMP_MESSAGES);
21388            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21389                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21390            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21391                    || "intent-filter-verifiers".equals(cmd)) {
21392                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21393            } else if ("version".equals(cmd)) {
21394                dumpState.setDump(DumpState.DUMP_VERSION);
21395            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21396                dumpState.setDump(DumpState.DUMP_KEYSETS);
21397            } else if ("installs".equals(cmd)) {
21398                dumpState.setDump(DumpState.DUMP_INSTALLS);
21399            } else if ("frozen".equals(cmd)) {
21400                dumpState.setDump(DumpState.DUMP_FROZEN);
21401            } else if ("volumes".equals(cmd)) {
21402                dumpState.setDump(DumpState.DUMP_VOLUMES);
21403            } else if ("dexopt".equals(cmd)) {
21404                dumpState.setDump(DumpState.DUMP_DEXOPT);
21405            } else if ("compiler-stats".equals(cmd)) {
21406                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21407            } else if ("changes".equals(cmd)) {
21408                dumpState.setDump(DumpState.DUMP_CHANGES);
21409            } else if ("service-permissions".equals(cmd)) {
21410                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21411            } else if ("write".equals(cmd)) {
21412                synchronized (mPackages) {
21413                    mSettings.writeLPr();
21414                    pw.println("Settings written.");
21415                    return;
21416                }
21417            }
21418        }
21419
21420        if (checkin) {
21421            pw.println("vers,1");
21422        }
21423
21424        // reader
21425        synchronized (mPackages) {
21426            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21427                if (!checkin) {
21428                    if (dumpState.onTitlePrinted())
21429                        pw.println();
21430                    pw.println("Database versions:");
21431                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21432                }
21433            }
21434
21435            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21436                if (!checkin) {
21437                    if (dumpState.onTitlePrinted())
21438                        pw.println();
21439                    pw.println("Verifiers:");
21440                    pw.print("  Required: ");
21441                    pw.print(mRequiredVerifierPackage);
21442                    pw.print(" (uid=");
21443                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21444                            UserHandle.USER_SYSTEM));
21445                    pw.println(")");
21446                } else if (mRequiredVerifierPackage != null) {
21447                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21448                    pw.print(",");
21449                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21450                            UserHandle.USER_SYSTEM));
21451                }
21452            }
21453
21454            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21455                    packageName == null) {
21456                if (mIntentFilterVerifierComponent != null) {
21457                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21458                    if (!checkin) {
21459                        if (dumpState.onTitlePrinted())
21460                            pw.println();
21461                        pw.println("Intent Filter Verifier:");
21462                        pw.print("  Using: ");
21463                        pw.print(verifierPackageName);
21464                        pw.print(" (uid=");
21465                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21466                                UserHandle.USER_SYSTEM));
21467                        pw.println(")");
21468                    } else if (verifierPackageName != null) {
21469                        pw.print("ifv,"); pw.print(verifierPackageName);
21470                        pw.print(",");
21471                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21472                                UserHandle.USER_SYSTEM));
21473                    }
21474                } else {
21475                    pw.println();
21476                    pw.println("No Intent Filter Verifier available!");
21477                }
21478            }
21479
21480            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21481                boolean printedHeader = false;
21482                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21483                while (it.hasNext()) {
21484                    String libName = it.next();
21485                    LongSparseArray<SharedLibraryEntry> versionedLib
21486                            = mSharedLibraries.get(libName);
21487                    if (versionedLib == null) {
21488                        continue;
21489                    }
21490                    final int versionCount = versionedLib.size();
21491                    for (int i = 0; i < versionCount; i++) {
21492                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21493                        if (!checkin) {
21494                            if (!printedHeader) {
21495                                if (dumpState.onTitlePrinted())
21496                                    pw.println();
21497                                pw.println("Libraries:");
21498                                printedHeader = true;
21499                            }
21500                            pw.print("  ");
21501                        } else {
21502                            pw.print("lib,");
21503                        }
21504                        pw.print(libEntry.info.getName());
21505                        if (libEntry.info.isStatic()) {
21506                            pw.print(" version=" + libEntry.info.getLongVersion());
21507                        }
21508                        if (!checkin) {
21509                            pw.print(" -> ");
21510                        }
21511                        if (libEntry.path != null) {
21512                            pw.print(" (jar) ");
21513                            pw.print(libEntry.path);
21514                        } else {
21515                            pw.print(" (apk) ");
21516                            pw.print(libEntry.apk);
21517                        }
21518                        pw.println();
21519                    }
21520                }
21521            }
21522
21523            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21524                if (dumpState.onTitlePrinted())
21525                    pw.println();
21526                if (!checkin) {
21527                    pw.println("Features:");
21528                }
21529
21530                synchronized (mAvailableFeatures) {
21531                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21532                        if (checkin) {
21533                            pw.print("feat,");
21534                            pw.print(feat.name);
21535                            pw.print(",");
21536                            pw.println(feat.version);
21537                        } else {
21538                            pw.print("  ");
21539                            pw.print(feat.name);
21540                            if (feat.version > 0) {
21541                                pw.print(" version=");
21542                                pw.print(feat.version);
21543                            }
21544                            pw.println();
21545                        }
21546                    }
21547                }
21548            }
21549
21550            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21551                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21552                        : "Activity Resolver Table:", "  ", packageName,
21553                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21554                    dumpState.setTitlePrinted(true);
21555                }
21556            }
21557            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21558                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21559                        : "Receiver Resolver Table:", "  ", packageName,
21560                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21561                    dumpState.setTitlePrinted(true);
21562                }
21563            }
21564            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21565                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21566                        : "Service Resolver Table:", "  ", packageName,
21567                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21568                    dumpState.setTitlePrinted(true);
21569                }
21570            }
21571            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21572                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21573                        : "Provider Resolver Table:", "  ", packageName,
21574                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21575                    dumpState.setTitlePrinted(true);
21576                }
21577            }
21578
21579            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21580                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21581                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21582                    int user = mSettings.mPreferredActivities.keyAt(i);
21583                    if (pir.dump(pw,
21584                            dumpState.getTitlePrinted()
21585                                ? "\nPreferred Activities User " + user + ":"
21586                                : "Preferred Activities User " + user + ":", "  ",
21587                            packageName, true, false)) {
21588                        dumpState.setTitlePrinted(true);
21589                    }
21590                }
21591            }
21592
21593            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21594                pw.flush();
21595                FileOutputStream fout = new FileOutputStream(fd);
21596                BufferedOutputStream str = new BufferedOutputStream(fout);
21597                XmlSerializer serializer = new FastXmlSerializer();
21598                try {
21599                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21600                    serializer.startDocument(null, true);
21601                    serializer.setFeature(
21602                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21603                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21604                    serializer.endDocument();
21605                    serializer.flush();
21606                } catch (IllegalArgumentException e) {
21607                    pw.println("Failed writing: " + e);
21608                } catch (IllegalStateException e) {
21609                    pw.println("Failed writing: " + e);
21610                } catch (IOException e) {
21611                    pw.println("Failed writing: " + e);
21612                }
21613            }
21614
21615            if (!checkin
21616                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21617                    && packageName == null) {
21618                pw.println();
21619                int count = mSettings.mPackages.size();
21620                if (count == 0) {
21621                    pw.println("No applications!");
21622                    pw.println();
21623                } else {
21624                    final String prefix = "  ";
21625                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21626                    if (allPackageSettings.size() == 0) {
21627                        pw.println("No domain preferred apps!");
21628                        pw.println();
21629                    } else {
21630                        pw.println("App verification status:");
21631                        pw.println();
21632                        count = 0;
21633                        for (PackageSetting ps : allPackageSettings) {
21634                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21635                            if (ivi == null || ivi.getPackageName() == null) continue;
21636                            pw.println(prefix + "Package: " + ivi.getPackageName());
21637                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21638                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21639                            pw.println();
21640                            count++;
21641                        }
21642                        if (count == 0) {
21643                            pw.println(prefix + "No app verification established.");
21644                            pw.println();
21645                        }
21646                        for (int userId : sUserManager.getUserIds()) {
21647                            pw.println("App linkages for user " + userId + ":");
21648                            pw.println();
21649                            count = 0;
21650                            for (PackageSetting ps : allPackageSettings) {
21651                                final long status = ps.getDomainVerificationStatusForUser(userId);
21652                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21653                                        && !DEBUG_DOMAIN_VERIFICATION) {
21654                                    continue;
21655                                }
21656                                pw.println(prefix + "Package: " + ps.name);
21657                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21658                                String statusStr = IntentFilterVerificationInfo.
21659                                        getStatusStringFromValue(status);
21660                                pw.println(prefix + "Status:  " + statusStr);
21661                                pw.println();
21662                                count++;
21663                            }
21664                            if (count == 0) {
21665                                pw.println(prefix + "No configured app linkages.");
21666                                pw.println();
21667                            }
21668                        }
21669                    }
21670                }
21671            }
21672
21673            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21674                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21675            }
21676
21677            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21678                boolean printedSomething = false;
21679                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21680                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21681                        continue;
21682                    }
21683                    if (!printedSomething) {
21684                        if (dumpState.onTitlePrinted())
21685                            pw.println();
21686                        pw.println("Registered ContentProviders:");
21687                        printedSomething = true;
21688                    }
21689                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21690                    pw.print("    "); pw.println(p.toString());
21691                }
21692                printedSomething = false;
21693                for (Map.Entry<String, PackageParser.Provider> entry :
21694                        mProvidersByAuthority.entrySet()) {
21695                    PackageParser.Provider p = entry.getValue();
21696                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21697                        continue;
21698                    }
21699                    if (!printedSomething) {
21700                        if (dumpState.onTitlePrinted())
21701                            pw.println();
21702                        pw.println("ContentProvider Authorities:");
21703                        printedSomething = true;
21704                    }
21705                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21706                    pw.print("    "); pw.println(p.toString());
21707                    if (p.info != null && p.info.applicationInfo != null) {
21708                        final String appInfo = p.info.applicationInfo.toString();
21709                        pw.print("      applicationInfo="); pw.println(appInfo);
21710                    }
21711                }
21712            }
21713
21714            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21715                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21716            }
21717
21718            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21719                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21720            }
21721
21722            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21723                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21724            }
21725
21726            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21727                if (dumpState.onTitlePrinted()) pw.println();
21728                pw.println("Package Changes:");
21729                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21730                final int K = mChangedPackages.size();
21731                for (int i = 0; i < K; i++) {
21732                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21733                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21734                    final int N = changes.size();
21735                    if (N == 0) {
21736                        pw.print("    "); pw.println("No packages changed");
21737                    } else {
21738                        for (int j = 0; j < N; j++) {
21739                            final String pkgName = changes.valueAt(j);
21740                            final int sequenceNumber = changes.keyAt(j);
21741                            pw.print("    ");
21742                            pw.print("seq=");
21743                            pw.print(sequenceNumber);
21744                            pw.print(", package=");
21745                            pw.println(pkgName);
21746                        }
21747                    }
21748                }
21749            }
21750
21751            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21752                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21753            }
21754
21755            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21756                // XXX should handle packageName != null by dumping only install data that
21757                // the given package is involved with.
21758                if (dumpState.onTitlePrinted()) pw.println();
21759
21760                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21761                ipw.println();
21762                ipw.println("Frozen packages:");
21763                ipw.increaseIndent();
21764                if (mFrozenPackages.size() == 0) {
21765                    ipw.println("(none)");
21766                } else {
21767                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21768                        ipw.println(mFrozenPackages.valueAt(i));
21769                    }
21770                }
21771                ipw.decreaseIndent();
21772            }
21773
21774            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21775                if (dumpState.onTitlePrinted()) pw.println();
21776
21777                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21778                ipw.println();
21779                ipw.println("Loaded volumes:");
21780                ipw.increaseIndent();
21781                if (mLoadedVolumes.size() == 0) {
21782                    ipw.println("(none)");
21783                } else {
21784                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21785                        ipw.println(mLoadedVolumes.valueAt(i));
21786                    }
21787                }
21788                ipw.decreaseIndent();
21789            }
21790
21791            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21792                    && packageName == null) {
21793                if (dumpState.onTitlePrinted()) pw.println();
21794                pw.println("Service permissions:");
21795
21796                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21797                while (filterIterator.hasNext()) {
21798                    final ServiceIntentInfo info = filterIterator.next();
21799                    final ServiceInfo serviceInfo = info.service.info;
21800                    final String permission = serviceInfo.permission;
21801                    if (permission != null) {
21802                        pw.print("    ");
21803                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21804                        pw.print(": ");
21805                        pw.println(permission);
21806                    }
21807                }
21808            }
21809
21810            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21811                if (dumpState.onTitlePrinted()) pw.println();
21812                dumpDexoptStateLPr(pw, packageName);
21813            }
21814
21815            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21816                if (dumpState.onTitlePrinted()) pw.println();
21817                dumpCompilerStatsLPr(pw, packageName);
21818            }
21819
21820            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21821                if (dumpState.onTitlePrinted()) pw.println();
21822                mSettings.dumpReadMessagesLPr(pw, dumpState);
21823
21824                pw.println();
21825                pw.println("Package warning messages:");
21826                dumpCriticalInfo(pw, null);
21827            }
21828
21829            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21830                dumpCriticalInfo(pw, "msg,");
21831            }
21832        }
21833
21834        // PackageInstaller should be called outside of mPackages lock
21835        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21836            // XXX should handle packageName != null by dumping only install data that
21837            // the given package is involved with.
21838            if (dumpState.onTitlePrinted()) pw.println();
21839            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21840        }
21841    }
21842
21843    private void dumpProto(FileDescriptor fd) {
21844        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21845
21846        synchronized (mPackages) {
21847            final long requiredVerifierPackageToken =
21848                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21849            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21850            proto.write(
21851                    PackageServiceDumpProto.PackageShortProto.UID,
21852                    getPackageUid(
21853                            mRequiredVerifierPackage,
21854                            MATCH_DEBUG_TRIAGED_MISSING,
21855                            UserHandle.USER_SYSTEM));
21856            proto.end(requiredVerifierPackageToken);
21857
21858            if (mIntentFilterVerifierComponent != null) {
21859                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21860                final long verifierPackageToken =
21861                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21862                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21863                proto.write(
21864                        PackageServiceDumpProto.PackageShortProto.UID,
21865                        getPackageUid(
21866                                verifierPackageName,
21867                                MATCH_DEBUG_TRIAGED_MISSING,
21868                                UserHandle.USER_SYSTEM));
21869                proto.end(verifierPackageToken);
21870            }
21871
21872            dumpSharedLibrariesProto(proto);
21873            dumpFeaturesProto(proto);
21874            mSettings.dumpPackagesProto(proto);
21875            mSettings.dumpSharedUsersProto(proto);
21876            dumpCriticalInfo(proto);
21877        }
21878        proto.flush();
21879    }
21880
21881    private void dumpFeaturesProto(ProtoOutputStream proto) {
21882        synchronized (mAvailableFeatures) {
21883            final int count = mAvailableFeatures.size();
21884            for (int i = 0; i < count; i++) {
21885                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21886            }
21887        }
21888    }
21889
21890    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21891        final int count = mSharedLibraries.size();
21892        for (int i = 0; i < count; i++) {
21893            final String libName = mSharedLibraries.keyAt(i);
21894            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21895            if (versionedLib == null) {
21896                continue;
21897            }
21898            final int versionCount = versionedLib.size();
21899            for (int j = 0; j < versionCount; j++) {
21900                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21901                final long sharedLibraryToken =
21902                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21903                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21904                final boolean isJar = (libEntry.path != null);
21905                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21906                if (isJar) {
21907                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21908                } else {
21909                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21910                }
21911                proto.end(sharedLibraryToken);
21912            }
21913        }
21914    }
21915
21916    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21917        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21918        ipw.println();
21919        ipw.println("Dexopt state:");
21920        ipw.increaseIndent();
21921        Collection<PackageParser.Package> packages = null;
21922        if (packageName != null) {
21923            PackageParser.Package targetPackage = mPackages.get(packageName);
21924            if (targetPackage != null) {
21925                packages = Collections.singletonList(targetPackage);
21926            } else {
21927                ipw.println("Unable to find package: " + packageName);
21928                return;
21929            }
21930        } else {
21931            packages = mPackages.values();
21932        }
21933
21934        for (PackageParser.Package pkg : packages) {
21935            ipw.println("[" + pkg.packageName + "]");
21936            ipw.increaseIndent();
21937            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21938                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21939            ipw.decreaseIndent();
21940        }
21941    }
21942
21943    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21944        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21945        ipw.println();
21946        ipw.println("Compiler stats:");
21947        ipw.increaseIndent();
21948        Collection<PackageParser.Package> packages = null;
21949        if (packageName != null) {
21950            PackageParser.Package targetPackage = mPackages.get(packageName);
21951            if (targetPackage != null) {
21952                packages = Collections.singletonList(targetPackage);
21953            } else {
21954                ipw.println("Unable to find package: " + packageName);
21955                return;
21956            }
21957        } else {
21958            packages = mPackages.values();
21959        }
21960
21961        for (PackageParser.Package pkg : packages) {
21962            ipw.println("[" + pkg.packageName + "]");
21963            ipw.increaseIndent();
21964
21965            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21966            if (stats == null) {
21967                ipw.println("(No recorded stats)");
21968            } else {
21969                stats.dump(ipw);
21970            }
21971            ipw.decreaseIndent();
21972        }
21973    }
21974
21975    private String dumpDomainString(String packageName) {
21976        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21977                .getList();
21978        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21979
21980        ArraySet<String> result = new ArraySet<>();
21981        if (iviList.size() > 0) {
21982            for (IntentFilterVerificationInfo ivi : iviList) {
21983                for (String host : ivi.getDomains()) {
21984                    result.add(host);
21985                }
21986            }
21987        }
21988        if (filters != null && filters.size() > 0) {
21989            for (IntentFilter filter : filters) {
21990                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21991                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21992                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21993                    result.addAll(filter.getHostsList());
21994                }
21995            }
21996        }
21997
21998        StringBuilder sb = new StringBuilder(result.size() * 16);
21999        for (String domain : result) {
22000            if (sb.length() > 0) sb.append(" ");
22001            sb.append(domain);
22002        }
22003        return sb.toString();
22004    }
22005
22006    // ------- apps on sdcard specific code -------
22007    static final boolean DEBUG_SD_INSTALL = false;
22008
22009    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22010
22011    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22012
22013    private boolean mMediaMounted = false;
22014
22015    static String getEncryptKey() {
22016        try {
22017            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22018                    SD_ENCRYPTION_KEYSTORE_NAME);
22019            if (sdEncKey == null) {
22020                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22021                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22022                if (sdEncKey == null) {
22023                    Slog.e(TAG, "Failed to create encryption keys");
22024                    return null;
22025                }
22026            }
22027            return sdEncKey;
22028        } catch (NoSuchAlgorithmException nsae) {
22029            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22030            return null;
22031        } catch (IOException ioe) {
22032            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22033            return null;
22034        }
22035    }
22036
22037    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22038            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22039        final int size = infos.size();
22040        final String[] packageNames = new String[size];
22041        final int[] packageUids = new int[size];
22042        for (int i = 0; i < size; i++) {
22043            final ApplicationInfo info = infos.get(i);
22044            packageNames[i] = info.packageName;
22045            packageUids[i] = info.uid;
22046        }
22047        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22048                finishedReceiver);
22049    }
22050
22051    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22052            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22053        sendResourcesChangedBroadcast(mediaStatus, replacing,
22054                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22055    }
22056
22057    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22058            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22059        int size = pkgList.length;
22060        if (size > 0) {
22061            // Send broadcasts here
22062            Bundle extras = new Bundle();
22063            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22064            if (uidArr != null) {
22065                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22066            }
22067            if (replacing) {
22068                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22069            }
22070            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22071                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22072            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22073        }
22074    }
22075
22076    private void loadPrivatePackages(final VolumeInfo vol) {
22077        mHandler.post(new Runnable() {
22078            @Override
22079            public void run() {
22080                loadPrivatePackagesInner(vol);
22081            }
22082        });
22083    }
22084
22085    private void loadPrivatePackagesInner(VolumeInfo vol) {
22086        final String volumeUuid = vol.fsUuid;
22087        if (TextUtils.isEmpty(volumeUuid)) {
22088            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22089            return;
22090        }
22091
22092        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22093        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22094        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22095
22096        final VersionInfo ver;
22097        final List<PackageSetting> packages;
22098        synchronized (mPackages) {
22099            ver = mSettings.findOrCreateVersion(volumeUuid);
22100            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22101        }
22102
22103        for (PackageSetting ps : packages) {
22104            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22105            synchronized (mInstallLock) {
22106                final PackageParser.Package pkg;
22107                try {
22108                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22109                    loaded.add(pkg.applicationInfo);
22110
22111                } catch (PackageManagerException e) {
22112                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22113                }
22114
22115                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22116                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22117                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22118                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22119                }
22120            }
22121        }
22122
22123        // Reconcile app data for all started/unlocked users
22124        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22125        final UserManager um = mContext.getSystemService(UserManager.class);
22126        UserManagerInternal umInternal = getUserManagerInternal();
22127        for (UserInfo user : um.getUsers()) {
22128            final int flags;
22129            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22130                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22131            } else if (umInternal.isUserRunning(user.id)) {
22132                flags = StorageManager.FLAG_STORAGE_DE;
22133            } else {
22134                continue;
22135            }
22136
22137            try {
22138                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22139                synchronized (mInstallLock) {
22140                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22141                }
22142            } catch (IllegalStateException e) {
22143                // Device was probably ejected, and we'll process that event momentarily
22144                Slog.w(TAG, "Failed to prepare storage: " + e);
22145            }
22146        }
22147
22148        synchronized (mPackages) {
22149            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22150            if (sdkUpdated) {
22151                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22152                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22153            }
22154            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22155                    mPermissionCallback);
22156
22157            // Yay, everything is now upgraded
22158            ver.forceCurrent();
22159
22160            mSettings.writeLPr();
22161        }
22162
22163        for (PackageFreezer freezer : freezers) {
22164            freezer.close();
22165        }
22166
22167        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22168        sendResourcesChangedBroadcast(true, false, loaded, null);
22169        mLoadedVolumes.add(vol.getId());
22170    }
22171
22172    private void unloadPrivatePackages(final VolumeInfo vol) {
22173        mHandler.post(new Runnable() {
22174            @Override
22175            public void run() {
22176                unloadPrivatePackagesInner(vol);
22177            }
22178        });
22179    }
22180
22181    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22182        final String volumeUuid = vol.fsUuid;
22183        if (TextUtils.isEmpty(volumeUuid)) {
22184            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22185            return;
22186        }
22187
22188        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22189        synchronized (mInstallLock) {
22190        synchronized (mPackages) {
22191            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22192            for (PackageSetting ps : packages) {
22193                if (ps.pkg == null) continue;
22194
22195                final ApplicationInfo info = ps.pkg.applicationInfo;
22196                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22197                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22198
22199                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22200                        "unloadPrivatePackagesInner")) {
22201                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22202                            false, null)) {
22203                        unloaded.add(info);
22204                    } else {
22205                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22206                    }
22207                }
22208
22209                // Try very hard to release any references to this package
22210                // so we don't risk the system server being killed due to
22211                // open FDs
22212                AttributeCache.instance().removePackage(ps.name);
22213            }
22214
22215            mSettings.writeLPr();
22216        }
22217        }
22218
22219        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22220        sendResourcesChangedBroadcast(false, false, unloaded, null);
22221        mLoadedVolumes.remove(vol.getId());
22222
22223        // Try very hard to release any references to this path so we don't risk
22224        // the system server being killed due to open FDs
22225        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22226
22227        for (int i = 0; i < 3; i++) {
22228            System.gc();
22229            System.runFinalization();
22230        }
22231    }
22232
22233    private void assertPackageKnown(String volumeUuid, String packageName)
22234            throws PackageManagerException {
22235        synchronized (mPackages) {
22236            // Normalize package name to handle renamed packages
22237            packageName = normalizePackageNameLPr(packageName);
22238
22239            final PackageSetting ps = mSettings.mPackages.get(packageName);
22240            if (ps == null) {
22241                throw new PackageManagerException("Package " + packageName + " is unknown");
22242            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22243                throw new PackageManagerException(
22244                        "Package " + packageName + " found on unknown volume " + volumeUuid
22245                                + "; expected volume " + ps.volumeUuid);
22246            }
22247        }
22248    }
22249
22250    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22251            throws PackageManagerException {
22252        synchronized (mPackages) {
22253            // Normalize package name to handle renamed packages
22254            packageName = normalizePackageNameLPr(packageName);
22255
22256            final PackageSetting ps = mSettings.mPackages.get(packageName);
22257            if (ps == null) {
22258                throw new PackageManagerException("Package " + packageName + " is unknown");
22259            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22260                throw new PackageManagerException(
22261                        "Package " + packageName + " found on unknown volume " + volumeUuid
22262                                + "; expected volume " + ps.volumeUuid);
22263            } else if (!ps.getInstalled(userId)) {
22264                throw new PackageManagerException(
22265                        "Package " + packageName + " not installed for user " + userId);
22266            }
22267        }
22268    }
22269
22270    private List<String> collectAbsoluteCodePaths() {
22271        synchronized (mPackages) {
22272            List<String> codePaths = new ArrayList<>();
22273            final int packageCount = mSettings.mPackages.size();
22274            for (int i = 0; i < packageCount; i++) {
22275                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22276                codePaths.add(ps.codePath.getAbsolutePath());
22277            }
22278            return codePaths;
22279        }
22280    }
22281
22282    /**
22283     * Examine all apps present on given mounted volume, and destroy apps that
22284     * aren't expected, either due to uninstallation or reinstallation on
22285     * another volume.
22286     */
22287    private void reconcileApps(String volumeUuid) {
22288        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22289        List<File> filesToDelete = null;
22290
22291        final File[] files = FileUtils.listFilesOrEmpty(
22292                Environment.getDataAppDirectory(volumeUuid));
22293        for (File file : files) {
22294            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22295                    && !PackageInstallerService.isStageName(file.getName());
22296            if (!isPackage) {
22297                // Ignore entries which are not packages
22298                continue;
22299            }
22300
22301            String absolutePath = file.getAbsolutePath();
22302
22303            boolean pathValid = false;
22304            final int absoluteCodePathCount = absoluteCodePaths.size();
22305            for (int i = 0; i < absoluteCodePathCount; i++) {
22306                String absoluteCodePath = absoluteCodePaths.get(i);
22307                if (absolutePath.startsWith(absoluteCodePath)) {
22308                    pathValid = true;
22309                    break;
22310                }
22311            }
22312
22313            if (!pathValid) {
22314                if (filesToDelete == null) {
22315                    filesToDelete = new ArrayList<>();
22316                }
22317                filesToDelete.add(file);
22318            }
22319        }
22320
22321        if (filesToDelete != null) {
22322            final int fileToDeleteCount = filesToDelete.size();
22323            for (int i = 0; i < fileToDeleteCount; i++) {
22324                File fileToDelete = filesToDelete.get(i);
22325                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22326                synchronized (mInstallLock) {
22327                    removeCodePathLI(fileToDelete);
22328                }
22329            }
22330        }
22331    }
22332
22333    /**
22334     * Reconcile all app data for the given user.
22335     * <p>
22336     * Verifies that directories exist and that ownership and labeling is
22337     * correct for all installed apps on all mounted volumes.
22338     */
22339    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22340        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22341        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22342            final String volumeUuid = vol.getFsUuid();
22343            synchronized (mInstallLock) {
22344                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22345            }
22346        }
22347    }
22348
22349    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22350            boolean migrateAppData) {
22351        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22352    }
22353
22354    /**
22355     * Reconcile all app data on given mounted volume.
22356     * <p>
22357     * Destroys app data that isn't expected, either due to uninstallation or
22358     * reinstallation on another volume.
22359     * <p>
22360     * Verifies that directories exist and that ownership and labeling is
22361     * correct for all installed apps.
22362     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22363     */
22364    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22365            boolean migrateAppData, boolean onlyCoreApps) {
22366        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22367                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22368        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22369
22370        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22371        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22372
22373        // First look for stale data that doesn't belong, and check if things
22374        // have changed since we did our last restorecon
22375        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22376            if (StorageManager.isFileEncryptedNativeOrEmulated()
22377                    && !StorageManager.isUserKeyUnlocked(userId)) {
22378                throw new RuntimeException(
22379                        "Yikes, someone asked us to reconcile CE storage while " + userId
22380                                + " was still locked; this would have caused massive data loss!");
22381            }
22382
22383            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22384            for (File file : files) {
22385                final String packageName = file.getName();
22386                try {
22387                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22388                } catch (PackageManagerException e) {
22389                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22390                    try {
22391                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22392                                StorageManager.FLAG_STORAGE_CE, 0);
22393                    } catch (InstallerException e2) {
22394                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22395                    }
22396                }
22397            }
22398        }
22399        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22400            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22401            for (File file : files) {
22402                final String packageName = file.getName();
22403                try {
22404                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22405                } catch (PackageManagerException e) {
22406                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22407                    try {
22408                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22409                                StorageManager.FLAG_STORAGE_DE, 0);
22410                    } catch (InstallerException e2) {
22411                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22412                    }
22413                }
22414            }
22415        }
22416
22417        // Ensure that data directories are ready to roll for all packages
22418        // installed for this volume and user
22419        final List<PackageSetting> packages;
22420        synchronized (mPackages) {
22421            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22422        }
22423        int preparedCount = 0;
22424        for (PackageSetting ps : packages) {
22425            final String packageName = ps.name;
22426            if (ps.pkg == null) {
22427                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22428                // TODO: might be due to legacy ASEC apps; we should circle back
22429                // and reconcile again once they're scanned
22430                continue;
22431            }
22432            // Skip non-core apps if requested
22433            if (onlyCoreApps && !ps.pkg.coreApp) {
22434                result.add(packageName);
22435                continue;
22436            }
22437
22438            if (ps.getInstalled(userId)) {
22439                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22440                preparedCount++;
22441            }
22442        }
22443
22444        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22445        return result;
22446    }
22447
22448    /**
22449     * Prepare app data for the given app just after it was installed or
22450     * upgraded. This method carefully only touches users that it's installed
22451     * for, and it forces a restorecon to handle any seinfo changes.
22452     * <p>
22453     * Verifies that directories exist and that ownership and labeling is
22454     * correct for all installed apps. If there is an ownership mismatch, it
22455     * will try recovering system apps by wiping data; third-party app data is
22456     * left intact.
22457     * <p>
22458     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22459     */
22460    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22461        final PackageSetting ps;
22462        synchronized (mPackages) {
22463            ps = mSettings.mPackages.get(pkg.packageName);
22464            mSettings.writeKernelMappingLPr(ps);
22465        }
22466
22467        final UserManager um = mContext.getSystemService(UserManager.class);
22468        UserManagerInternal umInternal = getUserManagerInternal();
22469        for (UserInfo user : um.getUsers()) {
22470            final int flags;
22471            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22472                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22473            } else if (umInternal.isUserRunning(user.id)) {
22474                flags = StorageManager.FLAG_STORAGE_DE;
22475            } else {
22476                continue;
22477            }
22478
22479            if (ps.getInstalled(user.id)) {
22480                // TODO: when user data is locked, mark that we're still dirty
22481                prepareAppDataLIF(pkg, user.id, flags);
22482            }
22483        }
22484    }
22485
22486    /**
22487     * Prepare app data for the given app.
22488     * <p>
22489     * Verifies that directories exist and that ownership and labeling is
22490     * correct for all installed apps. If there is an ownership mismatch, this
22491     * will try recovering system apps by wiping data; third-party app data is
22492     * left intact.
22493     */
22494    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22495        if (pkg == null) {
22496            Slog.wtf(TAG, "Package was null!", new Throwable());
22497            return;
22498        }
22499        prepareAppDataLeafLIF(pkg, userId, flags);
22500        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22501        for (int i = 0; i < childCount; i++) {
22502            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22503        }
22504    }
22505
22506    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22507            boolean maybeMigrateAppData) {
22508        prepareAppDataLIF(pkg, userId, flags);
22509
22510        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22511            // We may have just shuffled around app data directories, so
22512            // prepare them one more time
22513            prepareAppDataLIF(pkg, userId, flags);
22514        }
22515    }
22516
22517    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22518        if (DEBUG_APP_DATA) {
22519            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22520                    + Integer.toHexString(flags));
22521        }
22522
22523        final PackageSetting ps;
22524        synchronized (mPackages) {
22525            ps = mSettings.mPackages.get(pkg.packageName);
22526        }
22527        final String volumeUuid = pkg.volumeUuid;
22528        final String packageName = pkg.packageName;
22529
22530        ApplicationInfo app = (ps == null)
22531                ? pkg.applicationInfo
22532                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22533        if (app == null) {
22534            app = pkg.applicationInfo;
22535        }
22536
22537        final int appId = UserHandle.getAppId(app.uid);
22538
22539        Preconditions.checkNotNull(app.seInfo);
22540
22541        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22542        long ceDataInode = -1;
22543        try {
22544            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22545                    appId, seInfo, app.targetSdkVersion);
22546        } catch (InstallerException e) {
22547            if (app.isSystemApp()) {
22548                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22549                        + ", but trying to recover: " + e);
22550                destroyAppDataLeafLIF(pkg, userId, flags);
22551                try {
22552                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22553                            appId, seInfo, app.targetSdkVersion);
22554                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22555                } catch (InstallerException e2) {
22556                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22557                }
22558            } else {
22559                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22560            }
22561        }
22562        // Prepare the application profiles only for upgrades and first boot (so that we don't
22563        // repeat the same operation at each boot).
22564        // We only have to cover the upgrade and first boot here because for app installs we
22565        // prepare the profiles before invoking dexopt (in installPackageLI).
22566        //
22567        // We also have to cover non system users because we do not call the usual install package
22568        // methods for them.
22569        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22570            mArtManagerService.prepareAppProfiles(pkg, userId);
22571        }
22572
22573        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22574            // TODO: mark this structure as dirty so we persist it!
22575            synchronized (mPackages) {
22576                if (ps != null) {
22577                    ps.setCeDataInode(ceDataInode, userId);
22578                }
22579            }
22580        }
22581
22582        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22583    }
22584
22585    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22586        if (pkg == null) {
22587            Slog.wtf(TAG, "Package was null!", new Throwable());
22588            return;
22589        }
22590        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22591        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22592        for (int i = 0; i < childCount; i++) {
22593            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22594        }
22595    }
22596
22597    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22598        final String volumeUuid = pkg.volumeUuid;
22599        final String packageName = pkg.packageName;
22600        final ApplicationInfo app = pkg.applicationInfo;
22601
22602        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22603            // Create a native library symlink only if we have native libraries
22604            // and if the native libraries are 32 bit libraries. We do not provide
22605            // this symlink for 64 bit libraries.
22606            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22607                final String nativeLibPath = app.nativeLibraryDir;
22608                try {
22609                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22610                            nativeLibPath, userId);
22611                } catch (InstallerException e) {
22612                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22613                }
22614            }
22615        }
22616    }
22617
22618    /**
22619     * For system apps on non-FBE devices, this method migrates any existing
22620     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22621     * requested by the app.
22622     */
22623    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22624        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22625                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22626            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22627                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22628            try {
22629                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22630                        storageTarget);
22631            } catch (InstallerException e) {
22632                logCriticalInfo(Log.WARN,
22633                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22634            }
22635            return true;
22636        } else {
22637            return false;
22638        }
22639    }
22640
22641    public PackageFreezer freezePackage(String packageName, String killReason) {
22642        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22643    }
22644
22645    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22646        return new PackageFreezer(packageName, userId, killReason);
22647    }
22648
22649    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22650            String killReason) {
22651        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22652    }
22653
22654    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22655            String killReason) {
22656        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22657            return new PackageFreezer();
22658        } else {
22659            return freezePackage(packageName, userId, killReason);
22660        }
22661    }
22662
22663    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22664            String killReason) {
22665        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22666    }
22667
22668    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22669            String killReason) {
22670        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22671            return new PackageFreezer();
22672        } else {
22673            return freezePackage(packageName, userId, killReason);
22674        }
22675    }
22676
22677    /**
22678     * Class that freezes and kills the given package upon creation, and
22679     * unfreezes it upon closing. This is typically used when doing surgery on
22680     * app code/data to prevent the app from running while you're working.
22681     */
22682    private class PackageFreezer implements AutoCloseable {
22683        private final String mPackageName;
22684        private final PackageFreezer[] mChildren;
22685
22686        private final boolean mWeFroze;
22687
22688        private final AtomicBoolean mClosed = new AtomicBoolean();
22689        private final CloseGuard mCloseGuard = CloseGuard.get();
22690
22691        /**
22692         * Create and return a stub freezer that doesn't actually do anything,
22693         * typically used when someone requested
22694         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22695         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22696         */
22697        public PackageFreezer() {
22698            mPackageName = null;
22699            mChildren = null;
22700            mWeFroze = false;
22701            mCloseGuard.open("close");
22702        }
22703
22704        public PackageFreezer(String packageName, int userId, String killReason) {
22705            synchronized (mPackages) {
22706                mPackageName = packageName;
22707                mWeFroze = mFrozenPackages.add(mPackageName);
22708
22709                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22710                if (ps != null) {
22711                    killApplication(ps.name, ps.appId, userId, killReason);
22712                }
22713
22714                final PackageParser.Package p = mPackages.get(packageName);
22715                if (p != null && p.childPackages != null) {
22716                    final int N = p.childPackages.size();
22717                    mChildren = new PackageFreezer[N];
22718                    for (int i = 0; i < N; i++) {
22719                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22720                                userId, killReason);
22721                    }
22722                } else {
22723                    mChildren = null;
22724                }
22725            }
22726            mCloseGuard.open("close");
22727        }
22728
22729        @Override
22730        protected void finalize() throws Throwable {
22731            try {
22732                if (mCloseGuard != null) {
22733                    mCloseGuard.warnIfOpen();
22734                }
22735
22736                close();
22737            } finally {
22738                super.finalize();
22739            }
22740        }
22741
22742        @Override
22743        public void close() {
22744            mCloseGuard.close();
22745            if (mClosed.compareAndSet(false, true)) {
22746                synchronized (mPackages) {
22747                    if (mWeFroze) {
22748                        mFrozenPackages.remove(mPackageName);
22749                    }
22750
22751                    if (mChildren != null) {
22752                        for (PackageFreezer freezer : mChildren) {
22753                            freezer.close();
22754                        }
22755                    }
22756                }
22757            }
22758        }
22759    }
22760
22761    /**
22762     * Verify that given package is currently frozen.
22763     */
22764    private void checkPackageFrozen(String packageName) {
22765        synchronized (mPackages) {
22766            if (!mFrozenPackages.contains(packageName)) {
22767                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22768            }
22769        }
22770    }
22771
22772    @Override
22773    public int movePackage(final String packageName, final String volumeUuid) {
22774        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22775
22776        final int callingUid = Binder.getCallingUid();
22777        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22778        final int moveId = mNextMoveId.getAndIncrement();
22779        mHandler.post(new Runnable() {
22780            @Override
22781            public void run() {
22782                try {
22783                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22784                } catch (PackageManagerException e) {
22785                    Slog.w(TAG, "Failed to move " + packageName, e);
22786                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22787                }
22788            }
22789        });
22790        return moveId;
22791    }
22792
22793    private void movePackageInternal(final String packageName, final String volumeUuid,
22794            final int moveId, final int callingUid, UserHandle user)
22795                    throws PackageManagerException {
22796        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22797        final PackageManager pm = mContext.getPackageManager();
22798
22799        final boolean currentAsec;
22800        final String currentVolumeUuid;
22801        final File codeFile;
22802        final String installerPackageName;
22803        final String packageAbiOverride;
22804        final int appId;
22805        final String seinfo;
22806        final String label;
22807        final int targetSdkVersion;
22808        final PackageFreezer freezer;
22809        final int[] installedUserIds;
22810
22811        // reader
22812        synchronized (mPackages) {
22813            final PackageParser.Package pkg = mPackages.get(packageName);
22814            final PackageSetting ps = mSettings.mPackages.get(packageName);
22815            if (pkg == null
22816                    || ps == null
22817                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22818                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22819            }
22820            if (pkg.applicationInfo.isSystemApp()) {
22821                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22822                        "Cannot move system application");
22823            }
22824
22825            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22826            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22827                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22828            if (isInternalStorage && !allow3rdPartyOnInternal) {
22829                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22830                        "3rd party apps are not allowed on internal storage");
22831            }
22832
22833            if (pkg.applicationInfo.isExternalAsec()) {
22834                currentAsec = true;
22835                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22836            } else if (pkg.applicationInfo.isForwardLocked()) {
22837                currentAsec = true;
22838                currentVolumeUuid = "forward_locked";
22839            } else {
22840                currentAsec = false;
22841                currentVolumeUuid = ps.volumeUuid;
22842
22843                final File probe = new File(pkg.codePath);
22844                final File probeOat = new File(probe, "oat");
22845                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22846                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22847                            "Move only supported for modern cluster style installs");
22848                }
22849            }
22850
22851            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22852                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22853                        "Package already moved to " + volumeUuid);
22854            }
22855            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22856                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22857                        "Device admin cannot be moved");
22858            }
22859
22860            if (mFrozenPackages.contains(packageName)) {
22861                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22862                        "Failed to move already frozen package");
22863            }
22864
22865            codeFile = new File(pkg.codePath);
22866            installerPackageName = ps.installerPackageName;
22867            packageAbiOverride = ps.cpuAbiOverrideString;
22868            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22869            seinfo = pkg.applicationInfo.seInfo;
22870            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22871            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22872            freezer = freezePackage(packageName, "movePackageInternal");
22873            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22874        }
22875
22876        final Bundle extras = new Bundle();
22877        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22878        extras.putString(Intent.EXTRA_TITLE, label);
22879        mMoveCallbacks.notifyCreated(moveId, extras);
22880
22881        int installFlags;
22882        final boolean moveCompleteApp;
22883        final File measurePath;
22884
22885        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22886            installFlags = INSTALL_INTERNAL;
22887            moveCompleteApp = !currentAsec;
22888            measurePath = Environment.getDataAppDirectory(volumeUuid);
22889        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22890            installFlags = INSTALL_EXTERNAL;
22891            moveCompleteApp = false;
22892            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22893        } else {
22894            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22895            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22896                    || !volume.isMountedWritable()) {
22897                freezer.close();
22898                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22899                        "Move location not mounted private volume");
22900            }
22901
22902            Preconditions.checkState(!currentAsec);
22903
22904            installFlags = INSTALL_INTERNAL;
22905            moveCompleteApp = true;
22906            measurePath = Environment.getDataAppDirectory(volumeUuid);
22907        }
22908
22909        // If we're moving app data around, we need all the users unlocked
22910        if (moveCompleteApp) {
22911            for (int userId : installedUserIds) {
22912                if (StorageManager.isFileEncryptedNativeOrEmulated()
22913                        && !StorageManager.isUserKeyUnlocked(userId)) {
22914                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22915                            "User " + userId + " must be unlocked");
22916                }
22917            }
22918        }
22919
22920        final PackageStats stats = new PackageStats(null, -1);
22921        synchronized (mInstaller) {
22922            for (int userId : installedUserIds) {
22923                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22924                    freezer.close();
22925                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22926                            "Failed to measure package size");
22927                }
22928            }
22929        }
22930
22931        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22932                + stats.dataSize);
22933
22934        final long startFreeBytes = measurePath.getUsableSpace();
22935        final long sizeBytes;
22936        if (moveCompleteApp) {
22937            sizeBytes = stats.codeSize + stats.dataSize;
22938        } else {
22939            sizeBytes = stats.codeSize;
22940        }
22941
22942        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22943            freezer.close();
22944            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22945                    "Not enough free space to move");
22946        }
22947
22948        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22949
22950        final CountDownLatch installedLatch = new CountDownLatch(1);
22951        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22952            @Override
22953            public void onUserActionRequired(Intent intent) throws RemoteException {
22954                throw new IllegalStateException();
22955            }
22956
22957            @Override
22958            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22959                    Bundle extras) throws RemoteException {
22960                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22961                        + PackageManager.installStatusToString(returnCode, msg));
22962
22963                installedLatch.countDown();
22964                freezer.close();
22965
22966                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22967                switch (status) {
22968                    case PackageInstaller.STATUS_SUCCESS:
22969                        mMoveCallbacks.notifyStatusChanged(moveId,
22970                                PackageManager.MOVE_SUCCEEDED);
22971                        break;
22972                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22973                        mMoveCallbacks.notifyStatusChanged(moveId,
22974                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22975                        break;
22976                    default:
22977                        mMoveCallbacks.notifyStatusChanged(moveId,
22978                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22979                        break;
22980                }
22981            }
22982        };
22983
22984        final MoveInfo move;
22985        if (moveCompleteApp) {
22986            // Kick off a thread to report progress estimates
22987            new Thread() {
22988                @Override
22989                public void run() {
22990                    while (true) {
22991                        try {
22992                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22993                                break;
22994                            }
22995                        } catch (InterruptedException ignored) {
22996                        }
22997
22998                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22999                        final int progress = 10 + (int) MathUtils.constrain(
23000                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23001                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23002                    }
23003                }
23004            }.start();
23005
23006            final String dataAppName = codeFile.getName();
23007            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23008                    dataAppName, appId, seinfo, targetSdkVersion);
23009        } else {
23010            move = null;
23011        }
23012
23013        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23014
23015        final Message msg = mHandler.obtainMessage(INIT_COPY);
23016        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23017        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23018                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23019                packageAbiOverride, null /*grantedPermissions*/,
23020                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
23021        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23022        msg.obj = params;
23023
23024        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23025                System.identityHashCode(msg.obj));
23026        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23027                System.identityHashCode(msg.obj));
23028
23029        mHandler.sendMessage(msg);
23030    }
23031
23032    @Override
23033    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23034        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23035
23036        final int realMoveId = mNextMoveId.getAndIncrement();
23037        final Bundle extras = new Bundle();
23038        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23039        mMoveCallbacks.notifyCreated(realMoveId, extras);
23040
23041        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23042            @Override
23043            public void onCreated(int moveId, Bundle extras) {
23044                // Ignored
23045            }
23046
23047            @Override
23048            public void onStatusChanged(int moveId, int status, long estMillis) {
23049                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23050            }
23051        };
23052
23053        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23054        storage.setPrimaryStorageUuid(volumeUuid, callback);
23055        return realMoveId;
23056    }
23057
23058    @Override
23059    public int getMoveStatus(int moveId) {
23060        mContext.enforceCallingOrSelfPermission(
23061                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23062        return mMoveCallbacks.mLastStatus.get(moveId);
23063    }
23064
23065    @Override
23066    public void registerMoveCallback(IPackageMoveObserver callback) {
23067        mContext.enforceCallingOrSelfPermission(
23068                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23069        mMoveCallbacks.register(callback);
23070    }
23071
23072    @Override
23073    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23074        mContext.enforceCallingOrSelfPermission(
23075                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23076        mMoveCallbacks.unregister(callback);
23077    }
23078
23079    @Override
23080    public boolean setInstallLocation(int loc) {
23081        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23082                null);
23083        if (getInstallLocation() == loc) {
23084            return true;
23085        }
23086        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23087                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23088            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23089                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23090            return true;
23091        }
23092        return false;
23093   }
23094
23095    @Override
23096    public int getInstallLocation() {
23097        // allow instant app access
23098        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23099                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23100                PackageHelper.APP_INSTALL_AUTO);
23101    }
23102
23103    /** Called by UserManagerService */
23104    void cleanUpUser(UserManagerService userManager, int userHandle) {
23105        synchronized (mPackages) {
23106            mDirtyUsers.remove(userHandle);
23107            mUserNeedsBadging.delete(userHandle);
23108            mSettings.removeUserLPw(userHandle);
23109            mPendingBroadcasts.remove(userHandle);
23110            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23111            removeUnusedPackagesLPw(userManager, userHandle);
23112        }
23113    }
23114
23115    /**
23116     * We're removing userHandle and would like to remove any downloaded packages
23117     * that are no longer in use by any other user.
23118     * @param userHandle the user being removed
23119     */
23120    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23121        final boolean DEBUG_CLEAN_APKS = false;
23122        int [] users = userManager.getUserIds();
23123        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23124        while (psit.hasNext()) {
23125            PackageSetting ps = psit.next();
23126            if (ps.pkg == null) {
23127                continue;
23128            }
23129            final String packageName = ps.pkg.packageName;
23130            // Skip over if system app
23131            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23132                continue;
23133            }
23134            if (DEBUG_CLEAN_APKS) {
23135                Slog.i(TAG, "Checking package " + packageName);
23136            }
23137            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23138            if (keep) {
23139                if (DEBUG_CLEAN_APKS) {
23140                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23141                }
23142            } else {
23143                for (int i = 0; i < users.length; i++) {
23144                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23145                        keep = true;
23146                        if (DEBUG_CLEAN_APKS) {
23147                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23148                                    + users[i]);
23149                        }
23150                        break;
23151                    }
23152                }
23153            }
23154            if (!keep) {
23155                if (DEBUG_CLEAN_APKS) {
23156                    Slog.i(TAG, "  Removing package " + packageName);
23157                }
23158                mHandler.post(new Runnable() {
23159                    public void run() {
23160                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23161                                userHandle, 0);
23162                    } //end run
23163                });
23164            }
23165        }
23166    }
23167
23168    /** Called by UserManagerService */
23169    void createNewUser(int userId, String[] disallowedPackages) {
23170        synchronized (mInstallLock) {
23171            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23172        }
23173        synchronized (mPackages) {
23174            scheduleWritePackageRestrictionsLocked(userId);
23175            scheduleWritePackageListLocked(userId);
23176            applyFactoryDefaultBrowserLPw(userId);
23177            primeDomainVerificationsLPw(userId);
23178        }
23179    }
23180
23181    void onNewUserCreated(final int userId) {
23182        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23183        synchronized(mPackages) {
23184            // If permission review for legacy apps is required, we represent
23185            // dagerous permissions for such apps as always granted runtime
23186            // permissions to keep per user flag state whether review is needed.
23187            // Hence, if a new user is added we have to propagate dangerous
23188            // permission grants for these legacy apps.
23189            if (mSettings.mPermissions.mPermissionReviewRequired) {
23190// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23191                mPermissionManager.updateAllPermissions(
23192                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23193                        mPermissionCallback);
23194            }
23195        }
23196    }
23197
23198    @Override
23199    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23200        mContext.enforceCallingOrSelfPermission(
23201                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23202                "Only package verification agents can read the verifier device identity");
23203
23204        synchronized (mPackages) {
23205            return mSettings.getVerifierDeviceIdentityLPw();
23206        }
23207    }
23208
23209    @Override
23210    public void setPermissionEnforced(String permission, boolean enforced) {
23211        // TODO: Now that we no longer change GID for storage, this should to away.
23212        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23213                "setPermissionEnforced");
23214        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23215            synchronized (mPackages) {
23216                if (mSettings.mReadExternalStorageEnforced == null
23217                        || mSettings.mReadExternalStorageEnforced != enforced) {
23218                    mSettings.mReadExternalStorageEnforced =
23219                            enforced ? Boolean.TRUE : Boolean.FALSE;
23220                    mSettings.writeLPr();
23221                }
23222            }
23223            // kill any non-foreground processes so we restart them and
23224            // grant/revoke the GID.
23225            final IActivityManager am = ActivityManager.getService();
23226            if (am != null) {
23227                final long token = Binder.clearCallingIdentity();
23228                try {
23229                    am.killProcessesBelowForeground("setPermissionEnforcement");
23230                } catch (RemoteException e) {
23231                } finally {
23232                    Binder.restoreCallingIdentity(token);
23233                }
23234            }
23235        } else {
23236            throw new IllegalArgumentException("No selective enforcement for " + permission);
23237        }
23238    }
23239
23240    @Override
23241    @Deprecated
23242    public boolean isPermissionEnforced(String permission) {
23243        // allow instant applications
23244        return true;
23245    }
23246
23247    @Override
23248    public boolean isStorageLow() {
23249        // allow instant applications
23250        final long token = Binder.clearCallingIdentity();
23251        try {
23252            final DeviceStorageMonitorInternal
23253                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23254            if (dsm != null) {
23255                return dsm.isMemoryLow();
23256            } else {
23257                return false;
23258            }
23259        } finally {
23260            Binder.restoreCallingIdentity(token);
23261        }
23262    }
23263
23264    @Override
23265    public IPackageInstaller getPackageInstaller() {
23266        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23267            return null;
23268        }
23269        return mInstallerService;
23270    }
23271
23272    @Override
23273    public IArtManager getArtManager() {
23274        return mArtManagerService;
23275    }
23276
23277    private boolean userNeedsBadging(int userId) {
23278        int index = mUserNeedsBadging.indexOfKey(userId);
23279        if (index < 0) {
23280            final UserInfo userInfo;
23281            final long token = Binder.clearCallingIdentity();
23282            try {
23283                userInfo = sUserManager.getUserInfo(userId);
23284            } finally {
23285                Binder.restoreCallingIdentity(token);
23286            }
23287            final boolean b;
23288            if (userInfo != null && userInfo.isManagedProfile()) {
23289                b = true;
23290            } else {
23291                b = false;
23292            }
23293            mUserNeedsBadging.put(userId, b);
23294            return b;
23295        }
23296        return mUserNeedsBadging.valueAt(index);
23297    }
23298
23299    @Override
23300    public KeySet getKeySetByAlias(String packageName, String alias) {
23301        if (packageName == null || alias == null) {
23302            return null;
23303        }
23304        synchronized(mPackages) {
23305            final PackageParser.Package pkg = mPackages.get(packageName);
23306            if (pkg == null) {
23307                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23308                throw new IllegalArgumentException("Unknown package: " + packageName);
23309            }
23310            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23311            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23312                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23313                throw new IllegalArgumentException("Unknown package: " + packageName);
23314            }
23315            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23316            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23317        }
23318    }
23319
23320    @Override
23321    public KeySet getSigningKeySet(String packageName) {
23322        if (packageName == null) {
23323            return null;
23324        }
23325        synchronized(mPackages) {
23326            final int callingUid = Binder.getCallingUid();
23327            final int callingUserId = UserHandle.getUserId(callingUid);
23328            final PackageParser.Package pkg = mPackages.get(packageName);
23329            if (pkg == null) {
23330                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23331                throw new IllegalArgumentException("Unknown package: " + packageName);
23332            }
23333            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23334            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23335                // filter and pretend the package doesn't exist
23336                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23337                        + ", uid:" + callingUid);
23338                throw new IllegalArgumentException("Unknown package: " + packageName);
23339            }
23340            if (pkg.applicationInfo.uid != callingUid
23341                    && Process.SYSTEM_UID != callingUid) {
23342                throw new SecurityException("May not access signing KeySet of other apps.");
23343            }
23344            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23345            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23346        }
23347    }
23348
23349    @Override
23350    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23351        final int callingUid = Binder.getCallingUid();
23352        if (getInstantAppPackageName(callingUid) != null) {
23353            return false;
23354        }
23355        if (packageName == null || ks == null) {
23356            return false;
23357        }
23358        synchronized(mPackages) {
23359            final PackageParser.Package pkg = mPackages.get(packageName);
23360            if (pkg == null
23361                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23362                            UserHandle.getUserId(callingUid))) {
23363                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23364                throw new IllegalArgumentException("Unknown package: " + packageName);
23365            }
23366            IBinder ksh = ks.getToken();
23367            if (ksh instanceof KeySetHandle) {
23368                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23369                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23370            }
23371            return false;
23372        }
23373    }
23374
23375    @Override
23376    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23377        final int callingUid = Binder.getCallingUid();
23378        if (getInstantAppPackageName(callingUid) != null) {
23379            return false;
23380        }
23381        if (packageName == null || ks == null) {
23382            return false;
23383        }
23384        synchronized(mPackages) {
23385            final PackageParser.Package pkg = mPackages.get(packageName);
23386            if (pkg == null
23387                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23388                            UserHandle.getUserId(callingUid))) {
23389                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23390                throw new IllegalArgumentException("Unknown package: " + packageName);
23391            }
23392            IBinder ksh = ks.getToken();
23393            if (ksh instanceof KeySetHandle) {
23394                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23395                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23396            }
23397            return false;
23398        }
23399    }
23400
23401    private void deletePackageIfUnusedLPr(final String packageName) {
23402        PackageSetting ps = mSettings.mPackages.get(packageName);
23403        if (ps == null) {
23404            return;
23405        }
23406        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23407            // TODO Implement atomic delete if package is unused
23408            // It is currently possible that the package will be deleted even if it is installed
23409            // after this method returns.
23410            mHandler.post(new Runnable() {
23411                public void run() {
23412                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23413                            0, PackageManager.DELETE_ALL_USERS);
23414                }
23415            });
23416        }
23417    }
23418
23419    /**
23420     * Check and throw if the given before/after packages would be considered a
23421     * downgrade.
23422     */
23423    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23424            throws PackageManagerException {
23425        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23426            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23427                    "Update version code " + after.versionCode + " is older than current "
23428                    + before.getLongVersionCode());
23429        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23430            if (after.baseRevisionCode < before.baseRevisionCode) {
23431                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23432                        "Update base revision code " + after.baseRevisionCode
23433                        + " is older than current " + before.baseRevisionCode);
23434            }
23435
23436            if (!ArrayUtils.isEmpty(after.splitNames)) {
23437                for (int i = 0; i < after.splitNames.length; i++) {
23438                    final String splitName = after.splitNames[i];
23439                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23440                    if (j != -1) {
23441                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23442                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23443                                    "Update split " + splitName + " revision code "
23444                                    + after.splitRevisionCodes[i] + " is older than current "
23445                                    + before.splitRevisionCodes[j]);
23446                        }
23447                    }
23448                }
23449            }
23450        }
23451    }
23452
23453    private static class MoveCallbacks extends Handler {
23454        private static final int MSG_CREATED = 1;
23455        private static final int MSG_STATUS_CHANGED = 2;
23456
23457        private final RemoteCallbackList<IPackageMoveObserver>
23458                mCallbacks = new RemoteCallbackList<>();
23459
23460        private final SparseIntArray mLastStatus = new SparseIntArray();
23461
23462        public MoveCallbacks(Looper looper) {
23463            super(looper);
23464        }
23465
23466        public void register(IPackageMoveObserver callback) {
23467            mCallbacks.register(callback);
23468        }
23469
23470        public void unregister(IPackageMoveObserver callback) {
23471            mCallbacks.unregister(callback);
23472        }
23473
23474        @Override
23475        public void handleMessage(Message msg) {
23476            final SomeArgs args = (SomeArgs) msg.obj;
23477            final int n = mCallbacks.beginBroadcast();
23478            for (int i = 0; i < n; i++) {
23479                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23480                try {
23481                    invokeCallback(callback, msg.what, args);
23482                } catch (RemoteException ignored) {
23483                }
23484            }
23485            mCallbacks.finishBroadcast();
23486            args.recycle();
23487        }
23488
23489        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23490                throws RemoteException {
23491            switch (what) {
23492                case MSG_CREATED: {
23493                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23494                    break;
23495                }
23496                case MSG_STATUS_CHANGED: {
23497                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23498                    break;
23499                }
23500            }
23501        }
23502
23503        private void notifyCreated(int moveId, Bundle extras) {
23504            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23505
23506            final SomeArgs args = SomeArgs.obtain();
23507            args.argi1 = moveId;
23508            args.arg2 = extras;
23509            obtainMessage(MSG_CREATED, args).sendToTarget();
23510        }
23511
23512        private void notifyStatusChanged(int moveId, int status) {
23513            notifyStatusChanged(moveId, status, -1);
23514        }
23515
23516        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23517            Slog.v(TAG, "Move " + moveId + " status " + status);
23518
23519            final SomeArgs args = SomeArgs.obtain();
23520            args.argi1 = moveId;
23521            args.argi2 = status;
23522            args.arg3 = estMillis;
23523            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23524
23525            synchronized (mLastStatus) {
23526                mLastStatus.put(moveId, status);
23527            }
23528        }
23529    }
23530
23531    private final static class OnPermissionChangeListeners extends Handler {
23532        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23533
23534        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23535                new RemoteCallbackList<>();
23536
23537        public OnPermissionChangeListeners(Looper looper) {
23538            super(looper);
23539        }
23540
23541        @Override
23542        public void handleMessage(Message msg) {
23543            switch (msg.what) {
23544                case MSG_ON_PERMISSIONS_CHANGED: {
23545                    final int uid = msg.arg1;
23546                    handleOnPermissionsChanged(uid);
23547                } break;
23548            }
23549        }
23550
23551        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23552            mPermissionListeners.register(listener);
23553
23554        }
23555
23556        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23557            mPermissionListeners.unregister(listener);
23558        }
23559
23560        public void onPermissionsChanged(int uid) {
23561            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23562                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23563            }
23564        }
23565
23566        private void handleOnPermissionsChanged(int uid) {
23567            final int count = mPermissionListeners.beginBroadcast();
23568            try {
23569                for (int i = 0; i < count; i++) {
23570                    IOnPermissionsChangeListener callback = mPermissionListeners
23571                            .getBroadcastItem(i);
23572                    try {
23573                        callback.onPermissionsChanged(uid);
23574                    } catch (RemoteException e) {
23575                        Log.e(TAG, "Permission listener is dead", e);
23576                    }
23577                }
23578            } finally {
23579                mPermissionListeners.finishBroadcast();
23580            }
23581        }
23582    }
23583
23584    private class PackageManagerNative extends IPackageManagerNative.Stub {
23585        @Override
23586        public String[] getNamesForUids(int[] uids) throws RemoteException {
23587            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23588            // massage results so they can be parsed by the native binder
23589            for (int i = results.length - 1; i >= 0; --i) {
23590                if (results[i] == null) {
23591                    results[i] = "";
23592                }
23593            }
23594            return results;
23595        }
23596
23597        // NB: this differentiates between preloads and sideloads
23598        @Override
23599        public String getInstallerForPackage(String packageName) throws RemoteException {
23600            final String installerName = getInstallerPackageName(packageName);
23601            if (!TextUtils.isEmpty(installerName)) {
23602                return installerName;
23603            }
23604            // differentiate between preload and sideload
23605            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23606            ApplicationInfo appInfo = getApplicationInfo(packageName,
23607                                    /*flags*/ 0,
23608                                    /*userId*/ callingUser);
23609            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23610                return "preload";
23611            }
23612            return "";
23613        }
23614
23615        @Override
23616        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23617            try {
23618                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23619                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23620                if (pInfo != null) {
23621                    return pInfo.getLongVersionCode();
23622                }
23623            } catch (Exception e) {
23624            }
23625            return 0;
23626        }
23627    }
23628
23629    private class PackageManagerInternalImpl extends PackageManagerInternal {
23630        @Override
23631        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23632                int flagValues, int userId) {
23633            PackageManagerService.this.updatePermissionFlags(
23634                    permName, packageName, flagMask, flagValues, userId);
23635        }
23636
23637        @Override
23638        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23639            SigningDetails sd = getSigningDetails(packageName);
23640            if (sd == null) {
23641                return false;
23642            }
23643            return sd.hasSha256Certificate(restoringFromSigHash,
23644                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23645        }
23646
23647        @Override
23648        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23649            SigningDetails sd = getSigningDetails(packageName);
23650            if (sd == null) {
23651                return false;
23652            }
23653            return sd.hasCertificate(restoringFromSig,
23654                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23655        }
23656
23657        @Override
23658        public boolean hasSignatureCapability(int serverUid, int clientUid,
23659                @SigningDetails.CertCapabilities int capability) {
23660            SigningDetails serverSigningDetails = getSigningDetails(serverUid);
23661            SigningDetails clientSigningDetails = getSigningDetails(clientUid);
23662            return serverSigningDetails.checkCapability(clientSigningDetails, capability)
23663                    || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
23664
23665        }
23666
23667        private SigningDetails getSigningDetails(@NonNull String packageName) {
23668            synchronized (mPackages) {
23669                PackageParser.Package p = mPackages.get(packageName);
23670                if (p == null) {
23671                    return null;
23672                }
23673                return p.mSigningDetails;
23674            }
23675        }
23676
23677        private SigningDetails getSigningDetails(int uid) {
23678            synchronized (mPackages) {
23679                final int appId = UserHandle.getAppId(uid);
23680                final Object obj = mSettings.getUserIdLPr(appId);
23681                if (obj != null) {
23682                    if (obj instanceof SharedUserSetting) {
23683                        return ((SharedUserSetting) obj).signatures.mSigningDetails;
23684                    } else if (obj instanceof PackageSetting) {
23685                        final PackageSetting ps = (PackageSetting) obj;
23686                        return ps.signatures.mSigningDetails;
23687                    }
23688                }
23689                return SigningDetails.UNKNOWN;
23690            }
23691        }
23692
23693        @Override
23694        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23695            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23696        }
23697
23698        @Override
23699        public boolean isInstantApp(String packageName, int userId) {
23700            return PackageManagerService.this.isInstantApp(packageName, userId);
23701        }
23702
23703        @Override
23704        public String getInstantAppPackageName(int uid) {
23705            return PackageManagerService.this.getInstantAppPackageName(uid);
23706        }
23707
23708        @Override
23709        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23710            synchronized (mPackages) {
23711                return PackageManagerService.this.filterAppAccessLPr(
23712                        (PackageSetting) pkg.mExtras, callingUid, userId);
23713            }
23714        }
23715
23716        @Override
23717        public PackageParser.Package getPackage(String packageName) {
23718            synchronized (mPackages) {
23719                packageName = resolveInternalPackageNameLPr(
23720                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23721                return mPackages.get(packageName);
23722            }
23723        }
23724
23725        @Override
23726        public PackageList getPackageList(PackageListObserver observer) {
23727            synchronized (mPackages) {
23728                final int N = mPackages.size();
23729                final ArrayList<String> list = new ArrayList<>(N);
23730                for (int i = 0; i < N; i++) {
23731                    list.add(mPackages.keyAt(i));
23732                }
23733                final PackageList packageList = new PackageList(list, observer);
23734                if (observer != null) {
23735                    mPackageListObservers.add(packageList);
23736                }
23737                return packageList;
23738            }
23739        }
23740
23741        @Override
23742        public void removePackageListObserver(PackageListObserver observer) {
23743            synchronized (mPackages) {
23744                mPackageListObservers.remove(observer);
23745            }
23746        }
23747
23748        @Override
23749        public PackageParser.Package getDisabledPackage(String packageName) {
23750            synchronized (mPackages) {
23751                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23752                return (ps != null) ? ps.pkg : null;
23753            }
23754        }
23755
23756        @Override
23757        public String getKnownPackageName(int knownPackage, int userId) {
23758            switch(knownPackage) {
23759                case PackageManagerInternal.PACKAGE_BROWSER:
23760                    return getDefaultBrowserPackageName(userId);
23761                case PackageManagerInternal.PACKAGE_INSTALLER:
23762                    return mRequiredInstallerPackage;
23763                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23764                    return mSetupWizardPackage;
23765                case PackageManagerInternal.PACKAGE_SYSTEM:
23766                    return "android";
23767                case PackageManagerInternal.PACKAGE_VERIFIER:
23768                    return mRequiredVerifierPackage;
23769                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23770                    return mSystemTextClassifierPackage;
23771            }
23772            return null;
23773        }
23774
23775        @Override
23776        public boolean isResolveActivityComponent(ComponentInfo component) {
23777            return mResolveActivity.packageName.equals(component.packageName)
23778                    && mResolveActivity.name.equals(component.name);
23779        }
23780
23781        @Override
23782        public void setLocationPackagesProvider(PackagesProvider provider) {
23783            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23784        }
23785
23786        @Override
23787        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23788            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23789        }
23790
23791        @Override
23792        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23793            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23794        }
23795
23796        @Override
23797        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23798            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23799        }
23800
23801        @Override
23802        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23803            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23804        }
23805
23806        @Override
23807        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23808            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23809        }
23810
23811        @Override
23812        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23813            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23814        }
23815
23816        @Override
23817        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23818            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23819        }
23820
23821        @Override
23822        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23823            synchronized (mPackages) {
23824                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23825            }
23826            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23827        }
23828
23829        @Override
23830        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23831            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23832                    packageName, userId);
23833        }
23834
23835        @Override
23836        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23837            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23838                    packageName, userId);
23839        }
23840
23841        @Override
23842        public void setKeepUninstalledPackages(final List<String> packageList) {
23843            Preconditions.checkNotNull(packageList);
23844            List<String> removedFromList = null;
23845            synchronized (mPackages) {
23846                if (mKeepUninstalledPackages != null) {
23847                    final int packagesCount = mKeepUninstalledPackages.size();
23848                    for (int i = 0; i < packagesCount; i++) {
23849                        String oldPackage = mKeepUninstalledPackages.get(i);
23850                        if (packageList != null && packageList.contains(oldPackage)) {
23851                            continue;
23852                        }
23853                        if (removedFromList == null) {
23854                            removedFromList = new ArrayList<>();
23855                        }
23856                        removedFromList.add(oldPackage);
23857                    }
23858                }
23859                mKeepUninstalledPackages = new ArrayList<>(packageList);
23860                if (removedFromList != null) {
23861                    final int removedCount = removedFromList.size();
23862                    for (int i = 0; i < removedCount; i++) {
23863                        deletePackageIfUnusedLPr(removedFromList.get(i));
23864                    }
23865                }
23866            }
23867        }
23868
23869        @Override
23870        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23871            synchronized (mPackages) {
23872                return mPermissionManager.isPermissionsReviewRequired(
23873                        mPackages.get(packageName), userId);
23874            }
23875        }
23876
23877        @Override
23878        public PackageInfo getPackageInfo(
23879                String packageName, int flags, int filterCallingUid, int userId) {
23880            return PackageManagerService.this
23881                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23882                            flags, filterCallingUid, userId);
23883        }
23884
23885        @Override
23886        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23887            synchronized (mPackages) {
23888                final PackageSetting ps = mSettings.mPackages.get(packageName);
23889                PersistableBundle launcherExtras = null;
23890                if (ps != null) {
23891                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23892                }
23893                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23894            }
23895        }
23896
23897        @Override
23898        public boolean isPackageSuspended(String packageName, int userId) {
23899            synchronized (mPackages) {
23900                final PackageSetting ps = mSettings.mPackages.get(packageName);
23901                return (ps != null) ? ps.getSuspended(userId) : false;
23902            }
23903        }
23904
23905        @Override
23906        public String getSuspendingPackage(String suspendedPackage, int userId) {
23907            synchronized (mPackages) {
23908                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23909                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
23910            }
23911        }
23912
23913        @Override
23914        public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
23915            synchronized (mPackages) {
23916                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23917                return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
23918            }
23919        }
23920
23921        @Override
23922        public int getPackageUid(String packageName, int flags, int userId) {
23923            return PackageManagerService.this
23924                    .getPackageUid(packageName, flags, userId);
23925        }
23926
23927        @Override
23928        public ApplicationInfo getApplicationInfo(
23929                String packageName, int flags, int filterCallingUid, int userId) {
23930            return PackageManagerService.this
23931                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23932        }
23933
23934        @Override
23935        public ActivityInfo getActivityInfo(
23936                ComponentName component, int flags, int filterCallingUid, int userId) {
23937            return PackageManagerService.this
23938                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23939        }
23940
23941        @Override
23942        public List<ResolveInfo> queryIntentActivities(
23943                Intent intent, int flags, int filterCallingUid, int userId) {
23944            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23945            return PackageManagerService.this
23946                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23947                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23948        }
23949
23950        @Override
23951        public List<ResolveInfo> queryIntentServices(
23952                Intent intent, int flags, int callingUid, int userId) {
23953            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23954            return PackageManagerService.this
23955                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23956                            false);
23957        }
23958
23959        @Override
23960        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23961                int userId) {
23962            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23963        }
23964
23965        @Override
23966        public ComponentName getDefaultHomeActivity(int userId) {
23967            return PackageManagerService.this.getDefaultHomeActivity(userId);
23968        }
23969
23970        @Override
23971        public void setDeviceAndProfileOwnerPackages(
23972                int deviceOwnerUserId, String deviceOwnerPackage,
23973                SparseArray<String> profileOwnerPackages) {
23974            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23975                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23976        }
23977
23978        @Override
23979        public boolean isPackageDataProtected(int userId, String packageName) {
23980            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23981        }
23982
23983        @Override
23984        public boolean isPackageStateProtected(String packageName, int userId) {
23985            return mProtectedPackages.isPackageStateProtected(userId, packageName);
23986        }
23987
23988        @Override
23989        public boolean isPackageEphemeral(int userId, String packageName) {
23990            synchronized (mPackages) {
23991                final PackageSetting ps = mSettings.mPackages.get(packageName);
23992                return ps != null ? ps.getInstantApp(userId) : false;
23993            }
23994        }
23995
23996        @Override
23997        public boolean wasPackageEverLaunched(String packageName, int userId) {
23998            synchronized (mPackages) {
23999                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24000            }
24001        }
24002
24003        @Override
24004        public void grantRuntimePermission(String packageName, String permName, int userId,
24005                boolean overridePolicy) {
24006            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
24007                    permName, packageName, overridePolicy, getCallingUid(), userId,
24008                    mPermissionCallback);
24009        }
24010
24011        @Override
24012        public void revokeRuntimePermission(String packageName, String permName, int userId,
24013                boolean overridePolicy) {
24014            mPermissionManager.revokeRuntimePermission(
24015                    permName, packageName, overridePolicy, getCallingUid(), userId,
24016                    mPermissionCallback);
24017        }
24018
24019        @Override
24020        public String getNameForUid(int uid) {
24021            return PackageManagerService.this.getNameForUid(uid);
24022        }
24023
24024        @Override
24025        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24026                Intent origIntent, String resolvedType, String callingPackage,
24027                Bundle verificationBundle, int userId) {
24028            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24029                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24030                    userId);
24031        }
24032
24033        @Override
24034        public void grantEphemeralAccess(int userId, Intent intent,
24035                int targetAppId, int ephemeralAppId) {
24036            synchronized (mPackages) {
24037                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24038                        targetAppId, ephemeralAppId);
24039            }
24040        }
24041
24042        @Override
24043        public boolean isInstantAppInstallerComponent(ComponentName component) {
24044            synchronized (mPackages) {
24045                return mInstantAppInstallerActivity != null
24046                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24047            }
24048        }
24049
24050        @Override
24051        public void pruneInstantApps() {
24052            mInstantAppRegistry.pruneInstantApps();
24053        }
24054
24055        @Override
24056        public String getSetupWizardPackageName() {
24057            return mSetupWizardPackage;
24058        }
24059
24060        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24061            if (policy != null) {
24062                mExternalSourcesPolicy = policy;
24063            }
24064        }
24065
24066        @Override
24067        public boolean isPackagePersistent(String packageName) {
24068            synchronized (mPackages) {
24069                PackageParser.Package pkg = mPackages.get(packageName);
24070                return pkg != null
24071                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24072                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24073                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24074                        : false;
24075            }
24076        }
24077
24078        @Override
24079        public boolean isLegacySystemApp(Package pkg) {
24080            synchronized (mPackages) {
24081                final PackageSetting ps = (PackageSetting) pkg.mExtras;
24082                return mPromoteSystemApps
24083                        && ps.isSystem()
24084                        && mExistingSystemPackages.contains(ps.name);
24085            }
24086        }
24087
24088        @Override
24089        public List<PackageInfo> getOverlayPackages(int userId) {
24090            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24091            synchronized (mPackages) {
24092                for (PackageParser.Package p : mPackages.values()) {
24093                    if (p.mOverlayTarget != null) {
24094                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24095                        if (pkg != null) {
24096                            overlayPackages.add(pkg);
24097                        }
24098                    }
24099                }
24100            }
24101            return overlayPackages;
24102        }
24103
24104        @Override
24105        public List<String> getTargetPackageNames(int userId) {
24106            List<String> targetPackages = new ArrayList<>();
24107            synchronized (mPackages) {
24108                for (PackageParser.Package p : mPackages.values()) {
24109                    if (p.mOverlayTarget == null) {
24110                        targetPackages.add(p.packageName);
24111                    }
24112                }
24113            }
24114            return targetPackages;
24115        }
24116
24117        @Override
24118        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24119                @Nullable List<String> overlayPackageNames) {
24120            synchronized (mPackages) {
24121                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24122                    Slog.e(TAG, "failed to find package " + targetPackageName);
24123                    return false;
24124                }
24125                ArrayList<String> overlayPaths = null;
24126                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24127                    final int N = overlayPackageNames.size();
24128                    overlayPaths = new ArrayList<>(N);
24129                    for (int i = 0; i < N; i++) {
24130                        final String packageName = overlayPackageNames.get(i);
24131                        final PackageParser.Package pkg = mPackages.get(packageName);
24132                        if (pkg == null) {
24133                            Slog.e(TAG, "failed to find package " + packageName);
24134                            return false;
24135                        }
24136                        overlayPaths.add(pkg.baseCodePath);
24137                    }
24138                }
24139
24140                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24141                ps.setOverlayPaths(overlayPaths, userId);
24142                return true;
24143            }
24144        }
24145
24146        @Override
24147        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24148                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24149            return resolveIntentInternal(
24150                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24151        }
24152
24153        @Override
24154        public ResolveInfo resolveService(Intent intent, String resolvedType,
24155                int flags, int userId, int callingUid) {
24156            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24157        }
24158
24159        @Override
24160        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24161            return PackageManagerService.this.resolveContentProviderInternal(
24162                    name, flags, userId);
24163        }
24164
24165        @Override
24166        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24167            synchronized (mPackages) {
24168                mIsolatedOwners.put(isolatedUid, ownerUid);
24169            }
24170        }
24171
24172        @Override
24173        public void removeIsolatedUid(int isolatedUid) {
24174            synchronized (mPackages) {
24175                mIsolatedOwners.delete(isolatedUid);
24176            }
24177        }
24178
24179        @Override
24180        public int getUidTargetSdkVersion(int uid) {
24181            synchronized (mPackages) {
24182                return getUidTargetSdkVersionLockedLPr(uid);
24183            }
24184        }
24185
24186        @Override
24187        public int getPackageTargetSdkVersion(String packageName) {
24188            synchronized (mPackages) {
24189                return getPackageTargetSdkVersionLockedLPr(packageName);
24190            }
24191        }
24192
24193        @Override
24194        public boolean canAccessInstantApps(int callingUid, int userId) {
24195            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24196        }
24197
24198        @Override
24199        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24200            synchronized (mPackages) {
24201                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24202                return !PackageManagerService.this.filterAppAccessLPr(
24203                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24204            }
24205        }
24206
24207        @Override
24208        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24209            synchronized (mPackages) {
24210                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24211            }
24212        }
24213
24214        @Override
24215        public void notifyPackageUse(String packageName, int reason) {
24216            synchronized (mPackages) {
24217                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24218            }
24219        }
24220    }
24221
24222    @Override
24223    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24224        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24225        synchronized (mPackages) {
24226            final long identity = Binder.clearCallingIdentity();
24227            try {
24228                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24229                        packageNames, userId);
24230            } finally {
24231                Binder.restoreCallingIdentity(identity);
24232            }
24233        }
24234    }
24235
24236    @Override
24237    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24238        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24239        synchronized (mPackages) {
24240            final long identity = Binder.clearCallingIdentity();
24241            try {
24242                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24243                        packageNames, userId);
24244            } finally {
24245                Binder.restoreCallingIdentity(identity);
24246            }
24247        }
24248    }
24249
24250    @Override
24251    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24252            String[] packageNames, int userId) {
24253        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24254        synchronized (mPackages) {
24255            Binder.withCleanCallingIdentity( () -> {
24256                mDefaultPermissionPolicy.
24257                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24258                                packageNames, userId);
24259            });
24260        }
24261    }
24262
24263    @Override
24264    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24265            String[] packageNames, int userId) {
24266        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24267        synchronized (mPackages) {
24268            Binder.withCleanCallingIdentity( () -> {
24269                mDefaultPermissionPolicy.
24270                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24271                                packageNames, userId);
24272            });
24273        }
24274    }
24275
24276    @Override
24277    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24278        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24279        synchronized (mPackages) {
24280            final long identity = Binder.clearCallingIdentity();
24281            try {
24282                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24283                        packageName, userId);
24284            } finally {
24285                Binder.restoreCallingIdentity(identity);
24286            }
24287        }
24288    }
24289
24290    @Override
24291    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24292        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24293        synchronized (mPackages) {
24294            final long identity = Binder.clearCallingIdentity();
24295            try {
24296                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24297            } finally {
24298                Binder.restoreCallingIdentity(identity);
24299            }
24300        }
24301    }
24302
24303    private static void enforceSystemOrPhoneCaller(String tag) {
24304        int callingUid = Binder.getCallingUid();
24305        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24306            throw new SecurityException(
24307                    "Cannot call " + tag + " from UID " + callingUid);
24308        }
24309    }
24310
24311    boolean isHistoricalPackageUsageAvailable() {
24312        return mPackageUsage.isHistoricalPackageUsageAvailable();
24313    }
24314
24315    /**
24316     * Return a <b>copy</b> of the collection of packages known to the package manager.
24317     * @return A copy of the values of mPackages.
24318     */
24319    Collection<PackageParser.Package> getPackages() {
24320        synchronized (mPackages) {
24321            return new ArrayList<>(mPackages.values());
24322        }
24323    }
24324
24325    /**
24326     * Logs process start information (including base APK hash) to the security log.
24327     * @hide
24328     */
24329    @Override
24330    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24331            String apkFile, int pid) {
24332        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24333            return;
24334        }
24335        if (!SecurityLog.isLoggingEnabled()) {
24336            return;
24337        }
24338        Bundle data = new Bundle();
24339        data.putLong("startTimestamp", System.currentTimeMillis());
24340        data.putString("processName", processName);
24341        data.putInt("uid", uid);
24342        data.putString("seinfo", seinfo);
24343        data.putString("apkFile", apkFile);
24344        data.putInt("pid", pid);
24345        Message msg = mProcessLoggingHandler.obtainMessage(
24346                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24347        msg.setData(data);
24348        mProcessLoggingHandler.sendMessage(msg);
24349    }
24350
24351    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24352        return mCompilerStats.getPackageStats(pkgName);
24353    }
24354
24355    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24356        return getOrCreateCompilerPackageStats(pkg.packageName);
24357    }
24358
24359    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24360        return mCompilerStats.getOrCreatePackageStats(pkgName);
24361    }
24362
24363    public void deleteCompilerPackageStats(String pkgName) {
24364        mCompilerStats.deletePackageStats(pkgName);
24365    }
24366
24367    @Override
24368    public int getInstallReason(String packageName, int userId) {
24369        final int callingUid = Binder.getCallingUid();
24370        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24371                true /* requireFullPermission */, false /* checkShell */,
24372                "get install reason");
24373        synchronized (mPackages) {
24374            final PackageSetting ps = mSettings.mPackages.get(packageName);
24375            if (filterAppAccessLPr(ps, callingUid, userId)) {
24376                return PackageManager.INSTALL_REASON_UNKNOWN;
24377            }
24378            if (ps != null) {
24379                return ps.getInstallReason(userId);
24380            }
24381        }
24382        return PackageManager.INSTALL_REASON_UNKNOWN;
24383    }
24384
24385    @Override
24386    public boolean canRequestPackageInstalls(String packageName, int userId) {
24387        return canRequestPackageInstallsInternal(packageName, 0, userId,
24388                true /* throwIfPermNotDeclared*/);
24389    }
24390
24391    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24392            boolean throwIfPermNotDeclared) {
24393        int callingUid = Binder.getCallingUid();
24394        int uid = getPackageUid(packageName, 0, userId);
24395        if (callingUid != uid && callingUid != Process.ROOT_UID
24396                && callingUid != Process.SYSTEM_UID) {
24397            throw new SecurityException(
24398                    "Caller uid " + callingUid + " does not own package " + packageName);
24399        }
24400        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24401        if (info == null) {
24402            return false;
24403        }
24404        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24405            return false;
24406        }
24407        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24408        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24409        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24410            if (throwIfPermNotDeclared) {
24411                throw new SecurityException("Need to declare " + appOpPermission
24412                        + " to call this api");
24413            } else {
24414                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24415                return false;
24416            }
24417        }
24418        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24419            return false;
24420        }
24421        if (mExternalSourcesPolicy != null) {
24422            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24423            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24424                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24425            }
24426        }
24427        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24428    }
24429
24430    @Override
24431    public ComponentName getInstantAppResolverSettingsComponent() {
24432        return mInstantAppResolverSettingsComponent;
24433    }
24434
24435    @Override
24436    public ComponentName getInstantAppInstallerComponent() {
24437        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24438            return null;
24439        }
24440        return mInstantAppInstallerActivity == null
24441                ? null : mInstantAppInstallerActivity.getComponentName();
24442    }
24443
24444    @Override
24445    public String getInstantAppAndroidId(String packageName, int userId) {
24446        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24447                "getInstantAppAndroidId");
24448        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24449                true /* requireFullPermission */, false /* checkShell */,
24450                "getInstantAppAndroidId");
24451        // Make sure the target is an Instant App.
24452        if (!isInstantApp(packageName, userId)) {
24453            return null;
24454        }
24455        synchronized (mPackages) {
24456            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24457        }
24458    }
24459
24460    boolean canHaveOatDir(String packageName) {
24461        synchronized (mPackages) {
24462            PackageParser.Package p = mPackages.get(packageName);
24463            if (p == null) {
24464                return false;
24465            }
24466            return p.canHaveOatDir();
24467        }
24468    }
24469
24470    private String getOatDir(PackageParser.Package pkg) {
24471        if (!pkg.canHaveOatDir()) {
24472            return null;
24473        }
24474        File codePath = new File(pkg.codePath);
24475        if (codePath.isDirectory()) {
24476            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24477        }
24478        return null;
24479    }
24480
24481    void deleteOatArtifactsOfPackage(String packageName) {
24482        final String[] instructionSets;
24483        final List<String> codePaths;
24484        final String oatDir;
24485        final PackageParser.Package pkg;
24486        synchronized (mPackages) {
24487            pkg = mPackages.get(packageName);
24488        }
24489        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24490        codePaths = pkg.getAllCodePaths();
24491        oatDir = getOatDir(pkg);
24492
24493        for (String codePath : codePaths) {
24494            for (String isa : instructionSets) {
24495                try {
24496                    mInstaller.deleteOdex(codePath, isa, oatDir);
24497                } catch (InstallerException e) {
24498                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24499                }
24500            }
24501        }
24502    }
24503
24504    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24505        Set<String> unusedPackages = new HashSet<>();
24506        long currentTimeInMillis = System.currentTimeMillis();
24507        synchronized (mPackages) {
24508            for (PackageParser.Package pkg : mPackages.values()) {
24509                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24510                if (ps == null) {
24511                    continue;
24512                }
24513                PackageDexUsage.PackageUseInfo packageUseInfo =
24514                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24515                if (PackageManagerServiceUtils
24516                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24517                                downgradeTimeThresholdMillis, packageUseInfo,
24518                                pkg.getLatestPackageUseTimeInMills(),
24519                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24520                    unusedPackages.add(pkg.packageName);
24521                }
24522            }
24523        }
24524        return unusedPackages;
24525    }
24526
24527    @Override
24528    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24529            int userId) {
24530        final int callingUid = Binder.getCallingUid();
24531        final int callingAppId = UserHandle.getAppId(callingUid);
24532
24533        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24534                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24535
24536        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24537                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24538            throw new SecurityException("Caller must have the "
24539                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24540        }
24541
24542        synchronized(mPackages) {
24543            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24544            scheduleWritePackageRestrictionsLocked(userId);
24545        }
24546    }
24547
24548    @Nullable
24549    @Override
24550    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24551        final int callingUid = Binder.getCallingUid();
24552        final int callingAppId = UserHandle.getAppId(callingUid);
24553
24554        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24555                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24556
24557        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24558                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24559            throw new SecurityException("Caller must have the "
24560                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24561        }
24562
24563        synchronized(mPackages) {
24564            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24565        }
24566    }
24567
24568    @Override
24569    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24570        final int callingUid = Binder.getCallingUid();
24571        final int callingAppId = UserHandle.getAppId(callingUid);
24572
24573        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24574                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24575
24576        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24577                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24578            throw new SecurityException("Caller must have the "
24579                    + MANAGE_DEVICE_ADMINS + " permission.");
24580        }
24581
24582        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24583    }
24584}
24585
24586interface PackageSender {
24587    /**
24588     * @param userIds User IDs where the action occurred on a full application
24589     * @param instantUserIds User IDs where the action occurred on an instant application
24590     */
24591    void sendPackageBroadcast(final String action, final String pkg,
24592        final Bundle extras, final int flags, final String targetPkg,
24593        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24594    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24595        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24596    void notifyPackageAdded(String packageName);
24597    void notifyPackageRemoved(String packageName);
24598}
24599