下面列出了android.content.pm.PackageUserState#android.content.pm.PackageParser 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public byte[] getInstantAppCookieLPw(@NonNull String packageName,
@UserIdInt int userId) {
// Only installed packages can get their own cookie
PackageParser.Package pkg = mService.mPackages.get(packageName);
if (pkg == null) {
return null;
}
byte[] pendingCookie = mCookiePersistence.getPendingPersistCookieLPr(pkg, userId);
if (pendingCookie != null) {
return pendingCookie;
}
File cookieFile = peekInstantCookieFile(packageName, userId);
if (cookieFile != null && cookieFile.exists()) {
try {
return IoUtils.readFileAsByteArray(cookieFile.toString());
} catch (IOException e) {
Slog.w(LOG_TAG, "Error reading cookie file: " + cookieFile);
}
}
return null;
}
/** Add all components defined in the given package to the internal structures. */
void addAllComponents(PackageParser.Package pkg, boolean chatty) {
final ArrayList<PackageParser.ActivityIntentInfo> newIntents = new ArrayList<>();
synchronized (mLock) {
addActivitiesLocked(pkg, newIntents, chatty);
addReceiversLocked(pkg, chatty);
addProvidersLocked(pkg, chatty);
addServicesLocked(pkg, chatty);
}
final String setupWizardPackage = sPackageManagerInternal.getKnownPackageName(
PACKAGE_SETUP_WIZARD, UserHandle.USER_SYSTEM);
for (int i = newIntents.size() - 1; i >= 0; --i) {
final PackageParser.ActivityIntentInfo intentInfo = newIntents.get(i);
final PackageParser.Package disabledPkg = sPackageManagerInternal
.getDisabledSystemPackage(intentInfo.activity.info.packageName);
final List<PackageParser.Activity> systemActivities =
disabledPkg != null ? disabledPkg.activities : null;
adjustPriority(systemActivities, intentInfo, setupWizardPackage);
}
}
@GuardedBy("mLock")
private void addReceiversLocked(PackageParser.Package pkg, boolean chatty) {
final int receiversSize = pkg.receivers.size();
StringBuilder r = null;
for (int i = 0; i < receiversSize; i++) {
PackageParser.Activity a = pkg.receivers.get(i);
a.info.processName = fixProcessName(pkg.applicationInfo.processName,
a.info.processName);
mReceivers.addActivity(a, "receiver", null);
if (DEBUG_PACKAGE_SCANNING && chatty) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (DEBUG_PACKAGE_SCANNING && chatty) {
Log.d(TAG, " Receivers: " + (r == null ? "<NONE>" : r));
}
}
private void removeActivity(PackageParser.Activity a, String type) {
mActivities.remove(a.getComponentName());
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " " + type + " "
+ (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
: a.info.name) + ":");
Log.v(TAG, " Class=" + a.info.name);
}
final int intentsSize = a.intents.size();
for (int j = 0; j < intentsSize; j++) {
PackageParser.ActivityIntentInfo intent = a.intents.get(j);
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " IntentFilter:");
intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
}
removeFilter(intent);
}
}
private boolean isSysComponentOrPersistentPlatformSignedPrivApp(PackageParser.Package pkg) {
if (UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID) {
return true;
}
if (!pkg.isPrivileged()) {
return false;
}
final PackageParser.Package disabledPkg =
mServiceInternal.getDisabledPackage(pkg.packageName);
if (disabledPkg != null) {
if ((disabledPkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
return false;
}
} else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
return false;
}
final String systemPackageName = mServiceInternal.getKnownPackageName(
PackageManagerInternal.PACKAGE_SYSTEM, UserHandle.USER_SYSTEM);
final PackageParser.Package systemPackage = getPackage(systemPackageName);
return pkg.mSigningDetails.hasAncestorOrSelf(systemPackage.mSigningDetails)
|| systemPackage.mSigningDetails.checkCapability(pkg.mSigningDetails,
PackageParser.SigningDetails.CertCapabilities.PERMISSION);
}
private boolean isPermissionsReviewRequired(PackageParser.Package pkg, int userId) {
if (!mSettings.mPermissionReviewRequired) {
return false;
}
// Permission review applies only to apps not supporting the new permission model.
if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
return false;
}
// Legacy apps have the permission and get user consent on launch.
if (pkg == null || pkg.mExtras == null) {
return false;
}
final PackageSetting ps = (PackageSetting) pkg.mExtras;
final PermissionsState permissionsState = ps.getPermissionsState();
return permissionsState.isPermissionReviewRequired(userId);
}
private static boolean matchSignaturesRecover(
String packageName,
PackageParser.SigningDetails existingSignatures,
PackageParser.SigningDetails parsedSignatures,
@PackageParser.SigningDetails.CertCapabilities int flags) {
String msg = null;
try {
if (parsedSignatures.checkCapabilityRecover(existingSignatures, flags)) {
logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
+ packageName);
return true;
}
} catch (CertificateException e) {
msg = e.getMessage();
}
logCriticalInfo(Log.INFO,
"Failed to recover certificates for " + packageName + ": " + msg);
return false;
}
void removeService(PackageParser.Service s) {
mServices.remove(s.getComponentName());
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
? s.info.nonLocalizedLabel : s.info.name) + ":");
Log.v(TAG, " Class=" + s.info.name);
}
final int intentsSize = s.intents.size();
int j;
for (j = 0; j < intentsSize; j++) {
PackageParser.ServiceIntentInfo intent = s.intents.get(j);
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " IntentFilter:");
intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
}
removeFilter(intent);
}
}
@Override
protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
if (!sUserManager.exists(userId)) return true;
PackageParser.Package p = filter.service.owner;
if (p != null) {
PackageSetting ps = (PackageSetting) p.mExtras;
if (ps != null) {
// System apps are never considered stopped for purposes of
// filtering, because there may be no way for the user to
// actually re-launch them.
return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
&& ps.getStopped(userId);
}
}
return false;
}
private void addUninstalledInstantAppLPw(@NonNull PackageParser.Package pkg,
@UserIdInt int userId) {
InstantAppInfo uninstalledApp = createInstantAppInfoForPackage(
pkg, userId, false);
if (uninstalledApp == null) {
return;
}
if (mUninstalledInstantApps == null) {
mUninstalledInstantApps = new SparseArray<>();
}
List<UninstalledInstantAppState> uninstalledAppStates =
mUninstalledInstantApps.get(userId);
if (uninstalledAppStates == null) {
uninstalledAppStates = new ArrayList<>();
mUninstalledInstantApps.put(userId, uninstalledAppStates);
}
UninstalledInstantAppState uninstalledAppState = new UninstalledInstantAppState(
uninstalledApp, System.currentTimeMillis());
uninstalledAppStates.add(uninstalledAppState);
writeUninstalledInstantAppMetadata(uninstalledApp, userId);
writeInstantApplicationIconLPw(pkg, userId);
}
/**
* Creates oat dir for the specified package if needed and supported.
* In certain cases oat directory
* <strong>cannot</strong> be created:
* <ul>
* <li>{@code pkg} is a system app, which is not updated.</li>
* <li>Package location is not a directory, i.e. monolithic install.</li>
* </ul>
*
* @return Absolute path to the oat directory or null, if oat directory
* cannot be created.
*/
@Nullable
private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet) {
if (!pkg.canHaveOatDir()) {
return null;
}
File codePath = new File(pkg.codePath);
if (codePath.isDirectory()) {
// TODO(calin): why do we create this only if the codePath is a directory? (i.e for
// cluster packages). It seems that the logic for the folder creation is
// split between installd and here.
File oatDir = getOatDir(codePath);
try {
mInstaller.createOatDir(oatDir.getAbsolutePath(), dexInstructionSet);
} catch (InstallerException e) {
Slog.w(TAG, "Failed to create oat dir", e);
return null;
}
return oatDir.getAbsolutePath();
}
return null;
}
private List<PackageParser.Package> getHeadlessSyncAdapterPackages(
String[] syncAdapterPackageNames, int userId) {
List<PackageParser.Package> syncAdapterPackages = new ArrayList<>();
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_LAUNCHER);
for (String syncAdapterPackageName : syncAdapterPackageNames) {
homeIntent.setPackage(syncAdapterPackageName);
ResolveInfo homeActivity = mServiceInternal.resolveIntent(homeIntent,
homeIntent.resolveType(mContext.getContentResolver()), DEFAULT_FLAGS,
userId, false, Binder.getCallingUid());
if (homeActivity != null) {
continue;
}
PackageParser.Package syncAdapterPackage = getSystemPackage(syncAdapterPackageName);
if (syncAdapterPackage != null) {
syncAdapterPackages.add(syncAdapterPackage);
}
}
return syncAdapterPackages;
}
@Override
public List<String> querySharedPackages(String packageName) {
synchronized (mPackages) {
PackageParser.Package p = mPackages.get(packageName);
if (p == null || p.mSharedUserId == null) {
// noinspection unchecked
return Collections.EMPTY_LIST;
}
ArrayList<String> list = new ArrayList<>();
for (PackageParser.Package one : mPackages.values()) {
if (TextUtils.equals(one.mSharedUserId, p.mSharedUserId)) {
list.add(one.packageName);
}
}
return list;
}
}
public Intent getLeanbackLaunchIntent() {
ContentResolver resolver = this.mPluginContext.getContentResolver();
Intent launcher = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER);
for (PackageParser.Activity activity : this.mPackage.activities) {
for (PackageParser.ActivityIntentInfo intentInfo : activity.intents) {
if (intentInfo.match(resolver, launcher, false, TAG) > 0) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(activity.getComponentName());
intent.addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER);
return intent;
}
}
}
return null;
}
/**
* Performs dexopt on all code paths and libraries of the specified package for specified
* instruction sets.
*
* <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are
* synchronized on {@link #mInstallLock}.
*/
int performDexOpt(PackageParser.Package pkg, String[] sharedLibraries,
String[] instructionSets, CompilerStats.PackageStats packageStats,
PackageDexUsage.PackageUseInfo packageUseInfo, DexoptOptions options) {
if (pkg.applicationInfo.uid == -1) {
throw new IllegalArgumentException("Dexopt for " + pkg.packageName
+ " has invalid uid.");
}
if (!canOptimizePackage(pkg)) {
return DEX_OPT_SKIPPED;
}
synchronized (mInstallLock) {
final long acquireTime = acquireWakeLockLI(pkg.applicationInfo.uid);
try {
return performDexOptLI(pkg, sharedLibraries, instructionSets,
packageStats, packageUseInfo, options);
} finally {
releaseWakeLockLI(acquireTime);
}
}
}
public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, int flags,
ArrayList<PackageParser.Service> packageServices) {
if (packageServices == null) {
return null;
}
mFlags = flags;
final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
final int N = packageServices.size();
ArrayList<PackageParser.ServiceIntentInfo[]> listCut = new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
for (int i = 0; i < N; ++i) {
intentFilters = packageServices.get(i).intents;
if (intentFilters != null && intentFilters.size() > 0) {
PackageParser.ServiceIntentInfo[] array = new PackageParser.ServiceIntentInfo[intentFilters.size()];
intentFilters.toArray(array);
listCut.add(array);
}
}
return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
}
@Override
public List<ResolveInfo> queryIntentActivities(Intent intent, String resolvedType, int flags, int userId) {
checkUserId(userId);
ComponentName comp = intent.getComponent();
if (comp == null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
if (intent.getSelector() != null) {
intent = intent.getSelector();
comp = intent.getComponent();
}
}
}
if (comp != null) {
final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
final ActivityInfo ai = getActivityInfo(comp, flags, userId);
if (ai != null) {
final ResolveInfo ri = new ResolveInfo();
ri.activityInfo = ai;
list.add(ri);
}
return list;
}
// reader
synchronized (mPackages) {
final String pkgName = intent.getPackage();
if (pkgName == null) {
return mActivities.queryIntent(intent, resolvedType, flags);
}
final PackageParser.Package pkg = mPackages.get(pkgName);
if (pkg != null) {
return mActivities.queryIntentForPackage(intent, resolvedType, flags, pkg.activities);
}
return new ArrayList<ResolveInfo>();
}
}
public final void removeProvider(PackageParser.Provider p) {
mProviders.remove(p.getComponentName());
final int NI = p.intents.size();
int j;
for (j = 0; j < NI; j++) {
PackageParser.ProviderIntentInfo intent = p.intents.get(j);
removeFilter(intent);
}
}
private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
final int permCount = pkg.requestedPermissions.size();
for (int j = 0; j < permCount; j++) {
String requestedPermission = pkg.requestedPermissions.get(j);
if (permission.equals(requestedPermission)) {
return true;
}
}
return false;
}
private boolean updatePermissionFlagsForAllApps(int flagMask, int flagValues, int callingUid,
int userId, Collection<Package> packages, PermissionCallback callback) {
if (!mUserManagerInt.exists(userId)) {
return false;
}
enforceGrantRevokeRuntimePermissionPermissions(
"updatePermissionFlagsForAllApps");
enforceCrossUserPermission(callingUid, userId,
true, // requireFullPermission
true, // checkShell
false, // requirePermissionWhenSameUser
"updatePermissionFlagsForAllApps");
// Only the system can change system fixed flags.
if (callingUid != Process.SYSTEM_UID) {
flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
}
boolean changed = false;
for (PackageParser.Package pkg : packages) {
final PackageSetting ps = (PackageSetting) pkg.mExtras;
if (ps == null) {
continue;
}
PermissionsState permissionsState = ps.getPermissionsState();
changed |= permissionsState.updatePermissionFlagsForAllPermissions(
userId, flagMask, flagValues);
}
return changed;
}
private static ApkAssets loadApkAssets(String path, @ParseFlags int flags)
throws PackageParserException {
if ((flags & PackageParser.PARSE_MUST_BE_APK) != 0 && !PackageParser.isApkPath(path)) {
throw new PackageParserException(INSTALL_PARSE_FAILED_NOT_APK,
"Invalid package file: " + path);
}
try {
return ApkAssets.loadFromPath(path);
} catch (IOException e) {
throw new PackageParserException(PackageManager.INSTALL_FAILED_INVALID_APK,
"Failed to load APK at path " + path, e);
}
}
/**
* generateProviderInfo
*
* @param p PackageParser.Package
* @param pi PackageInfo
* @param flags flags
*/
private void generateProviderInfo(PackageParser.Package p, PackageInfo pi, int flags) {
PackageUserState state = new PackageUserState();
if ((flags & PackageManager.GET_PROVIDERS) != 0) {
int N = p.providers.size();
if (N > 0) {
if ((flags & PackageManager.GET_DISABLED_COMPONENTS) != 0) {
pi.providers = new ProviderInfo[N];
} else {
int num = 0;
for (int i = 0; i < N; i++) {
if (p.providers.get(i).info.enabled) num++;
}
pi.providers = new ProviderInfo[num];
}
for (int i = 0, j = 0; i < N; i++) {
final Provider provider = p.providers.get(i);
if (provider.info.enabled
|| (flags & PackageManager.GET_DISABLED_COMPONENTS) != 0) {
pi.providers[j++] = PackageParser.generateProviderInfo(p.providers.get(i), flags,
state, 0);
// try {
// pi.providers[j++] = JavaCalls.callStaticMethodOrThrow(PackageParser.class, "generateProviderInfo",
// p.providers.get(i), flags, state, 0);
// } catch (Exception e) {
// e.printStackTrace();
// }
}
}
}
}
}
public final void addService(PackageParser.Service s) {
mServices.put(s.getComponentName(), s);
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " " + (s.info.nonLocalizedLabel != null ? s.info.nonLocalizedLabel : s.info.name) + ":");
Log.v(TAG, " Class=" + s.info.name);
}
final int NI = s.intents.size();
int j;
for (j = 0; j < NI; j++) {
PackageParser.ServiceIntentInfo intent = s.intents.get(j);
addFilter(intent);
}
}
@DexReplace
static PackageInfo hook(PackageInfo pi, Context context, PackageParser.Package p, int flags, int userId) {
try {
if ((flags & PackageManager.GET_SIGNATURES) != 0) {
if (p.requestedPermissions != null) {
if (p.requestedPermissions.contains(FakeSignatureCore.PERMISSION)) {
if (getGlobalEnable(pi, context, p, flags, userId) &&
getPerAppEnable(pi, context, p, flags, userId)) {
if (p.mAppMetaData != null) {
Object fakeSignatureData = p.mAppMetaData.get(FakeSignatureCore.METADATA);
if (fakeSignatureData != null) {
if (fakeSignatureData instanceof String) {
pi.signatures = new Signature[] { new Signature((String) fakeSignatureData) };
} else {
Log.e("GeneratePackageInfoHook", "invalid '" + FakeSignatureCore.METADATA + "' metadata");
}
} else {
Log.e("GeneratePackageInfoHook", "missing 'fake-signature' metadata");
}
} else {
Log.e("GeneratePackageInfoHook", "null mAppMetaData");
}
}
}
} else {
Log.e("GeneratePackageInfoHook", "null requestedPermissions");
}
}
} catch (Throwable t) {
// We should never die because of any failures, this is system code!
// Eating up instances of Error might seem excessive, but they can be
// the result of improperly applied patches so we will handle them here.
Log.e("GeneratePackageInfoHook", "hook exception", t);
}
return pi;
}
public static void put(PackageParser.Package pkg, AppSetting appSetting) {
synchronized (PackageCache.class) {
pkg.mExtras = appSetting;
sPackageCaches.put(pkg.packageName, pkg);
VPackageManagerService.get().analyzePackageLocked(pkg);
}
}
public int getOrCreateUid(PackageParser.Package pkg) {
String sharedUserId = pkg.mSharedUserId;
if (sharedUserId == null) {
sharedUserId = pkg.packageName;
}
Integer uid = mSharedUserIdMap.get(sharedUserId);
if (uid != null) {
return uid;
}
int newUid = ++mFreeUid;
mSharedUserIdMap.put(sharedUserId, newUid);
save();
return newUid;
}
public void addScannedPackageLPw(PackageParser.Package pkg) {
Preconditions.checkNotNull(pkg, "Attempted to add null pkg to ksms.");
Preconditions.checkNotNull(pkg.packageName, "Attempted to add null pkg to ksms.");
PackageSetting ps = mPackages.get(pkg.packageName);
Preconditions.checkNotNull(ps, "pkg: " + pkg.packageName
+ "does not have a corresponding entry in mPackages.");
addSigningKeySetToPackageLPw(ps, pkg.mSigningDetails.publicKeys);
if (pkg.mKeySetMapping != null) {
addDefinedKeySetsToPackageLPw(ps, pkg.mKeySetMapping);
if (pkg.mUpgradeKeySets != null) {
addUpgradeKeySetsToPackageLPw(ps, pkg.mUpgradeKeySets);
}
}
}
private int adjustPermissionProtectionFlagsLocked(
int protectionLevel, String packageName, int uid) {
// Signature permission flags area always reported
final int protectionLevelMasked = protectionLevel
& (PermissionInfo.PROTECTION_NORMAL
| PermissionInfo.PROTECTION_DANGEROUS
| PermissionInfo.PROTECTION_SIGNATURE);
if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
return protectionLevel;
}
// System sees all flags.
final int appId = UserHandle.getAppId(uid);
if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
|| appId == Process.SHELL_UID) {
return protectionLevel;
}
// Normalize package name to handle renamed packages and static libs
final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName);
if (pkg == null) {
return protectionLevel;
}
if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
return protectionLevelMasked;
}
// Apps that target O see flags for all protection levels.
final PackageSetting ps = (PackageSetting) pkg.mExtras;
if (ps == null) {
return protectionLevel;
}
if (ps.getAppId() != appId) {
return protectionLevel;
}
return protectionLevel;
}
/**
* Clear the profiles for the given package.
*/
public void clearAppProfiles(PackageParser.Package pkg) {
try {
ArrayMap<String, String> packageProfileNames = getPackageProfileNames(pkg);
for (int i = packageProfileNames.size() - 1; i >= 0; i--) {
String profileName = packageProfileNames.valueAt(i);
mInstaller.clearAppProfiles(pkg.packageName, profileName);
}
} catch (InstallerException e) {
Slog.w(TAG, String.valueOf(e));
}
}
@Override
protected void dumpFilter(PrintWriter out, String prefix,
PackageParser.ProviderIntentInfo filter) {
out.print(prefix);
out.print(Integer.toHexString(System.identityHashCode(filter.provider)));
out.print(' ');
filter.provider.printComponentShortName(out);
out.print(" filter ");
out.println(Integer.toHexString(System.identityHashCode(filter)));
}