Skip to content

Commit

Permalink
Android: Use PackageUtils helpers in more places
Browse files Browse the repository at this point in the history
Removes ~100 lines of code. No intended behavior change.

Bug: None
Change-Id: Iff5af92c9f1411955bea89d734c5cfb8b6ac0ce3
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/4051982
Reviewed-by: Yaron Friedman <yfriedman@chromium.org>
Commit-Queue: Andrew Grieve <agrieve@chromium.org>
Owners-Override: Andrew Grieve <agrieve@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1075281}
  • Loading branch information
agrieve authored and Chromium LUCI CQ committed Nov 23, 2022
1 parent 18eba87 commit f604506
Show file tree
Hide file tree
Showing 20 changed files with 166 additions and 269 deletions.
Expand Up @@ -4,10 +4,8 @@

package org.chromium.android_webview;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import org.chromium.base.ContextUtils;
import org.chromium.base.PackageUtils;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.build.annotations.MainDex;
Expand All @@ -27,14 +25,8 @@ private AwFeatureList() {}

private static boolean computePageStartedOnCommitForBrowserNavigations() {
if (GMS_PACKAGE.equals(ContextUtils.getApplicationContext().getPackageName())) {
try {
PackageInfo gmsPackage =
ContextUtils.getApplicationContext().getPackageManager().getPackageInfo(
GMS_PACKAGE, 0);
return gmsPackage.versionCode >= 15000000;
} catch (PackageManager.NameNotFoundException e) {
}
return false;
int gmsPackageVersion = PackageUtils.getPackageVersion(GMS_PACKAGE);
return gmsPackageVersion >= 15000000;
}
return true;
}
Expand Down
Expand Up @@ -24,10 +24,12 @@

import org.chromium.android_webview.common.SafeModeController;
import org.chromium.android_webview.common.services.ISafeModeService;
import org.chromium.android_webview.services.SafeModeService.TrustedPackage;
import org.chromium.android_webview.services.ServicesStatsHelper.NonembeddedService;
import org.chromium.base.BuildInfo;
import org.chromium.base.ContextUtils;
import org.chromium.base.Log;
import org.chromium.base.PackageUtils;
import org.chromium.base.compat.ApiHelperForP;

import java.security.MessageDigest;
Expand Down Expand Up @@ -109,22 +111,20 @@ private static boolean hasSigningCertificate(
return ApiHelperForP.hasSigningCertificate(context.getPackageManager(), packageName,
expectedCertHash, PackageManager.CERT_INPUT_SHA256);
}
try {
PackageInfo info = context.getPackageManager().getPackageInfo(
packageName, PackageManager.GET_SIGNATURES);
PackageInfo info =
PackageUtils.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
if (info != null) {
Signature[] signatures = info.signatures;
if (info.signatures == null) {
if (signatures == null) {
return false;
}
for (Signature signature : info.signatures) {
for (Signature signature : signatures) {
if (Arrays.equals(expectedCertHash, sha256Hash(signature))) {
return true;
}
}
return false; // no matches
} catch (PackageManager.NameNotFoundException e) {
return false;
}
return false; // no matches
}

@Nullable
Expand Down
148 changes: 65 additions & 83 deletions base/android/java/src/org/chromium/base/BuildInfo.java
Expand Up @@ -11,7 +11,6 @@
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.os.Build;
import android.text.TextUtils;
Expand Down Expand Up @@ -148,98 +147,81 @@ public static BuildInfo getInstance() {
@VisibleForTesting
BuildInfo() {
sInitialized = true;
try {
Context appContext = ContextUtils.getApplicationContext();
String hostPackageName = appContext.getPackageName();
PackageManager pm = appContext.getPackageManager();
PackageInfo pi = pm.getPackageInfo(hostPackageName, 0);
hostVersionCode = packageVersionCode(pi);
if (sBrowserPackageInfo != null) {
packageName = sBrowserPackageInfo.packageName;
versionCode = packageVersionCode(sBrowserPackageInfo);
versionName = nullToEmpty(sBrowserPackageInfo.versionName);
sBrowserApplicationInfo = sBrowserPackageInfo.applicationInfo;
sBrowserPackageInfo = null;
} else {
packageName = hostPackageName;
versionCode = hostVersionCode;
versionName = nullToEmpty(pi.versionName);
sBrowserApplicationInfo = appContext.getApplicationInfo();
}

hostPackageLabel = nullToEmpty(pm.getApplicationLabel(pi.applicationInfo));
installerPackageName = nullToEmpty(pm.getInstallerPackageName(packageName));
Context appContext = ContextUtils.getApplicationContext();
String hostPackageName = appContext.getPackageName();
PackageManager pm = appContext.getPackageManager();
PackageInfo pi = PackageUtils.getPackageInfo(hostPackageName, 0);
hostVersionCode = packageVersionCode(pi);
if (sBrowserPackageInfo != null) {
packageName = sBrowserPackageInfo.packageName;
versionCode = packageVersionCode(sBrowserPackageInfo);
versionName = nullToEmpty(sBrowserPackageInfo.versionName);
sBrowserApplicationInfo = sBrowserPackageInfo.applicationInfo;
sBrowserPackageInfo = null;
} else {
packageName = hostPackageName;
versionCode = hostVersionCode;
versionName = nullToEmpty(pi.versionName);
sBrowserApplicationInfo = appContext.getApplicationInfo();
}

hostPackageLabel = nullToEmpty(pm.getApplicationLabel(pi.applicationInfo));
installerPackageName = nullToEmpty(pm.getInstallerPackageName(packageName));

PackageInfo gmsPackageInfo = null;
try {
gmsPackageInfo = pm.getPackageInfo("com.google.android.gms", 0);
} catch (NameNotFoundException e) {
// TODO(b/197112084): Re-enable the logging
// Log.d(TAG, "GMS package is not found.");
}
gmsVersionCode = gmsPackageInfo != null
? String.valueOf(packageVersionCode(gmsPackageInfo))
: "gms versionCode not available.";
PackageInfo gmsPackageInfo = PackageUtils.getPackageInfo("com.google.android.gms", 0);
gmsVersionCode = gmsPackageInfo != null ? String.valueOf(packageVersionCode(gmsPackageInfo))
: "gms versionCode not available.";

// Substratum is a theme engine that enables users to use custom themes provided
// by theme apps. Sometimes these can cause crashs if not installed correctly.
// These crashes can be difficult to debug, so knowing if the theme manager is
// present on the device is useful (http://crbug.com/820591).
customThemes = String.valueOf(PackageUtils.isPackageInstalled("projekt.substratum"));

String hasCustomThemes = "true";
String currentResourcesVersion = "Not Enabled";
// Controlled by target specific build flags.
if (BuildConfig.R_STRING_PRODUCT_VERSION != 0) {
try {
// Substratum is a theme engine that enables users to use custom themes provided
// by theme apps. Sometimes these can cause crashs if not installed correctly.
// These crashes can be difficult to debug, so knowing if the theme manager is
// present on the device is useful (http://crbug.com/820591).
pm.getPackageInfo("projekt.substratum", 0);
} catch (NameNotFoundException e) {
hasCustomThemes = "false";
// This value can be compared with the actual product version to determine if
// corrupted resources were the cause of a crash. This can happen if the app
// loads resources from the outdated package during an update
// (http://crbug.com/820591).
currentResourcesVersion = ContextUtils.getApplicationContext().getString(
BuildConfig.R_STRING_PRODUCT_VERSION);
} catch (Exception e) {
currentResourcesVersion = "Not found";
}
customThemes = hasCustomThemes;

String currentResourcesVersion = "Not Enabled";
// Controlled by target specific build flags.
if (BuildConfig.R_STRING_PRODUCT_VERSION != 0) {
try {
// This value can be compared with the actual product version to determine if
// corrupted resources were the cause of a crash. This can happen if the app
// loads resources from the outdated package during an update
// (http://crbug.com/820591).
currentResourcesVersion = ContextUtils.getApplicationContext().getString(
BuildConfig.R_STRING_PRODUCT_VERSION);
} catch (Exception e) {
currentResourcesVersion = "Not found";
}
}
resourcesVersion = currentResourcesVersion;
}
resourcesVersion = currentResourcesVersion;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
abiString = TextUtils.join(", ", Build.SUPPORTED_ABIS);
} else {
abiString = String.format("ABI1: %s, ABI2: %s", Build.CPU_ABI, Build.CPU_ABI2);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
abiString = TextUtils.join(", ", Build.SUPPORTED_ABIS);
} else {
abiString = String.format("ABI1: %s, ABI2: %s", Build.CPU_ABI, Build.CPU_ABI2);
}

// The value is truncated, as this is used for crash and UMA reporting.
androidBuildFingerprint = Build.FINGERPRINT.substring(
0, Math.min(Build.FINGERPRINT.length(), MAX_FINGERPRINT_LENGTH));
// The value is truncated, as this is used for crash and UMA reporting.
androidBuildFingerprint = Build.FINGERPRINT.substring(
0, Math.min(Build.FINGERPRINT.length(), MAX_FINGERPRINT_LENGTH));

// See https://developer.android.com/training/tv/start/hardware.html#runtime-check.
UiModeManager uiModeManager =
(UiModeManager) appContext.getSystemService(UI_MODE_SERVICE);
isTV = uiModeManager != null
&& uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION;
// See https://developer.android.com/training/tv/start/hardware.html#runtime-check.
UiModeManager uiModeManager = (UiModeManager) appContext.getSystemService(UI_MODE_SERVICE);
isTV = uiModeManager != null
&& uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION;

boolean isAutomotive;
try {
isAutomotive = pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
} catch (SecurityException e) {
Log.e(TAG, "Unable to query for Automotive system feature", e);

// `hasSystemFeature` can possibly throw an exception on modified instances of
// Android. In this case, assume the device is not a car since automotive vehicles
// should not have such a modification.
isAutomotive = false;
}
this.isAutomotive = isAutomotive;
} catch (NameNotFoundException e) {
throw new RuntimeException(e);
boolean isAutomotive;
try {
isAutomotive = pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
} catch (SecurityException e) {
Log.e(TAG, "Unable to query for Automotive system feature", e);

// `hasSystemFeature` can possibly throw an exception on modified instances of
// Android. In this case, assume the device is not a car since automotive vehicles
// should not have such a modification.
isAutomotive = false;
}
this.isAutomotive = isAutomotive;
}

/**
Expand Down
1 change: 1 addition & 0 deletions base/android/java/src/org/chromium/base/PackageUtils.java
Expand Up @@ -49,6 +49,7 @@ public class PackageUtils {
* @return The package's version code if found, -1 otherwise.
*/
public static int getPackageVersion(String packageName) {
// TODO(agrieve): Return a long and move BuildInfo.packageVersionCode() to this class.
PackageInfo packageInfo = getPackageInfo(packageName, 0);
if (packageInfo != null) return packageInfo.versionCode;
return -1;
Expand Down
Expand Up @@ -9,7 +9,6 @@
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
Expand All @@ -25,10 +24,10 @@
import org.chromium.base.BaseFeatures;
import org.chromium.base.BuildInfo;
import org.chromium.base.ChildBindingState;
import org.chromium.base.ContextUtils;
import org.chromium.base.Log;
import org.chromium.base.MemoryPressureLevel;
import org.chromium.base.MemoryPressureListener;
import org.chromium.base.PackageUtils;
import org.chromium.base.ThreadUtils;
import org.chromium.base.TraceEvent;
import org.chromium.base.memory.MemoryPressureCallback;
Expand Down Expand Up @@ -614,18 +613,10 @@ protected void onServiceConnectedOnLauncherThread(IBinder service) {
if (childMismatchError != null) {
// Check if it looks like the browser's package version has been changed since the
// browser process launched (i.e. if the install somehow did not kill our process)
boolean versionHasChanged;
try {
PackageInfo latestPackage =
ContextUtils.getApplicationContext().getPackageManager().getPackageInfo(
BuildInfo.getInstance().packageName, 0);
long latestVersionCode = BuildInfo.packageVersionCode(latestPackage);
long loadedVersionCode = BuildInfo.getInstance().versionCode;
versionHasChanged = latestVersionCode != loadedVersionCode;
} catch (PackageManager.NameNotFoundException e) {
// Package uninstalled since we launched? Then the version has "changed"...
versionHasChanged = true;
}
PackageInfo latestPackage = PackageUtils.getApplicationPackageInfo(0);
long latestVersionCode = BuildInfo.packageVersionCode(latestPackage);
long loadedVersionCode = BuildInfo.getInstance().versionCode;
boolean versionHasChanged = latestVersionCode != loadedVersionCode;
RecordHistogram.recordBooleanHistogram(
"Android.ChildMismatch.BrowserVersionChanged2", versionHasChanged);
childMismatchError += "; browser version has changed: " + versionHasChanged;
Expand Down
19 changes: 6 additions & 13 deletions chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java
Expand Up @@ -4,16 +4,14 @@

package org.chromium.chrome.browser;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;

import org.chromium.base.ContextUtils;
import org.chromium.base.PackageUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.chrome.browser.customtabs.CustomTabsConnection;
import org.chromium.chrome.browser.directactions.DirectActionCoordinator;
Expand Down Expand Up @@ -247,16 +245,11 @@ public DigitalWellbeingClient createDigitalWellbeingClient() {
* same as {@link GoogleApiAvailability#isGooglePlayServicesAvailable()}.
*/
public int isGoogleApiAvailableWithMinApkVersion(int minApkVersion) {
try {
PackageInfo gmsPackageInfo =
ContextUtils.getApplicationContext().getPackageManager().getPackageInfo(
GoogleApiAvailability.GOOGLE_PLAY_SERVICES_PACKAGE, /* flags= */ 0);
int apkVersion = gmsPackageInfo.versionCode;
if (apkVersion >= minApkVersion) return ConnectionResult.SUCCESS;
} catch (PackageManager.NameNotFoundException e) {
return ConnectionResult.SERVICE_MISSING;
}
return ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED;
int apkVersion =
PackageUtils.getPackageVersion(GoogleApiAvailability.GOOGLE_PLAY_SERVICES_PACKAGE);
return apkVersion < 0 ? ConnectionResult.SERVICE_MISSING
: apkVersion < minApkVersion ? ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED
: ConnectionResult.SUCCESS;
}

/**
Expand Down
Expand Up @@ -4,12 +4,9 @@

package org.chromium.chrome.browser;

import android.content.Context;
import android.content.pm.PackageManager;

import com.google.android.gms.common.GoogleApiAvailability;

import org.chromium.base.ContextUtils;
import org.chromium.base.PackageUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.components.externalauth.ExternalAuthUtils;

Expand All @@ -27,10 +24,8 @@ public class PlayServicesVersionInfo {
*/
@CalledByNative
public static String getGmsInfo() {
Context context = ContextUtils.getApplicationContext();

final long sdkVersion = GoogleApiAvailability.GOOGLE_PLAY_SERVICES_VERSION_CODE;
final long installedGmsVersion = getApkVersionNumber(context);
final long installedGmsVersion = getApkVersionNumber();

final String accessType;
ExternalAuthUtils externalAuthUtils = ExternalAuthUtils.getInstance();
Expand All @@ -49,16 +44,15 @@ public static String getGmsInfo() {
/**
*
* @param context A Context with which to retrieve the PackageManager.
* @return The version code for the Google Play Services installed on the device or 0 if the
* @return The version code for the Google Play Services installed on the device or -1 if the
* package is not found.
*/
public static int getApkVersionNumber(Context context) {
try {
return context.getPackageManager()
.getPackageInfo(GoogleApiAvailability.GOOGLE_PLAY_SERVICES_PACKAGE, 0)
.versionCode;
} catch (PackageManager.NameNotFoundException e) {
return 0;
public static int getApkVersionNumber() {
int ret =
PackageUtils.getPackageVersion(GoogleApiAvailability.GOOGLE_PLAY_SERVICES_PACKAGE);
if (ret < 0) {
ret = 0;
}
return ret;
}
}
Expand Up @@ -1353,7 +1353,7 @@ protected void initDeferredStartupForActivity() {
}

recordDisplayDimensions();
int playServicesVersion = PlayServicesVersionInfo.getApkVersionNumber(this);
int playServicesVersion = PlayServicesVersionInfo.getApkVersionNumber();
RecordHistogram.recordBooleanHistogram(
"Android.PlayServices.Installed", playServicesVersion > 0);
RecordHistogram.recordSparseHistogram(
Expand Down

0 comments on commit f604506

Please sign in to comment.