diff options
51 files changed, 369 insertions, 905 deletions
diff --git a/core/api/current.txt b/core/api/current.txt index 1f1067849d47..7915509c1381 100644 --- a/core/api/current.txt +++ b/core/api/current.txt @@ -16734,7 +16734,7 @@ package android.graphics { method public void arcTo(@NonNull android.graphics.RectF, float, float); method public void arcTo(float, float, float, float, float, float, boolean); method public void close(); - method @Deprecated public void computeBounds(@NonNull android.graphics.RectF, boolean); + method public void computeBounds(@NonNull android.graphics.RectF, boolean); method @FlaggedApi("com.android.graphics.flags.exact_compute_bounds") public void computeBounds(@NonNull android.graphics.RectF); method public void conicTo(float, float, float, float, float); method public void cubicTo(float, float, float, float, float, float); diff --git a/core/api/module-lib-current.txt b/core/api/module-lib-current.txt index 149e474055be..d3775dbb036d 100644 --- a/core/api/module-lib-current.txt +++ b/core/api/module-lib-current.txt @@ -499,6 +499,10 @@ package android.os { field public static final long TRACE_TAG_NETWORK = 2097152L; // 0x200000L } + public class UpdateEngine { + method @FlaggedApi("android.os.update_engine_api") public void triggerPostinstall(@NonNull String); + } + } package android.os.storage { diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java index 918ae1cb8ab6..4137a5fb9c1e 100644 --- a/core/java/android/app/SystemServiceRegistry.java +++ b/core/java/android/app/SystemServiceRegistry.java @@ -71,8 +71,6 @@ import android.content.ContentCaptureOptions; import android.content.Context; import android.content.IRestrictionsManager; import android.content.RestrictionsManager; -import android.content.integrity.AppIntegrityManager; -import android.content.integrity.IAppIntegrityManager; import android.content.om.IOverlayManager; import android.content.om.OverlayManager; import android.content.pm.ApplicationInfo; @@ -1497,16 +1495,6 @@ public final class SystemServiceRegistry { return new AttestationVerificationManager(ctx.getOuterContext(), IAttestationVerificationManagerService.Stub.asInterface(b)); }}); - - //CHECKSTYLE:ON IndentationCheck - registerService(Context.APP_INTEGRITY_SERVICE, AppIntegrityManager.class, - new CachedServiceFetcher<AppIntegrityManager>() { - @Override - public AppIntegrityManager createService(ContextImpl ctx) - throws ServiceNotFoundException { - IBinder b = ServiceManager.getServiceOrThrow(Context.APP_INTEGRITY_SERVICE); - return new AppIntegrityManager(IAppIntegrityManager.Stub.asInterface(b)); - }}); registerService(Context.APP_HIBERNATION_SERVICE, AppHibernationManager.class, new CachedServiceFetcher<AppHibernationManager>() { @Override diff --git a/core/java/android/net/metrics/DnsEvent.java b/core/java/android/net/metrics/DnsEvent.java index bf351ce07fe8..f53d1c4d191d 100644 --- a/core/java/android/net/metrics/DnsEvent.java +++ b/core/java/android/net/metrics/DnsEvent.java @@ -62,7 +62,11 @@ final public class DnsEvent { return isSuccess; } if (eventCount == eventTypes.length) { - resize((int) (1.4 * eventCount)); + int resizeLength = (int) (1.4 * eventCount); + if (eventCount == resizeLength) { + resizeLength++; + } + resize(resizeLength); } eventTypes[eventCount] = eventType; returnCodes[eventCount] = returnCode; diff --git a/core/java/android/os/OWNERS b/core/java/android/os/OWNERS index bfcc5cc6f18e..8d353384f1e2 100644 --- a/core/java/android/os/OWNERS +++ b/core/java/android/os/OWNERS @@ -118,9 +118,10 @@ per-file IpcDataCache.java = file:/PERFORMANCE_OWNERS # Memory per-file OomKillRecord.java = file:/MEMORY_OWNERS -# MessageQueue +# MessageQueue and related classes per-file MessageQueue.java = mfasheh@google.com, shayba@google.com per-file Message.java = mfasheh@google.com, shayba@google.com +per-file TestLooperManager.java = mfasheh@google.com, shayba@google.com # Stats per-file IStatsBootstrapAtomService.aidl = file:/services/core/java/com/android/server/stats/OWNERS diff --git a/core/java/android/os/SELinux.java b/core/java/android/os/SELinux.java index f64a81177ce2..11c54ef802fe 100644 --- a/core/java/android/os/SELinux.java +++ b/core/java/android/os/SELinux.java @@ -193,4 +193,31 @@ public class SELinux { return false; } } + + /** + * Gets the genfs labels version of the vendor. The genfs labels version is + * specified in {@code /vendor/etc/selinux/genfs_labels_version.txt}. The + * version follows the VINTF version format "YYYYMM" and affects how {@code + * genfs_contexts} entries are applied. + * + * <p>The genfs labels version indicates changes in the SELinux labeling + * scheme over time. For example: + * <ul> + * <li>For version 202504 and later, {@code /sys/class/udc} is labeled as + * {@code sysfs_udc}. + * <li>For version 202404 and earlier, {@code /sys/class/udc} is labeled + * as {@code sysfs}. + * </ul> + * Check {@code /system/etc/selinux/plat_sepolicy_genfs_{version}.cil} to + * see which labels are new in {version}. + * + * <p>Older vendors may override {@code genfs_contexts} with vendor-specific + * extensions. The framework must not break such labellings to maintain + * compatibility with such vendors, by checking the genfs labels version and + * implementing a fallback mechanism. + * + * @return an integer representing the genfs labels version of /vendor, in + * the format YYYYMM. + */ + public static final native int getGenfsLabelsVersion(); } diff --git a/core/java/android/os/UpdateEngine.java b/core/java/android/os/UpdateEngine.java index 0a8f62fd56d8..81e4549c78d1 100644 --- a/core/java/android/os/UpdateEngine.java +++ b/core/java/android/os/UpdateEngine.java @@ -16,6 +16,7 @@ package android.os; +import android.annotation.FlaggedApi; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.SystemApi; @@ -667,4 +668,23 @@ public class UpdateEngine { throw e.rethrowFromSystemServer(); } } + + /** + * Run postinstall script for specified partition |partition| + * + * @param partition The partition to trigger postinstall runs + * + * @throws ServiceSpecificException error code of this exception would be one of + * https://cs.android.com/android/platform/superproject/main/+/main:system/update_engine/common/error_code.h + * @hide + */ + @FlaggedApi(Flags.FLAG_UPDATE_ENGINE_API) + @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) + public void triggerPostinstall(@NonNull String partition) { + try { + mUpdateEngine.triggerPostinstall(partition); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } + } } diff --git a/core/java/com/android/internal/os/TEST_MAPPING b/core/java/com/android/internal/os/TEST_MAPPING index 83773e251a9e..f431e9308a89 100644 --- a/core/java/com/android/internal/os/TEST_MAPPING +++ b/core/java/com/android/internal/os/TEST_MAPPING @@ -20,7 +20,7 @@ "file_patterns": [ "BinderDeathDispatcher\\.java" ], - "name": "FrameworksCoreTests_internal_os_binder" + "name": "FrameworksCoreTests_all_binder" }, { "file_patterns": [ diff --git a/core/java/com/android/internal/pm/pkg/component/AconfigFlags.java b/core/java/com/android/internal/pm/pkg/component/AconfigFlags.java index f306b0b02677..27dbd9863e78 100644 --- a/core/java/com/android/internal/pm/pkg/component/AconfigFlags.java +++ b/core/java/com/android/internal/pm/pkg/component/AconfigFlags.java @@ -218,16 +218,12 @@ public class AconfigFlags { negated = true; featureFlag = featureFlag.substring(1).strip(); } - final Boolean flagValue = getFlagValue(featureFlag); + Boolean flagValue = getFlagValue(featureFlag); if (flagValue == null) { - Slog.w(LOG_TAG, "Skipping element " + parser.getName() - + " due to unknown feature flag " + featureFlag); - return true; + flagValue = false; } // Skip if flag==false && attr=="flag" OR flag==true && attr=="!flag" (negated) if (flagValue == negated) { - Slog.v(LOG_TAG, "Skipping element " + parser.getName() - + " behind feature flag " + featureFlag + " = " + flagValue); return true; } return false; diff --git a/core/jni/Android.bp b/core/jni/Android.bp index f6689d585df1..0196ef5ef852 100644 --- a/core/jni/Android.bp +++ b/core/jni/Android.bp @@ -287,6 +287,7 @@ cc_library_shared_for_libandroid_runtime { "libasync_safe", "libbinderthreadstateutils", "libdmabufinfo", + "libgenfslabelsversion.ffi", "libgui_window_info_static", "libkernelconfigs", "libnativehelper_lazy", diff --git a/core/jni/android_os_SELinux.cpp b/core/jni/android_os_SELinux.cpp index 7a4670f4e49d..805d5ad41e83 100644 --- a/core/jni/android_os_SELinux.cpp +++ b/core/jni/android_os_SELinux.cpp @@ -18,18 +18,19 @@ #include <errno.h> #include <fcntl.h> - +#include <genfslabelsversion.h> +#include <nativehelper/JNIPlatformHelp.h> +#include <nativehelper/ScopedLocalRef.h> +#include <nativehelper/ScopedUtfChars.h> #include <utils/Log.h> -#include <nativehelper/JNIPlatformHelp.h> -#include "jni.h" +#include <atomic> +#include <memory> + #include "core_jni_helpers.h" -#include "selinux/selinux.h" +#include "jni.h" #include "selinux/android.h" -#include <memory> -#include <atomic> -#include <nativehelper/ScopedLocalRef.h> -#include <nativehelper/ScopedUtfChars.h> +#include "selinux/selinux.h" namespace android { namespace { @@ -404,8 +405,19 @@ static jboolean native_restorecon(JNIEnv *env, jobject, jstring pathnameStr, jin } /* + * Function: getGenfsLabelsVersion + * Purpose: get which genfs labels version /vendor uses + * Returns: int: genfs labels version of /vendor + * Exceptions: none + */ +static jint getGenfsLabelsVersion(JNIEnv *, jclass) { + return get_genfs_labels_version(); +} + +/* * JNI registration. */ +// clang-format off static const JNINativeMethod method_table[] = { /* name, signature, funcPtr */ { "checkSELinuxAccess" , "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z" , (void*)checkSELinuxAccess }, @@ -420,7 +432,9 @@ static const JNINativeMethod method_table[] = { { "setFileContext" , "(Ljava/lang/String;Ljava/lang/String;)Z" , (void*)setFileCon }, { "setFSCreateContext" , "(Ljava/lang/String;)Z" , (void*)setFSCreateCon }, { "fileSelabelLookup" , "(Ljava/lang/String;)Ljava/lang/String;" , (void*)fileSelabelLookup}, + { "getGenfsLabelsVersion" , "()I" , (void *)getGenfsLabelsVersion}, }; +// clang-format on static int log_callback(int type, const char *fmt, ...) { va_list ap; diff --git a/core/tests/coretests/Android.bp b/core/tests/coretests/Android.bp index b1c48ab39396..4b0b98cf74f1 100644 --- a/core/tests/coretests/Android.bp +++ b/core/tests/coretests/Android.bp @@ -510,14 +510,25 @@ test_module_config { } test_module_config { - name: "FrameworksCoreTests_internal_os_binder", + name: "FrameworksCoreTests_all_binder", base: "FrameworksCoreTests", test_suites: [ "automotive-tests", "device-tests", "device-platinum-tests", ], - include_filters: ["com.android.internal.os.BinderDeathDispatcherTest"], + include_filters: [ + "android.os.BinderProxyTest", + "android.os.BinderDeathRecipientTest", + "android.os.BinderFrozenStateChangeNotificationTest", + "android.os.BinderProxyCountingTest", + "android.os.BinderUncaughtExceptionHandlerTest", + "android.os.BinderThreadPriorityTest", + "android.os.BinderWorkSourceTest", + "android.os.ParcelNullabilityTest", + "android.os.ParcelTest", + "com.android.internal.os.BinderDeathDispatcherTest", + ], exclude_annotations: ["com.android.internal.os.SkipPresubmit"], } diff --git a/core/tests/coretests/src/android/os/BinderThreadPriorityTest.java b/core/tests/coretests/src/android/os/BinderThreadPriorityTest.java index 4172bffe100c..9a679d8e8a96 100644 --- a/core/tests/coretests/src/android/os/BinderThreadPriorityTest.java +++ b/core/tests/coretests/src/android/os/BinderThreadPriorityTest.java @@ -31,6 +31,8 @@ import android.util.Log; import androidx.test.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; +import com.android.internal.os.SkipPresubmit; + import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -131,6 +133,7 @@ public class BinderThreadPriorityTest { } @Test + @SkipPresubmit("b/381950874: bitrot and failed") public void testPassPriorityToService() throws Exception { for (int prio = 19; prio >= -20; prio--) { Process.setThreadPriority(prio); @@ -146,6 +149,7 @@ public class BinderThreadPriorityTest { } @Test + @SkipPresubmit("b/381950874: bitrot and failed") public void testCallBackFromServiceWithPriority() throws Exception { for (int prio = -20; prio <= 19; prio++) { final int expected = prio; diff --git a/data/etc/privapp-permissions-platform.xml b/data/etc/privapp-permissions-platform.xml index b8bed92c7baa..a33a71482e63 100644 --- a/data/etc/privapp-permissions-platform.xml +++ b/data/etc/privapp-permissions-platform.xml @@ -505,7 +505,6 @@ applications that come with the platform <permission name="android.permission.RENOUNCE_PERMISSIONS" /> <permission name="android.permission.WRITE_EMBEDDED_SUBSCRIPTIONS" /> <permission name="android.permission.GET_PROCESS_STATE_AND_OOM_SCORE" /> - <permission name="android.permission.READ_DROPBOX_DATA" /> <permission name="android.permission.READ_LOGS" /> <permission name="android.permission.BRIGHTNESS_SLIDER_USAGE" /> <permission name="android.permission.ACCESS_AMBIENT_LIGHT_STATS" /> diff --git a/graphics/java/android/graphics/Path.java b/graphics/java/android/graphics/Path.java index 073307c7a2e8..d010c525e099 100644 --- a/graphics/java/android/graphics/Path.java +++ b/graphics/java/android/graphics/Path.java @@ -301,10 +301,7 @@ public class Path { * * @param bounds Returns the computed bounds of the path's control points. * @param exact This parameter is no longer used. - * - * @deprecated use computeBounds(RectF) instead */ - @Deprecated @SuppressWarnings({"UnusedDeclaration"}) public void computeBounds(@NonNull RectF bounds, boolean exact) { computeBounds(bounds); diff --git a/nfc/api/system-current.txt b/nfc/api/system-current.txt index 3ed9b7667be7..e97b15d3b926 100644 --- a/nfc/api/system-current.txt +++ b/nfc/api/system-current.txt @@ -124,6 +124,7 @@ package android.nfc { @FlaggedApi("android.nfc.nfc_oem_extension") public abstract class NfcRoutingTableEntry { method public int getNfceeId(); + method public int getRouteType(); method public int getType(); field public static final int TYPE_AID = 0; // 0x0 field public static final int TYPE_PROTOCOL = 1; // 0x1 diff --git a/nfc/java/android/nfc/Entry.java b/nfc/java/android/nfc/Entry.java index 49d0f10dbfce..aa5ba58e7179 100644 --- a/nfc/java/android/nfc/Entry.java +++ b/nfc/java/android/nfc/Entry.java @@ -25,11 +25,13 @@ public final class Entry implements Parcelable { private final byte mType; private final byte mNfceeId; private final String mEntry; + private final String mRoutingType; - public Entry(String entry, byte type, byte nfceeId) { + public Entry(String entry, byte type, byte nfceeId, String routingType) { mEntry = entry; mType = type; mNfceeId = nfceeId; + mRoutingType = routingType; } public byte getType() { @@ -44,6 +46,10 @@ public final class Entry implements Parcelable { return mEntry; } + public String getRoutingType() { + return mRoutingType; + } + @Override public int describeContents() { return 0; @@ -53,6 +59,7 @@ public final class Entry implements Parcelable { this.mEntry = in.readString(); this.mNfceeId = in.readByte(); this.mType = in.readByte(); + this.mRoutingType = in.readString(); } public static final @NonNull Parcelable.Creator<Entry> CREATOR = @@ -73,5 +80,6 @@ public final class Entry implements Parcelable { dest.writeString(mEntry); dest.writeByte(mNfceeId); dest.writeByte(mType); + dest.writeString(mRoutingType); } } diff --git a/nfc/java/android/nfc/NfcOemExtension.java b/nfc/java/android/nfc/NfcOemExtension.java index f78161e7cad0..fb11875ec7d7 100644 --- a/nfc/java/android/nfc/NfcOemExtension.java +++ b/nfc/java/android/nfc/NfcOemExtension.java @@ -887,18 +887,22 @@ public final class NfcOemExtension { switch (entry.getType()) { case TYPE_TECHNOLOGY -> result.add( new RoutingTableTechnologyEntry(entry.getNfceeId(), - RoutingTableTechnologyEntry.techStringToInt(entry.getEntry())) + RoutingTableTechnologyEntry.techStringToInt(entry.getEntry()), + routeStringToInt(entry.getRoutingType())) ); case TYPE_PROTOCOL -> result.add( new RoutingTableProtocolEntry(entry.getNfceeId(), - RoutingTableProtocolEntry.protocolStringToInt(entry.getEntry())) + RoutingTableProtocolEntry.protocolStringToInt(entry.getEntry()), + routeStringToInt(entry.getRoutingType())) ); case TYPE_AID -> result.add( - new RoutingTableAidEntry(entry.getNfceeId(), entry.getEntry()) + new RoutingTableAidEntry(entry.getNfceeId(), entry.getEntry(), + routeStringToInt(entry.getRoutingType())) ); case TYPE_SYSTEMCODE -> result.add( new RoutingTableSystemCodeEntry(entry.getNfceeId(), - entry.getEntry().getBytes(StandardCharsets.UTF_8)) + entry.getEntry().getBytes(StandardCharsets.UTF_8), + routeStringToInt(entry.getRoutingType())) ); } } diff --git a/nfc/java/android/nfc/NfcRoutingTableEntry.java b/nfc/java/android/nfc/NfcRoutingTableEntry.java index c2cbbede9b75..4153779a8ba2 100644 --- a/nfc/java/android/nfc/NfcRoutingTableEntry.java +++ b/nfc/java/android/nfc/NfcRoutingTableEntry.java @@ -19,6 +19,7 @@ package android.nfc; import android.annotation.FlaggedApi; import android.annotation.IntDef; import android.annotation.SystemApi; +import android.nfc.cardemulation.CardEmulation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -35,6 +36,7 @@ import java.lang.annotation.RetentionPolicy; public abstract class NfcRoutingTableEntry { private final int mNfceeId; private final int mType; + private final int mRouteType; /** * AID routing table type. @@ -67,9 +69,11 @@ public abstract class NfcRoutingTableEntry { public @interface RoutingTableType {} /** @hide */ - protected NfcRoutingTableEntry(int nfceeId, @RoutingTableType int type) { + protected NfcRoutingTableEntry(int nfceeId, @RoutingTableType int type, + @CardEmulation.ProtocolAndTechnologyRoute int routeType) { mNfceeId = nfceeId; mType = type; + mRouteType = routeType; } /** @@ -88,4 +92,14 @@ public abstract class NfcRoutingTableEntry { public int getType() { return mType; } + + /** + * Get the route type of this entry. + * @return an integer defined in + * {@link android.nfc.cardemulation.CardEmulation.ProtocolAndTechnologyRoute} + */ + @CardEmulation.ProtocolAndTechnologyRoute + public int getRouteType() { + return mRouteType; + } } diff --git a/nfc/java/android/nfc/RoutingTableAidEntry.java b/nfc/java/android/nfc/RoutingTableAidEntry.java index bf697d662bd6..be94f9fc117c 100644 --- a/nfc/java/android/nfc/RoutingTableAidEntry.java +++ b/nfc/java/android/nfc/RoutingTableAidEntry.java @@ -18,6 +18,7 @@ package android.nfc; import android.annotation.FlaggedApi; import android.annotation.NonNull; import android.annotation.SystemApi; +import android.nfc.cardemulation.CardEmulation; /** * Represents an Application ID (AID) entry in current routing table. @@ -29,8 +30,9 @@ public class RoutingTableAidEntry extends NfcRoutingTableEntry { private final String mValue; /** @hide */ - public RoutingTableAidEntry(int nfceeId, String value) { - super(nfceeId, TYPE_AID); + public RoutingTableAidEntry(int nfceeId, String value, + @CardEmulation.ProtocolAndTechnologyRoute int routeType) { + super(nfceeId, TYPE_AID, routeType); this.mValue = value; } diff --git a/nfc/java/android/nfc/RoutingTableProtocolEntry.java b/nfc/java/android/nfc/RoutingTableProtocolEntry.java index 536de4d7430e..a68d8c167865 100644 --- a/nfc/java/android/nfc/RoutingTableProtocolEntry.java +++ b/nfc/java/android/nfc/RoutingTableProtocolEntry.java @@ -18,6 +18,7 @@ package android.nfc; import android.annotation.FlaggedApi; import android.annotation.IntDef; import android.annotation.SystemApi; +import android.nfc.cardemulation.CardEmulation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -96,8 +97,9 @@ public class RoutingTableProtocolEntry extends NfcRoutingTableEntry { private final @ProtocolValue int mValue; /** @hide */ - public RoutingTableProtocolEntry(int nfceeId, @ProtocolValue int value) { - super(nfceeId, TYPE_PROTOCOL); + public RoutingTableProtocolEntry(int nfceeId, @ProtocolValue int value, + @CardEmulation.ProtocolAndTechnologyRoute int routeType) { + super(nfceeId, TYPE_PROTOCOL, routeType); this.mValue = value; } diff --git a/nfc/java/android/nfc/RoutingTableSystemCodeEntry.java b/nfc/java/android/nfc/RoutingTableSystemCodeEntry.java index f61892d31668..06cc0a5f26f1 100644 --- a/nfc/java/android/nfc/RoutingTableSystemCodeEntry.java +++ b/nfc/java/android/nfc/RoutingTableSystemCodeEntry.java @@ -18,6 +18,7 @@ package android.nfc; import android.annotation.FlaggedApi; import android.annotation.NonNull; import android.annotation.SystemApi; +import android.nfc.cardemulation.CardEmulation; /** * Represents a system code entry in current routing table, where system codes are two-byte values @@ -31,8 +32,9 @@ public class RoutingTableSystemCodeEntry extends NfcRoutingTableEntry { private final byte[] mValue; /** @hide */ - public RoutingTableSystemCodeEntry(int nfceeId, byte[] value) { - super(nfceeId, TYPE_SYSTEM_CODE); + public RoutingTableSystemCodeEntry(int nfceeId, byte[] value, + @CardEmulation.ProtocolAndTechnologyRoute int routeType) { + super(nfceeId, TYPE_SYSTEM_CODE, routeType); this.mValue = value; } diff --git a/nfc/java/android/nfc/RoutingTableTechnologyEntry.java b/nfc/java/android/nfc/RoutingTableTechnologyEntry.java index 2dbc94232b0b..86239ce7a6b2 100644 --- a/nfc/java/android/nfc/RoutingTableTechnologyEntry.java +++ b/nfc/java/android/nfc/RoutingTableTechnologyEntry.java @@ -18,6 +18,7 @@ package android.nfc; import android.annotation.FlaggedApi; import android.annotation.IntDef; import android.annotation.SystemApi; +import android.nfc.cardemulation.CardEmulation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -77,8 +78,9 @@ public class RoutingTableTechnologyEntry extends NfcRoutingTableEntry { private final @TechnologyValue int mValue; /** @hide */ - public RoutingTableTechnologyEntry(int nfceeId, @TechnologyValue int value) { - super(nfceeId, TYPE_TECHNOLOGY); + public RoutingTableTechnologyEntry(int nfceeId, @TechnologyValue int value, + @CardEmulation.ProtocolAndTechnologyRoute int routeType) { + super(nfceeId, TYPE_TECHNOLOGY, routeType); this.mValue = value; } diff --git a/nfc/java/android/nfc/cardemulation/HostApduService.java b/nfc/java/android/nfc/cardemulation/HostApduService.java index 4f601f0704b4..db1f6a2bb3b1 100644 --- a/nfc/java/android/nfc/cardemulation/HostApduService.java +++ b/nfc/java/android/nfc/cardemulation/HostApduService.java @@ -107,7 +107,7 @@ import java.util.List; * <intent-filter> * <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE"/> * </intent-filter> - * <meta-data android:name="android.nfc.cardemulation.host_apdu_ervice" android:resource="@xml/apduservice"/> + * <meta-data android:name="android.nfc.cardemulation.host_apdu_service" android:resource="@xml/apduservice"/> * </service></pre> * * This meta-data tag points to an apduservice.xml file. diff --git a/nfc/java/android/nfc/cardemulation/OffHostApduService.java b/nfc/java/android/nfc/cardemulation/OffHostApduService.java index 2286e8476d94..8d8a17270523 100644 --- a/nfc/java/android/nfc/cardemulation/OffHostApduService.java +++ b/nfc/java/android/nfc/cardemulation/OffHostApduService.java @@ -96,7 +96,7 @@ import android.os.IBinder; * <intent-filter> * <action android:name="android.nfc.cardemulation.action.OFF_HOST_APDU_SERVICE"/> * </intent-filter> - * <meta-data android:name="android.nfc.cardemulation.off_host_apdu_ervice" android:resource="@xml/apduservice"/> + * <meta-data android:name="android.nfc.cardemulation.off_host_apdu_service" android:resource="@xml/apduservice"/> * </service></pre> * * This meta-data tag points to an apduservice.xml file. diff --git a/nfc/tests/src/android/nfc/NdefRecordTest.java b/nfc/tests/src/android/nfc/NdefRecordTest.java index 231e939b4fbe..044c67448329 100644 --- a/nfc/tests/src/android/nfc/NdefRecordTest.java +++ b/nfc/tests/src/android/nfc/NdefRecordTest.java @@ -24,6 +24,8 @@ import androidx.test.filters.SmallTest; import org.junit.Test; import org.junit.runner.RunWith; +import java.util.Locale; + @SmallTest @RunWith(AndroidJUnit4.class) public class NdefRecordTest { @@ -56,4 +58,20 @@ public class NdefRecordTest { assertThat(ndefRecord.getType()).isEqualTo(NdefRecord.RTD_URI); } + @Test + public void testCreateMime() { + NdefRecord ndefRecord = NdefRecord.createMime("text/plain", "example".getBytes()); + assertThat(ndefRecord).isNotNull(); + assertThat(ndefRecord.getTnf()).isEqualTo(NdefRecord.TNF_MIME_MEDIA); + } + + @Test + public void testCreateTextRecord() { + String languageCode = Locale.getDefault().getLanguage(); + NdefRecord ndefRecord = NdefRecord.createTextRecord(languageCode, "testdata"); + assertThat(ndefRecord).isNotNull(); + assertThat(ndefRecord.getTnf()).isEqualTo(NdefRecord.TNF_WELL_KNOWN); + assertThat(ndefRecord.getType()).isEqualTo(NdefRecord.RTD_TEXT); + } + } diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java index fc7802c9f9da..68b66dfa2657 100644 --- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java +++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java @@ -178,11 +178,6 @@ final class SettingsState { private static final String APEX_DIR = "/apex"; private static final String APEX_ACONFIG_PATH_SUFFIX = "/etc/aconfig_flags.pb"; - private static final String STORAGE_MIGRATION_FLAG = - "core_experiments_team_internal/com.android.providers.settings.storage_test_mission_1"; - private static final String STORAGE_MIGRATION_MARKER_FILE = - "/metadata/aconfig_test_missions/mission_1"; - /** * This tag is applied to all aconfig default value-loaded flags. */ @@ -1740,32 +1735,6 @@ final class SettingsState { } } - if (isConfigSettingsKey(mKey) && name != null - && name.equals(STORAGE_MIGRATION_FLAG)) { - if (value.equals("true")) { - Path path = Paths.get(STORAGE_MIGRATION_MARKER_FILE); - if (!Files.exists(path)) { - Files.createFile(path); - } - - Set<PosixFilePermission> perms = - Files.readAttributes(path, PosixFileAttributes.class).permissions(); - perms.add(PosixFilePermission.OWNER_WRITE); - perms.add(PosixFilePermission.OWNER_READ); - perms.add(PosixFilePermission.GROUP_READ); - perms.add(PosixFilePermission.OTHERS_READ); - try { - Files.setPosixFilePermissions(path, perms); - } catch (Exception e) { - Slog.e(LOG_TAG, "failed to set permissions on migration marker", e); - } - } else { - java.nio.file.Path path = Paths.get(STORAGE_MIGRATION_MARKER_FILE); - if (Files.exists(path)) { - Files.delete(path); - } - } - } mSettings.put(name, new Setting(name, value, defaultValue, packageName, tag, fromSystem, id, isPreservedInRestore)); diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml index 676ff97226ed..acff44957c1f 100644 --- a/packages/Shell/AndroidManifest.xml +++ b/packages/Shell/AndroidManifest.xml @@ -65,7 +65,6 @@ <uses-permission android:name="com.android.voicemail.permission.ADD_VOICEMAIL" /> <uses-permission android:name="android.permission.WRITE_EMBEDDED_SUBSCRIPTIONS" /> <uses-permission android:name="android.permission.GET_PROCESS_STATE_AND_OOM_SCORE" /> - <uses-permission android:name="android.permission.READ_DROPBOX_DATA" /> <uses-permission android:name="android.permission.READ_LOGS" /> <uses-permission android:name="android.permission.BRIGHTNESS_SLIDER_USAGE" /> <uses-permission android:name="android.permission.ACCESS_AMBIENT_LIGHT_STATS" /> diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java index 7f5839d4f1fb..057fb68bad78 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java @@ -1873,7 +1873,9 @@ public class KeyguardUpdateMonitor implements TrustManager.TrustListener, Dumpab if (posture == DEVICE_POSTURE_OPENED) { mLogger.d("Posture changed to open - attempting to request active" + " unlock and run face auth"); - getFaceAuthInteractor().onDeviceUnfolded(); + if (getFaceAuthInteractor() != null) { + getFaceAuthInteractor().onDeviceUnfolded(); + } requestActiveUnlockFromWakeReason(PowerManager.WAKE_REASON_UNFOLD_DEVICE, false); } diff --git a/ravenwood/Android.bp b/ravenwood/Android.bp index 66c8d0fa32f9..59043a8356ae 100644 --- a/ravenwood/Android.bp +++ b/ravenwood/Android.bp @@ -182,21 +182,6 @@ java_device_for_host { visibility: [":__subpackages__"], } -// Separated out from ravenwood-junit-impl since it needs to compile -// against `module_current` -java_library { - name: "ravenwood-junit-impl-flag", - srcs: [ - "junit-flag-src/**/*.java", - ], - sdk_version: "module_current", - libs: [ - "junit", - "flag-junit", - ], - visibility: ["//visibility:public"], -} - // Carefully compiles against only module_current to support tests that // want to verify they're unbundled. The "impl" library above is what // ships inside the Ravenwood environment to actually drive any API @@ -651,7 +636,6 @@ android_ravenwood_libgroup { "flag-junit", "ravenwood-framework", "ravenwood-junit-impl", - "ravenwood-junit-impl-flag", "mockito-ravenwood-prebuilt", "inline-mockito-ravenwood-prebuilt", diff --git a/ravenwood/junit-flag-src/android/platform/test/flag/junit/RavenwoodFlagsValueProvider.java b/ravenwood/junit-flag-src/android/platform/test/flag/junit/RavenwoodFlagsValueProvider.java deleted file mode 100644 index 9d6277473298..000000000000 --- a/ravenwood/junit-flag-src/android/platform/test/flag/junit/RavenwoodFlagsValueProvider.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2024 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.platform.test.flag.junit; - -import android.platform.test.flag.junit.CheckFlagsRule; -import android.platform.test.flag.junit.IFlagsValueProvider; - -/** - * Offer to create {@link CheckFlagsRule} instances that are useful on the Ravenwood deviceless - * testing environment. - * - * At the moment, default flag values are not available on Ravenwood, so the only options offered - * here are "all-on" and "all-off" options. Tests that want to exercise specific flag states should - * use {@link android.platform.test.flag.junit.SetFlagsRule}. - */ -public class RavenwoodFlagsValueProvider { - /** - * Create a {@link CheckFlagsRule} instance where flags are in an "all-on" state. - */ - public static CheckFlagsRule createAllOnCheckFlagsRule() { - return new CheckFlagsRule(new IFlagsValueProvider() { - @Override - public boolean getBoolean(String flag) { - return true; - } - }); - } - - /** - * Create a {@link CheckFlagsRule} instance where flags are in an "all-off" state. - */ - public static CheckFlagsRule createAllOffCheckFlagsRule() { - return new CheckFlagsRule(new IFlagsValueProvider() { - @Override - public boolean getBoolean(String flag) { - return false; - } - }); - } -} diff --git a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodAwareTestRunner.java b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodAwareTestRunner.java index 9644a52a749e..3ebef02284d6 100644 --- a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodAwareTestRunner.java +++ b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodAwareTestRunner.java @@ -129,7 +129,7 @@ public final class RavenwoodAwareTestRunner extends RavenwoodAwareTestRunnerBase mTestClass = new TestClass(testClass); - Log.v(TAG, "RavenwoodAwareTestRunner starting for " + testClass.getCanonicalName()); + Log.v(TAG, "RavenwoodAwareTestRunner initializing for " + testClass.getCanonicalName()); // Hook point to allow more customization. runAnnotatedMethodsOnRavenwood(RavenwoodTestRunnerInitializing.class, null); @@ -146,7 +146,9 @@ public final class RavenwoodAwareTestRunner extends RavenwoodAwareTestRunnerBase private void runAnnotatedMethodsOnRavenwood(Class<? extends Annotation> annotationClass, Object instance) { - Log.v(TAG, "runAnnotatedMethodsOnRavenwood() " + annotationClass.getName()); + if (RAVENWOOD_VERBOSE_LOGGING) { + Log.v(TAG, "runAnnotatedMethodsOnRavenwood() " + annotationClass.getName()); + } for (var method : mTestClass.getAnnotatedMethods(annotationClass)) { ensureIsPublicVoidMethod(method.getMethod(), /* isStatic=*/ instance == null); @@ -169,12 +171,14 @@ public final class RavenwoodAwareTestRunner extends RavenwoodAwareTestRunnerBase RavenwoodTestStats.getInstance().attachToRunNotifier(notifier); if (mRealRunner instanceof ClassSkippingTestRunner) { - Log.i(TAG, "onClassSkipped: description=" + description); + Log.v(TAG, "onClassSkipped: description=" + description); mRealRunner.run(notifier); return; } - Log.v(TAG, "Starting " + mTestJavaClass.getCanonicalName()); + if (RAVENWOOD_VERBOSE_LOGGING) { + Log.v(TAG, "Running " + mTestJavaClass.getCanonicalName()); + } if (RAVENWOOD_VERBOSE_LOGGING) { dumpDescription(description); } diff --git a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodRunnerState.java b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodRunnerState.java index a5d0bfd51a0f..70bc52bdaa12 100644 --- a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodRunnerState.java +++ b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodRunnerState.java @@ -15,6 +15,8 @@ */ package android.platform.test.ravenwood; +import static com.android.ravenwood.common.RavenwoodCommonUtils.RAVENWOOD_VERBOSE_LOGGING; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -59,16 +61,22 @@ public final class RavenwoodRunnerState { private Description mMethodDescription; public void enterTestRunner() { - Log.i(TAG, "enterTestRunner: " + mRunner); + if (RAVENWOOD_VERBOSE_LOGGING) { + Log.v(TAG, "enterTestRunner: " + mRunner); + } RavenwoodRuntimeEnvironmentController.initForRunner(); } public void enterTestClass() { - Log.i(TAG, "enterTestClass: " + mRunner.mTestJavaClass.getName()); + if (RAVENWOOD_VERBOSE_LOGGING) { + Log.v(TAG, "enterTestClass: " + mRunner.mTestJavaClass.getName()); + } } public void exitTestClass() { - Log.i(TAG, "exitTestClass: " + mRunner.mTestJavaClass.getName()); + if (RAVENWOOD_VERBOSE_LOGGING) { + Log.v(TAG, "exitTestClass: " + mRunner.mTestJavaClass.getName()); + } assertTrue(RAVENWOOD_RULE_ERROR, sActiveProperties.isEmpty()); RavenwoodRuntimeEnvironmentController.exitTestClass(); } diff --git a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodRuntimeEnvironmentController.java b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodRuntimeEnvironmentController.java index 930914f586eb..3cb6c5a6bd16 100644 --- a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodRuntimeEnvironmentController.java +++ b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodRuntimeEnvironmentController.java @@ -552,7 +552,7 @@ public class RavenwoodRuntimeEnvironmentController { } private static void dumpCommandLineArgs() { - Log.i(TAG, "JVM arguments:"); + Log.v(TAG, "JVM arguments:"); // Note, we use the wrapper in JUnit4, not the actual class ( // java.lang.management.ManagementFactory), because we can't see the later at the build @@ -561,7 +561,7 @@ public class RavenwoodRuntimeEnvironmentController { var args = ManagementFactory.getRuntimeMXBean().getInputArguments(); for (var arg : args) { - Log.i(TAG, " " + arg); + Log.v(TAG, " " + arg); } } } diff --git a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodSystemProperties.java b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodSystemProperties.java index fac07910be11..70c161c1f19a 100644 --- a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodSystemProperties.java +++ b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodSystemProperties.java @@ -84,7 +84,7 @@ public class RavenwoodSystemProperties { var ravenwoodProps = readProperties(path + RAVENWOOD_BUILD_PROP); var deviceProps = readProperties(path + DEVICE_BUILD_PROP); - Log.i(TAG, "Default system properties:"); + Log.v(TAG, "Default system properties:"); ravenwoodProps.forEach((key, origValue) -> { final String value; @@ -100,7 +100,7 @@ public class RavenwoodSystemProperties { } else { value = origValue; } - Log.i(TAG, key + "=" + value); + Log.v(TAG, key + "=" + value); sDefaultValues.put(key, value); }); diff --git a/ravenwood/junit-src/android/platform/test/ravenwood/RavenwoodAwareTestRunnerBase.java b/ravenwood/junit-src/android/platform/test/ravenwood/RavenwoodAwareTestRunnerBase.java index f3688d664142..359210582ba5 100644 --- a/ravenwood/junit-src/android/platform/test/ravenwood/RavenwoodAwareTestRunnerBase.java +++ b/ravenwood/junit-src/android/platform/test/ravenwood/RavenwoodAwareTestRunnerBase.java @@ -15,6 +15,8 @@ */ package android.platform.test.ravenwood; +import static com.android.ravenwood.common.RavenwoodCommonUtils.RAVENWOOD_VERBOSE_LOGGING; + import android.platform.test.annotations.internal.InnerRunner; import android.util.Log; @@ -53,7 +55,9 @@ abstract class RavenwoodAwareTestRunnerBase extends Runner implements Filterable } try { - Log.i(TAG, "Initializing the inner runner: " + runnerClass); + if (RAVENWOOD_VERBOSE_LOGGING) { + Log.v(TAG, "Initializing the inner runner: " + runnerClass); + } try { return runnerClass.getConstructor(Class.class) .newInstance(testClass.getJavaClass()); diff --git a/ravenwood/runtime-jni/ravenwood_initializer.cpp b/ravenwood/runtime-jni/ravenwood_initializer.cpp index dbbc3453b2f1..391c5d56b212 100644 --- a/ravenwood/runtime-jni/ravenwood_initializer.cpp +++ b/ravenwood/runtime-jni/ravenwood_initializer.cpp @@ -140,7 +140,7 @@ static void check_system_property_access(const char* key, bool write) { if (gVM != nullptr && gRunnerState != nullptr) { JNIEnv* env; if (gVM->GetEnv((void**)&env, JNI_VERSION_1_4) >= 0) { - ALOGI("%s access to system property '%s'", write ? "Write" : "Read", key); + ALOGV("%s access to system property '%s'", write ? "Write" : "Read", key); env->CallStaticVoidMethod(gRunnerState, gCheckSystemPropertyAccess, env->NewStringUTF(key), write ? JNI_TRUE : JNI_FALSE); return; @@ -208,7 +208,7 @@ static const JNINativeMethod sMethods[] = { }; extern "C" jint JNI_OnLoad(JavaVM* vm, void* /* reserved */) { - ALOGI("%s: JNI_OnLoad", __FILE__); + ALOGV("%s: JNI_OnLoad", __FILE__); maybeRedirectLog(); diff --git a/ravenwood/runtime-jni/ravenwood_runtime.cpp b/ravenwood/runtime-jni/ravenwood_runtime.cpp index bab4c7e0fd14..8d8ed7119e84 100644 --- a/ravenwood/runtime-jni/ravenwood_runtime.cpp +++ b/ravenwood/runtime-jni/ravenwood_runtime.cpp @@ -204,7 +204,7 @@ static const JNINativeMethod sMethods[] = }; extern "C" jint JNI_OnLoad(JavaVM* vm, void* /* reserved */) { - ALOGI("%s: JNI_OnLoad", __FILE__); + ALOGV("%s: JNI_OnLoad", __FILE__); JNIEnv* env = GetJNIEnvOrDie(vm); g_StructStat = FindGlobalClassOrDie(env, "android/system/StructStat"); diff --git a/services/core/java/android/content/pm/PackageManagerInternal.java b/services/core/java/android/content/pm/PackageManagerInternal.java index 43774bbc51ca..b0dae6a1f306 100644 --- a/services/core/java/android/content/pm/PackageManagerInternal.java +++ b/services/core/java/android/content/pm/PackageManagerInternal.java @@ -90,6 +90,7 @@ public abstract class PackageManagerInternal { */ public static final int RESOLVE_NON_RESOLVER_ONLY = 0x00000002; + @Deprecated @IntDef(value = { INTEGRITY_VERIFICATION_ALLOW, INTEGRITY_VERIFICATION_REJECT, @@ -97,18 +98,10 @@ public abstract class PackageManagerInternal { @Retention(RetentionPolicy.SOURCE) public @interface IntegrityVerificationResult {} - /** - * Used as the {@code verificationCode} argument for - * {@link PackageManagerInternal#setIntegrityVerificationResult(int, int)} to indicate that the - * integrity component allows the install to proceed. - */ + @Deprecated public static final int INTEGRITY_VERIFICATION_ALLOW = 1; - /** - * Used as the {@code verificationCode} argument for - * {@link PackageManagerInternal#setIntegrityVerificationResult(int, int)} to indicate that the - * integrity component does not allow install to proceed. - */ + @Deprecated public static final int INTEGRITY_VERIFICATION_REJECT = 0; /** @@ -1131,17 +1124,13 @@ public abstract class PackageManagerInternal { public abstract boolean isPermissionUpgradeNeeded(@UserIdInt int userId); /** - * Allows the integrity component to respond to the - * {@link Intent#ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION package verification - * broadcast} to respond to the package manager. The response must include - * the {@code verificationCode} which is one of - * {@link #INTEGRITY_VERIFICATION_ALLOW} and {@link #INTEGRITY_VERIFICATION_REJECT}. + * Used to allow the integrity component to respond to the + * ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION package verification + * broadcast to respond to the package manager. * - * @param verificationId pending package identifier as passed via the - * {@link PackageManager#EXTRA_VERIFICATION_ID} Intent extra. - * @param verificationResult either {@link #INTEGRITY_VERIFICATION_ALLOW} - * or {@link #INTEGRITY_VERIFICATION_REJECT}. + * Deprecated. */ + @Deprecated public abstract void setIntegrityVerificationResult(int verificationId, @IntegrityVerificationResult int verificationResult); diff --git a/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java b/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java index a132876b72a3..0914b7e3eeb2 100644 --- a/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java +++ b/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java @@ -93,29 +93,6 @@ public class AppIntegrityManagerServiceImpl extends IAppIntegrityManager.Stub { mContext = context; mPackageManagerInternal = packageManagerInternal; mHandler = handler; - - IntentFilter integrityVerificationFilter = new IntentFilter(); - integrityVerificationFilter.addAction(ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION); - try { - integrityVerificationFilter.addDataType(PACKAGE_MIME_TYPE); - } catch (IntentFilter.MalformedMimeTypeException e) { - throw new RuntimeException("Mime type malformed: should never happen.", e); - } - - mContext.registerReceiver( - new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - if (!ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION.equals( - intent.getAction())) { - return; - } - mHandler.post(() -> handleIntegrityVerification(intent)); - } - }, - integrityVerificationFilter, - /* broadcastPermission= */ null, - mHandler); } @Override @@ -157,10 +134,4 @@ public class AppIntegrityManagerServiceImpl extends IAppIntegrityManager.Stub { public List<String> getWhitelistedRuleProviders() { return Collections.emptyList(); } - - private void handleIntegrityVerification(Intent intent) { - int verificationId = intent.getIntExtra(EXTRA_VERIFICATION_ID, -1); - mPackageManagerInternal.setIntegrityVerificationResult( - verificationId, PackageManagerInternal.INTEGRITY_VERIFICATION_ALLOW); - } } diff --git a/services/core/java/com/android/server/pm/PackageHandler.java b/services/core/java/com/android/server/pm/PackageHandler.java index 0a0882d80cc1..4ea405441030 100644 --- a/services/core/java/com/android/server/pm/PackageHandler.java +++ b/services/core/java/com/android/server/pm/PackageHandler.java @@ -18,7 +18,6 @@ package com.android.server.pm; import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; -import static com.android.server.pm.PackageManagerService.CHECK_PENDING_INTEGRITY_VERIFICATION; import static com.android.server.pm.PackageManagerService.CHECK_PENDING_VERIFICATION; import static com.android.server.pm.PackageManagerService.DEBUG_INSTALL; import static com.android.server.pm.PackageManagerService.DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD; @@ -29,7 +28,6 @@ import static com.android.server.pm.PackageManagerService.DOMAIN_VERIFICATION; import static com.android.server.pm.PackageManagerService.ENABLE_ROLLBACK_STATUS; import static com.android.server.pm.PackageManagerService.ENABLE_ROLLBACK_TIMEOUT; import static com.android.server.pm.PackageManagerService.INSTANT_APP_RESOLUTION_PHASE_TWO; -import static com.android.server.pm.PackageManagerService.INTEGRITY_VERIFICATION_COMPLETE; import static com.android.server.pm.PackageManagerService.PACKAGE_VERIFIED; import static com.android.server.pm.PackageManagerService.POST_INSTALL; import static com.android.server.pm.PackageManagerService.PRUNE_UNUSED_STATIC_SHARED_LIBRARIES; @@ -149,42 +147,6 @@ final class PackageHandler extends Handler { break; } - case CHECK_PENDING_INTEGRITY_VERIFICATION: { - final int verificationId = msg.arg1; - final PackageVerificationState state = mPm.mPendingVerification.get(verificationId); - - if (state != null && !state.isIntegrityVerificationComplete()) { - final VerifyingSession verifyingSession = state.getVerifyingSession(); - final Uri originUri = Uri.fromFile(verifyingSession.mOriginInfo.mResolvedFile); - - String errorMsg = "Integrity verification timed out for " + originUri; - Slog.i(TAG, errorMsg); - - state.setIntegrityVerificationResult( - getDefaultIntegrityVerificationResponse()); - - if (getDefaultIntegrityVerificationResponse() - == PackageManagerInternal.INTEGRITY_VERIFICATION_ALLOW) { - Slog.i(TAG, "Integrity check times out, continuing with " + originUri); - } else { - verifyingSession.setReturnCode( - PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE, - errorMsg); - } - - if (state.areAllVerificationsComplete()) { - mPm.mPendingVerification.remove(verificationId); - } - - Trace.asyncTraceEnd( - TRACE_TAG_PACKAGE_MANAGER, - "integrity_verification", - verificationId); - - verifyingSession.handleIntegrityVerificationFinished(); - } - break; - } case PACKAGE_VERIFIED: { final int verificationId = msg.arg1; @@ -205,42 +167,6 @@ final class PackageHandler extends Handler { break; } - case INTEGRITY_VERIFICATION_COMPLETE: { - final int verificationId = msg.arg1; - - final PackageVerificationState state = mPm.mPendingVerification.get(verificationId); - if (state == null) { - Slog.w(TAG, "Integrity verification with id " + verificationId - + " not found. It may be invalid or overridden by verifier"); - break; - } - - final int response = (Integer) msg.obj; - final VerifyingSession verifyingSession = state.getVerifyingSession(); - final Uri originUri = Uri.fromFile(verifyingSession.mOriginInfo.mResolvedFile); - - state.setIntegrityVerificationResult(response); - - if (response == PackageManagerInternal.INTEGRITY_VERIFICATION_ALLOW) { - Slog.i(TAG, "Integrity check passed for " + originUri); - } else { - verifyingSession.setReturnCode( - PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE, - "Integrity check failed for " + originUri); - } - - if (state.areAllVerificationsComplete()) { - mPm.mPendingVerification.remove(verificationId); - } - - Trace.asyncTraceEnd( - TRACE_TAG_PACKAGE_MANAGER, - "integrity_verification", - verificationId); - - verifyingSession.handleIntegrityVerificationFinished(); - break; - } case INSTANT_APP_RESOLUTION_PHASE_TWO: { InstantAppResolver.doInstantAppResolutionPhaseTwo(mPm.mContext, mPm.snapshotComputer(), diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java index f9c103762815..b22bc2b8c5be 100644 --- a/services/core/java/com/android/server/pm/PackageManagerService.java +++ b/services/core/java/com/android/server/pm/PackageManagerService.java @@ -922,8 +922,8 @@ public class PackageManagerService implements PackageSender, TestUtilityService static final int ENABLE_ROLLBACK_TIMEOUT = 22; static final int DEFERRED_NO_KILL_POST_DELETE = 23; static final int DEFERRED_NO_KILL_INSTALL_OBSERVER = 24; - static final int INTEGRITY_VERIFICATION_COMPLETE = 25; - static final int CHECK_PENDING_INTEGRITY_VERIFICATION = 26; + // static final int UNUSED = 25; + // static final int UNUSED = 26; static final int DOMAIN_VERIFICATION = 27; static final int PRUNE_UNUSED_STATIC_SHARED_LIBRARIES = 28; static final int DEFERRED_PENDING_KILL_INSTALL_OBSERVER = 29; @@ -7023,12 +7023,10 @@ public class PackageManagerService implements PackageSender, TestUtilityService return mSettings.isPermissionUpgradeNeeded(userId); } + @Deprecated @Override public void setIntegrityVerificationResult(int verificationId, int verificationResult) { - final Message msg = mHandler.obtainMessage(INTEGRITY_VERIFICATION_COMPLETE); - msg.arg1 = verificationId; - msg.obj = verificationResult; - mHandler.sendMessage(msg); + // Do nothing. } @Override diff --git a/services/core/java/com/android/server/pm/PackageVerificationState.java b/services/core/java/com/android/server/pm/PackageVerificationState.java index 0b6ccc41d956..63c2ee2e5454 100644 --- a/services/core/java/com/android/server/pm/PackageVerificationState.java +++ b/services/core/java/com/android/server/pm/PackageVerificationState.java @@ -43,8 +43,6 @@ class PackageVerificationState { private boolean mRequiredVerificationPassed; - private boolean mIntegrityVerificationComplete; - /** * Create a new package verification state where {@code requiredVerifierUid} is the user ID for * the package that must reply affirmative before things can continue. @@ -213,15 +211,7 @@ class PackageVerificationState { return mExtendedTimeoutUids.get(uid, false); } - void setIntegrityVerificationResult(int code) { - mIntegrityVerificationComplete = true; - } - - boolean isIntegrityVerificationComplete() { - return mIntegrityVerificationComplete; - } - boolean areAllVerificationsComplete() { - return mIntegrityVerificationComplete && isVerificationComplete(); + return isVerificationComplete(); } } diff --git a/services/core/java/com/android/server/pm/VerifyingSession.java b/services/core/java/com/android/server/pm/VerifyingSession.java index f7eb29fe3ee9..542ae8eb9207 100644 --- a/services/core/java/com/android/server/pm/VerifyingSession.java +++ b/services/core/java/com/android/server/pm/VerifyingSession.java @@ -28,7 +28,6 @@ import static android.os.PowerWhitelistManager.REASON_PACKAGE_VERIFIER; import static android.os.PowerWhitelistManager.TEMPORARY_ALLOWLIST_TYPE_FOREGROUND_SERVICE_ALLOWED; import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; -import static com.android.server.pm.PackageManagerService.CHECK_PENDING_INTEGRITY_VERIFICATION; import static com.android.server.pm.PackageManagerService.CHECK_PENDING_VERIFICATION; import static com.android.server.pm.PackageManagerService.DEBUG_INSTALL; import static com.android.server.pm.PackageManagerService.DEBUG_VERIFY; @@ -87,11 +86,6 @@ final class VerifyingSession { * Whether verification is enabled by default. */ private static final boolean DEFAULT_VERIFY_ENABLE = true; - - /** - * Whether integrity verification is enabled by default. - */ - private static final boolean DEFAULT_INTEGRITY_VERIFY_ENABLE = true; /** * The default maximum time to wait for the integrity verification to return in * milliseconds. @@ -129,7 +123,6 @@ final class VerifyingSession { private final boolean mUserActionRequired; private final int mUserActionRequiredType; private boolean mWaitForVerificationToComplete; - private boolean mWaitForIntegrityVerificationToComplete; private boolean mWaitForEnableRollbackToComplete; private int mRet = PackageManager.INSTALL_SUCCEEDED; private String mErrorMessage = null; @@ -217,7 +210,6 @@ final class VerifyingSession { new PackageVerificationState(this); mPm.mPendingVerification.append(verificationId, verificationState); - sendIntegrityVerificationRequest(verificationId, pkgLite, verificationState); sendPackageVerificationRequest( verificationId, pkgLite, verificationState); @@ -270,89 +262,6 @@ final class VerifyingSession { mPm.mHandler.sendMessageDelayed(msg, rollbackTimeout); } - /** - * Send a request to check the integrity of the package. - */ - void sendIntegrityVerificationRequest( - int verificationId, - PackageInfoLite pkgLite, - PackageVerificationState verificationState) { - if (!isIntegrityVerificationEnabled()) { - // Consider the integrity check as passed. - verificationState.setIntegrityVerificationResult( - PackageManagerInternal.INTEGRITY_VERIFICATION_ALLOW); - return; - } - - final Intent integrityVerification = - new Intent(Intent.ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION); - - integrityVerification.setDataAndType(Uri.fromFile(new File(mOriginInfo.mResolvedPath)), - PACKAGE_MIME_TYPE); - - final int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION - | Intent.FLAG_RECEIVER_REGISTERED_ONLY - | Intent.FLAG_RECEIVER_FOREGROUND; - integrityVerification.addFlags(flags); - - integrityVerification.putExtra(EXTRA_VERIFICATION_ID, verificationId); - integrityVerification.putExtra(EXTRA_PACKAGE_NAME, pkgLite.packageName); - integrityVerification.putExtra(EXTRA_VERSION_CODE, pkgLite.versionCode); - integrityVerification.putExtra(EXTRA_LONG_VERSION_CODE, pkgLite.getLongVersionCode()); - populateInstallerExtras(integrityVerification); - - // send to integrity component only. - integrityVerification.setPackage("android"); - - final BroadcastOptions options = BroadcastOptions.makeBasic(); - - mPm.mContext.sendOrderedBroadcastAsUser(integrityVerification, UserHandle.SYSTEM, - /* receiverPermission= */ null, - /* appOp= */ AppOpsManager.OP_NONE, - /* options= */ options.toBundle(), - new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - final Message msg = - mPm.mHandler.obtainMessage(CHECK_PENDING_INTEGRITY_VERIFICATION); - msg.arg1 = verificationId; - mPm.mHandler.sendMessageDelayed(msg, getIntegrityVerificationTimeout()); - } - }, /* scheduler= */ null, - /* initialCode= */ 0, - /* initialData= */ null, - /* initialExtras= */ null); - - Trace.asyncTraceBegin( - TRACE_TAG_PACKAGE_MANAGER, "integrity_verification", verificationId); - - // stop the copy until verification succeeds. - mWaitForIntegrityVerificationToComplete = true; - } - - - /** - * Get the integrity verification timeout. - * - * @return verification timeout in milliseconds - */ - private long getIntegrityVerificationTimeout() { - long timeout = Settings.Global.getLong(mPm.mContext.getContentResolver(), - Settings.Global.APP_INTEGRITY_VERIFICATION_TIMEOUT, - DEFAULT_INTEGRITY_VERIFICATION_TIMEOUT); - // The setting can be used to increase the timeout but not decrease it, since that is - // equivalent to disabling the integrity component. - return Math.max(timeout, DEFAULT_INTEGRITY_VERIFICATION_TIMEOUT); - } - - /** - * Check whether or not integrity verification has been enabled. - */ - private boolean isIntegrityVerificationEnabled() { - // We are not exposing this as a user-configurable setting because we don't want to provide - // an easy way to get around the integrity check. - return DEFAULT_INTEGRITY_VERIFY_ENABLE; - } /** * Send a request to verifier(s) to verify the package if necessary. @@ -827,11 +736,6 @@ final class VerifyingSession { handleReturnCode(); } - void handleIntegrityVerificationFinished() { - mWaitForIntegrityVerificationToComplete = false; - handleReturnCode(); - } - void handleRollbackEnabled() { // TODO(b/112431924): Consider halting the install if we // couldn't enable rollback. @@ -840,7 +744,7 @@ final class VerifyingSession { } void handleReturnCode() { - if (mWaitForVerificationToComplete || mWaitForIntegrityVerificationToComplete + if (mWaitForVerificationToComplete || mWaitForEnableRollbackToComplete) { return; } diff --git a/services/core/java/com/android/server/vcn/VcnGatewayConnection.java b/services/core/java/com/android/server/vcn/VcnGatewayConnection.java index 9ccf0401e91d..77bda9dc6b14 100644 --- a/services/core/java/com/android/server/vcn/VcnGatewayConnection.java +++ b/services/core/java/com/android/server/vcn/VcnGatewayConnection.java @@ -1228,10 +1228,7 @@ public class VcnGatewayConnection extends StateMachine { @VisibleForTesting(visibility = Visibility.PRIVATE) void setSafeModeAlarm() { - final boolean isFlagSafeModeConfigEnabled = mVcnContext.getFeatureFlags().safeModeConfig(); - logVdbg("isFlagSafeModeConfigEnabled " + isFlagSafeModeConfigEnabled); - - if (isFlagSafeModeConfigEnabled && !mConnectionConfig.isSafeModeEnabled()) { + if (!mConnectionConfig.isSafeModeEnabled()) { logVdbg("setSafeModeAlarm: safe mode disabled"); return; } diff --git a/services/core/java/com/android/server/vibrator/VibrationSettings.java b/services/core/java/com/android/server/vibrator/VibrationSettings.java index 227b6b410e6b..a0dca946a718 100644 --- a/services/core/java/com/android/server/vibrator/VibrationSettings.java +++ b/services/core/java/com/android/server/vibrator/VibrationSettings.java @@ -31,6 +31,7 @@ import static android.os.VibrationAttributes.USAGE_UNKNOWN; import android.annotation.NonNull; import android.annotation.Nullable; import android.app.ActivityManager; +import android.app.IActivityManager; import android.app.SynchronousUserSwitchObserver; import android.app.UidObserver; import android.content.BroadcastReceiver; @@ -73,6 +74,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.Set; /** Controls all the system settings related to vibration. */ @@ -146,9 +148,6 @@ final class VibrationSettings { PowerManager.GO_TO_SLEEP_REASON_INATTENTIVE, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT)); - private static final IntentFilter INTERNAL_RINGER_MODE_CHANGED_INTENT_FILTER = - new IntentFilter(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION); - /** Listener for changes on vibration settings. */ interface OnVibratorSettingsChanged { /** Callback triggered when any of the vibrator settings change. */ @@ -157,15 +156,18 @@ final class VibrationSettings { private final Object mLock = new Object(); private final Context mContext; - private final String mSystemUiPackage; @VisibleForTesting final SettingsContentObserver mSettingObserver; @VisibleForTesting - final SettingsBroadcastReceiver mSettingChangeReceiver; + final RingerModeBroadcastReceiver mRingerModeBroadcastReceiver; + @VisibleForTesting + final BatteryBroadcastReceiver mBatteryBroadcastReceiver; @VisibleForTesting final VibrationUidObserver mUidObserver; @VisibleForTesting final VibrationUserSwitchObserver mUserSwitchObserver; + @VisibleForTesting + final VibrationLowPowerModeListener mLowPowerModeListener; @GuardedBy("mLock") private final List<OnVibratorSettingsChanged> mListeners = new ArrayList<>(); @@ -179,10 +181,13 @@ final class VibrationSettings { @GuardedBy("mLock") @Nullable private PowerManagerInternal mPowerManagerInternal; + @GuardedBy("mLock") @Nullable private VirtualDeviceManagerInternal mVirtualDeviceManagerInternal; @GuardedBy("mLock") + private String mSystemUiPackage; + @GuardedBy("mLock") private boolean mVibrateInputDevices; @GuardedBy("mLock") private SparseIntArray mCurrentVibrationIntensities = new SparseIntArray(); @@ -206,11 +211,11 @@ final class VibrationSettings { mContext = context; mVibrationConfig = config; mSettingObserver = new SettingsContentObserver(handler); - mSettingChangeReceiver = new SettingsBroadcastReceiver(); + mRingerModeBroadcastReceiver = new RingerModeBroadcastReceiver(); + mBatteryBroadcastReceiver = new BatteryBroadcastReceiver(); mUidObserver = new VibrationUidObserver(); mUserSwitchObserver = new VibrationUserSwitchObserver(); - mSystemUiPackage = LocalServices.getService(PackageManagerInternal.class) - .getSystemUiServiceComponent().getPackageName(); + mLowPowerModeListener = new VibrationLowPowerModeListener(); VibrationEffect clickEffect = createEffectFromResource( com.android.internal.R.array.config_virtualKeyVibePattern); @@ -234,18 +239,34 @@ final class VibrationSettings { } public void onSystemReady() { - PowerManagerInternal pm = LocalServices.getService(PowerManagerInternal.class); - AudioManager am = mContext.getSystemService(AudioManager.class); - int ringerMode = (am == null) ? mRingerMode : am.getRingerModeInternal(); + onSystemReady(LocalServices.getService(PackageManagerInternal.class), + LocalServices.getService(PowerManagerInternal.class), + ActivityManager.getService(), + LocalServices.getService(VirtualDeviceManagerInternal.class), + mContext.getSystemService(AudioManager.class)); + } + + @VisibleForTesting + void onSystemReady(PackageManagerInternal packageManagerInternal, + PowerManagerInternal powerManagerInternal, + IActivityManager activityManagerInternal, + @Nullable VirtualDeviceManagerInternal virtualDeviceManagerInternal, + @Nullable AudioManager audioManager) { + int ringerMode = (audioManager == null) + ? AudioManager.RINGER_MODE_NORMAL + : audioManager.getRingerModeInternal(); + String sysUiPackage = packageManagerInternal.getSystemUiServiceComponent().getPackageName(); synchronized (mLock) { - mPowerManagerInternal = pm; - mAudioManager = am; + mPowerManagerInternal = powerManagerInternal; + mVirtualDeviceManagerInternal = virtualDeviceManagerInternal; + mAudioManager = audioManager; mRingerMode = ringerMode; + mSystemUiPackage = sysUiPackage; } try { - ActivityManager.getService().registerUidObserver(mUidObserver, + activityManagerInternal.registerUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE, ActivityManager.PROCESS_STATE_UNKNOWN, /* callingPackage= */ null); } catch (RemoteException e) { @@ -253,32 +274,16 @@ final class VibrationSettings { } try { - ActivityManager.getService().registerUserSwitchObserver(mUserSwitchObserver, TAG); + activityManagerInternal.registerUserSwitchObserver(mUserSwitchObserver, TAG); } catch (RemoteException e) { // ignored; both services live in system_server } - pm.registerLowPowerModeObserver( - new PowerManagerInternal.LowPowerModeListener() { - @Override - public int getServiceType() { - return PowerManager.ServiceType.VIBRATION; - } - - @Override - public void onLowPowerModeChanged(PowerSaveState result) { - boolean shouldNotifyListeners; - synchronized (mLock) { - shouldNotifyListeners = result.batterySaverEnabled != mBatterySaverMode; - mBatterySaverMode = result.batterySaverEnabled; - } - if (shouldNotifyListeners) { - notifyListeners(); - } - } - }); - - registerSettingsChangeReceiver(INTERNAL_RINGER_MODE_CHANGED_INTENT_FILTER); + powerManagerInternal.registerLowPowerModeObserver(mLowPowerModeListener); + + mContext.registerReceiver(mRingerModeBroadcastReceiver, + new IntentFilter(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION), + Context.RECEIVER_EXPORTED_UNAUDITED); // Listen to all settings that might affect the result of Vibrator.getVibrationIntensity. registerSettingsObserver(Settings.System.getUriFor(Settings.System.VIBRATE_INPUT_DEVICES)); @@ -302,12 +307,7 @@ final class VibrationSettings { if (mVibrationConfig.ignoreVibrationsOnWirelessCharger()) { Intent batteryStatus = mContext.registerReceiver( - new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - updateBatteryInfo(intent); - } - }, + mBatteryBroadcastReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED), Context.RECEIVER_NOT_EXPORTED); // After registering the receiver for battery status, process the sticky broadcast that @@ -477,8 +477,10 @@ final class VibrationSettings { public boolean shouldCancelVibrationOnScreenOff(@NonNull Vibration.CallerInfo callerInfo, long vibrationStartUptimeMillis) { PowerManagerInternal pm; + String sysUiPackageName; synchronized (mLock) { pm = mPowerManagerInternal; + sysUiPackageName = mSystemUiPackage; } if (pm != null) { // The SleepData from PowerManager may refer to a more recent sleep than the broadcast @@ -502,7 +504,7 @@ final class VibrationSettings { } // Only allow vibrations from System packages to continue vibrating when the screen goes off return callerInfo.uid != Process.SYSTEM_UID && callerInfo.uid != 0 - && !mSystemUiPackage.equals(callerInfo.opPkg); + && !Objects.equals(sysUiPackageName, callerInfo.opPkg); } /** @@ -785,11 +787,6 @@ final class VibrationSettings { UserHandle.USER_ALL); } - private void registerSettingsChangeReceiver(IntentFilter intentFilter) { - mContext.registerReceiver(mSettingChangeReceiver, intentFilter, - Context.RECEIVER_EXPORTED_UNAUDITED); - } - @Nullable private VibrationEffect createEffectFromResource(int resId) { return createEffectFromResource(mContext.getResources(), resId); @@ -836,12 +833,11 @@ final class VibrationSettings { } private boolean isAppRunningOnAnyVirtualDevice(int uid) { - if (mVirtualDeviceManagerInternal == null) { - mVirtualDeviceManagerInternal = - LocalServices.getService(VirtualDeviceManagerInternal.class); + VirtualDeviceManagerInternal vdm; + synchronized (mLock) { + vdm = mVirtualDeviceManagerInternal; } - return mVirtualDeviceManagerInternal != null - && mVirtualDeviceManagerInternal.isAppRunningOnAnyVirtualDevice(uid); + return vdm != null && vdm.isAppRunningOnAnyVirtualDevice(uid); } /** Implementation of {@link ContentObserver} to be registered to a setting {@link Uri}. */ @@ -860,7 +856,7 @@ final class VibrationSettings { /** Implementation of {@link BroadcastReceiver} to update on ringer mode change. */ @VisibleForTesting - final class SettingsBroadcastReceiver extends BroadcastReceiver { + final class RingerModeBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); @@ -871,6 +867,18 @@ final class VibrationSettings { } } + /** Implementation of {@link BroadcastReceiver} to update on battery mode change. */ + @VisibleForTesting + final class BatteryBroadcastReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { + updateBatteryInfo(intent); + } + } + } + /** Implementation of {@link ContentObserver} to be registered to a setting {@link Uri}. */ @VisibleForTesting final class VibrationUidObserver extends UidObserver { @@ -916,4 +924,25 @@ final class VibrationSettings { update(); } } + + /** Implementation of {@link PowerManagerInternal.LowPowerModeListener} for low battery. */ + @VisibleForTesting + final class VibrationLowPowerModeListener implements PowerManagerInternal.LowPowerModeListener { + @Override + public int getServiceType() { + return PowerManager.ServiceType.VIBRATION; + } + + @Override + public void onLowPowerModeChanged(PowerSaveState result) { + boolean shouldNotifyListeners; + synchronized (mLock) { + shouldNotifyListeners = result.batterySaverEnabled != mBatterySaverMode; + mBatterySaverMode = result.batterySaverEnabled; + } + if (shouldNotifyListeners) { + notifyListeners(); + } + } + } } diff --git a/services/core/java/com/android/server/wm/Transition.java b/services/core/java/com/android/server/wm/Transition.java index 84df11a2746b..9ff9e348af77 100644 --- a/services/core/java/com/android/server/wm/Transition.java +++ b/services/core/java/com/android/server/wm/Transition.java @@ -1337,7 +1337,16 @@ class Transition implements BLASTSyncEngine.TransactionReadyListener { // Commit wallpaper visibility after activity, because usually the wallpaper target token is // an activity, and wallpaper's visibility depends on activity's visibility. for (int i = mParticipants.size() - 1; i >= 0; --i) { - final WallpaperWindowToken wt = mParticipants.valueAt(i).asWallpaperToken(); + final WindowContainer<?> wc = mParticipants.valueAt(i); + WallpaperWindowToken wt = wc.asWallpaperToken(); + if (!Flags.ensureWallpaperInTransitions()) { + if (wt == null) { + final WindowState windowState = wc.asWindowState(); + if (windowState != null) { + wt = windowState.mToken.asWallpaperToken(); + } + } + } if (wt == null) continue; final WindowState target = wt.mDisplayContent.mWallpaperController.getWallpaperTarget(); final boolean isTargetInvisible = target == null || !target.mToken.isVisible(); diff --git a/services/tests/PackageManagerServiceTests/server/src/com/android/server/pm/PackageVerificationStateTest.java b/services/tests/PackageManagerServiceTests/server/src/com/android/server/pm/PackageVerificationStateTest.java index a93e8ad93756..97f1bd46678f 100644 --- a/services/tests/PackageManagerServiceTests/server/src/com/android/server/pm/PackageVerificationStateTest.java +++ b/services/tests/PackageManagerServiceTests/server/src/com/android/server/pm/PackageVerificationStateTest.java @@ -574,57 +574,16 @@ public class PackageVerificationStateTest extends AndroidTestCase { assertTrue(state.isInstallAllowed()); } - public void testAreAllVerificationsComplete_onlyVerificationPasses() { + public void testAreAllVerificationsComplete() { PackageVerificationState state = new PackageVerificationState(null); state.addRequiredVerifierUid(REQUIRED_UID_1); assertFalse(state.areAllVerificationsComplete()); state.setVerifierResponse(REQUIRED_UID_1, PackageManager.VERIFICATION_ALLOW); - assertFalse(state.areAllVerificationsComplete()); - } - - public void testAreAllVerificationsComplete_onlyIntegrityCheckPasses() { - PackageVerificationState state = new PackageVerificationState(null); - state.addRequiredVerifierUid(REQUIRED_UID_1); - assertFalse(state.areAllVerificationsComplete()); - - state.setIntegrityVerificationResult(PackageManagerInternal.INTEGRITY_VERIFICATION_ALLOW); - - assertFalse(state.areAllVerificationsComplete()); - } - - public void testAreAllVerificationsComplete_bothPasses() { - PackageVerificationState state = new PackageVerificationState(null); - state.addRequiredVerifierUid(REQUIRED_UID_1); - assertFalse(state.areAllVerificationsComplete()); - - state.setIntegrityVerificationResult(PackageManagerInternal.INTEGRITY_VERIFICATION_ALLOW); - state.setVerifierResponse(REQUIRED_UID_1, PackageManager.VERIFICATION_ALLOW); - assertTrue(state.areAllVerificationsComplete()); } - public void testAreAllVerificationsComplete_onlyVerificationFails() { - PackageVerificationState state = new PackageVerificationState(null); - state.addRequiredVerifierUid(REQUIRED_UID_1); - assertFalse(state.areAllVerificationsComplete()); - - state.setVerifierResponse(REQUIRED_UID_1, PackageManager.VERIFICATION_REJECT); - - assertFalse(state.areAllVerificationsComplete()); - } - - public void testAreAllVerificationsComplete_onlyIntegrityCheckFails() { - PackageVerificationState state = new PackageVerificationState(null); - state.addRequiredVerifierUid(REQUIRED_UID_1); - assertFalse(state.areAllVerificationsComplete()); - - state.setIntegrityVerificationResult(PackageManagerInternal.INTEGRITY_VERIFICATION_REJECT); - - assertFalse(state.areAllVerificationsComplete()); - } - private void processOnTimeout(PackageVerificationState state, int code, int uid) { // CHECK_PENDING_VERIFICATION handler. assertFalse("Verification should not be marked as complete yet", diff --git a/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java b/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java deleted file mode 100644 index fd221185bacf..000000000000 --- a/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (C) 2019 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.integrity; - -import static android.content.integrity.AppIntegrityManager.EXTRA_STATUS; -import static android.content.integrity.AppIntegrityManager.STATUS_FAILURE; -import static android.content.integrity.AppIntegrityManager.STATUS_SUCCESS; -import static android.content.integrity.InstallerAllowedByManifestFormula.INSTALLER_CERTIFICATE_NOT_EVALUATED; -import static android.content.pm.PackageManager.EXTRA_VERIFICATION_ID; -import static android.content.pm.PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE; -import static android.content.pm.PackageManager.EXTRA_VERIFICATION_INSTALLER_UID; - -import static com.google.common.truth.Truth.assertThat; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.IntentSender; -import android.content.integrity.AppInstallMetadata; -import android.content.integrity.AtomicFormula; -import android.content.integrity.IntegrityFormula; -import android.content.integrity.Rule; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManagerInternal; -import android.content.pm.ParceledListSlice; -import android.content.res.Resources; -import android.net.Uri; -import android.os.Handler; -import android.os.Message; -import android.provider.Settings; - -import androidx.test.InstrumentationRegistry; - -import com.android.internal.R; -import com.android.server.compat.PlatformCompat; -import com.android.server.testutils.TestUtils; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; - -/** Unit test for {@link com.android.server.integrity.AppIntegrityManagerServiceImpl} */ -@RunWith(JUnit4.class) -public class AppIntegrityManagerServiceImplTest { - private static final String TEST_APP_PATH = - "AppIntegrityManagerServiceImplTest/AppIntegrityManagerServiceTestApp.apk"; - - private static final String TEST_APP_TWO_CERT_PATH = - "AppIntegrityManagerServiceImplTest/DummyAppTwoCerts.apk"; - - private static final String TEST_APP_SOURCE_STAMP_PATH = - "AppIntegrityManagerServiceImplTest/SourceStampTestApk.apk"; - - private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; - private static final String VERSION = "version"; - private static final String TEST_FRAMEWORK_PACKAGE = "com.android.frameworks.servicestests"; - - private static final String PACKAGE_NAME = "com.test.app"; - - private static final long VERSION_CODE = 100; - private static final String INSTALLER = "com.long.random.test.installer.name"; - - // These are obtained by running the test and checking logcat. - private static final String APP_CERT = - "F14CFECF5070874C05D3D2FA98E046BE20BDE02A0DC74BAF6B59C6A0E4C06850"; - // We use SHA256 for package names longer than 32 characters. - private static final String INSTALLER_SHA256 = - "30F41A7CBF96EE736A54DD6DF759B50ED3CC126ABCEF694E167C324F5976C227"; - private static final String SOURCE_STAMP_CERTIFICATE_HASH = - "C6E737809CEF2B08CC6694892215F82A5E8FBC3C2A0F6212770310B90622D2D9"; - - private static final String DUMMY_APP_TWO_CERTS_CERT_1 = - "C0369C2A1096632429DFA8433068AECEAD00BAC337CA92A175036D39CC9AFE94"; - private static final String DUMMY_APP_TWO_CERTS_CERT_2 = - "94366E0A80F3A3F0D8171A15760B88E228CD6E1101F0414C98878724FBE70147"; - - private static final String PLAY_STORE_PKG = "com.android.vending"; - private static final String ADB_INSTALLER = "adb"; - private static final String PLAY_STORE_CERT = "play_store_cert"; - - @org.junit.Rule public MockitoRule mMockitoRule = MockitoJUnit.rule(); - - @Mock PackageManagerInternal mPackageManagerInternal; - @Mock PlatformCompat mPlatformCompat; - @Mock Context mMockContext; - @Mock Resources mMockResources; - @Mock Handler mHandler; - - private final Context mRealContext = InstrumentationRegistry.getTargetContext(); - - private PackageManager mSpyPackageManager; - private File mTestApk; - private File mTestApkTwoCerts; - private File mTestApkSourceStamp; - - // under test - private AppIntegrityManagerServiceImpl mService; - - @Before - public void setup() throws Exception { - mTestApk = File.createTempFile("AppIntegrity", ".apk"); - try (InputStream inputStream = mRealContext.getAssets().open(TEST_APP_PATH)) { - Files.copy(inputStream, mTestApk.toPath(), REPLACE_EXISTING); - } - - mTestApkTwoCerts = File.createTempFile("AppIntegrityTwoCerts", ".apk"); - try (InputStream inputStream = mRealContext.getAssets().open(TEST_APP_TWO_CERT_PATH)) { - Files.copy(inputStream, mTestApkTwoCerts.toPath(), REPLACE_EXISTING); - } - - mTestApkSourceStamp = File.createTempFile("AppIntegritySourceStamp", ".apk"); - try (InputStream inputStream = mRealContext.getAssets().open(TEST_APP_SOURCE_STAMP_PATH)) { - Files.copy(inputStream, mTestApkSourceStamp.toPath(), REPLACE_EXISTING); - } - - mService = - new AppIntegrityManagerServiceImpl( - mMockContext, - mPackageManagerInternal, - mHandler); - - mSpyPackageManager = spy(mRealContext.getPackageManager()); - // setup mocks to prevent NPE - when(mMockContext.getPackageManager()).thenReturn(mSpyPackageManager); - when(mMockContext.getResources()).thenReturn(mMockResources); - when(mMockResources.getStringArray(anyInt())).thenReturn(new String[] {}); - // These are needed to override the Settings.Global.get result. - when(mMockContext.getContentResolver()).thenReturn(mRealContext.getContentResolver()); - setIntegrityCheckIncludesRuleProvider(true); - } - - @After - public void tearDown() throws Exception { - mTestApk.delete(); - mTestApkTwoCerts.delete(); - mTestApkSourceStamp.delete(); - } - - @Test - public void broadcastReceiverRegistration() throws Exception { - allowlistUsAsRuleProvider(); - makeUsSystemApp(); - ArgumentCaptor<IntentFilter> intentFilterCaptor = - ArgumentCaptor.forClass(IntentFilter.class); - - verify(mMockContext).registerReceiver(any(), intentFilterCaptor.capture(), any(), any()); - assertEquals(1, intentFilterCaptor.getValue().countActions()); - assertEquals( - Intent.ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION, - intentFilterCaptor.getValue().getAction(0)); - assertEquals(1, intentFilterCaptor.getValue().countDataTypes()); - assertEquals(PACKAGE_MIME_TYPE, intentFilterCaptor.getValue().getDataType(0)); - } - - @Test - public void handleBroadcast_allow() throws Exception { - allowlistUsAsRuleProvider(); - makeUsSystemApp(); - ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor = - ArgumentCaptor.forClass(BroadcastReceiver.class); - verify(mMockContext) - .registerReceiver(broadcastReceiverCaptor.capture(), any(), any(), any()); - Intent intent = makeVerificationIntent(); - - broadcastReceiverCaptor.getValue().onReceive(mMockContext, intent); - runJobInHandler(); - - verify(mPackageManagerInternal) - .setIntegrityVerificationResult( - 1, PackageManagerInternal.INTEGRITY_VERIFICATION_ALLOW); - } - - private void allowlistUsAsRuleProvider() { - Resources mockResources = mock(Resources.class); - when(mockResources.getStringArray(R.array.config_integrityRuleProviderPackages)) - .thenReturn(new String[] {TEST_FRAMEWORK_PACKAGE}); - when(mMockContext.getResources()).thenReturn(mockResources); - } - - private void runJobInHandler() { - ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class); - // sendMessageAtTime is the first non-final method in the call chain when "post" is invoked. - verify(mHandler).sendMessageAtTime(messageCaptor.capture(), anyLong()); - messageCaptor.getValue().getCallback().run(); - } - - private void makeUsSystemApp() throws Exception { - makeUsSystemApp(true); - } - - private void makeUsSystemApp(boolean isSystemApp) throws Exception { - PackageInfo packageInfo = - mRealContext.getPackageManager().getPackageInfo(TEST_FRAMEWORK_PACKAGE, 0); - if (isSystemApp) { - packageInfo.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; - } else { - packageInfo.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; - } - doReturn(packageInfo) - .when(mSpyPackageManager) - .getPackageInfo(eq(TEST_FRAMEWORK_PACKAGE), anyInt()); - when(mMockContext.getPackageManager()).thenReturn(mSpyPackageManager); - } - - private Intent makeVerificationIntent() throws Exception { - PackageInfo packageInfo = - mRealContext - .getPackageManager() - .getPackageInfo( - TEST_FRAMEWORK_PACKAGE, PackageManager.GET_SIGNING_CERTIFICATES); - doReturn(packageInfo).when(mSpyPackageManager).getPackageInfo(eq(INSTALLER), anyInt()); - doReturn(1).when(mSpyPackageManager).getPackageUid(eq(INSTALLER), anyInt()); - doReturn(new String[]{INSTALLER}).when(mSpyPackageManager).getPackagesForUid(anyInt()); - return makeVerificationIntent(INSTALLER); - } - - private Intent makeVerificationIntent(String installer) throws Exception { - Intent intent = new Intent(); - intent.setDataAndType(Uri.fromFile(mTestApk), PACKAGE_MIME_TYPE); - intent.setAction(Intent.ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION); - intent.putExtra(EXTRA_VERIFICATION_ID, 1); - intent.putExtra(Intent.EXTRA_PACKAGE_NAME, PACKAGE_NAME); - intent.putExtra(EXTRA_VERIFICATION_INSTALLER_PACKAGE, installer); - intent.putExtra( - EXTRA_VERIFICATION_INSTALLER_UID, - mMockContext.getPackageManager().getPackageUid(installer, /* flags= */ 0)); - intent.putExtra(Intent.EXTRA_LONG_VERSION_CODE, VERSION_CODE); - return intent; - } - - private void setIntegrityCheckIncludesRuleProvider(boolean shouldInclude) throws Exception { - int value = shouldInclude ? 1 : 0; - Settings.Global.putInt( - mRealContext.getContentResolver(), - Settings.Global.INTEGRITY_CHECK_INCLUDES_RULE_PROVIDER, - value); - assertThat( - Settings.Global.getInt( - mRealContext.getContentResolver(), - Settings.Global.INTEGRITY_CHECK_INCLUDES_RULE_PROVIDER, - -1) - == 1) - .isEqualTo(shouldInclude); - } -} diff --git a/services/tests/vibrator/src/com/android/server/vibrator/VibrationSettingsTest.java b/services/tests/vibrator/src/com/android/server/vibrator/VibrationSettingsTest.java index 21604df87fe7..0f2017897719 100644 --- a/services/tests/vibrator/src/com/android/server/vibrator/VibrationSettingsTest.java +++ b/services/tests/vibrator/src/com/android/server/vibrator/VibrationSettingsTest.java @@ -43,7 +43,8 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -51,12 +52,14 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import android.app.ActivityManager; +import android.app.IActivityManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; +import android.content.IntentFilter; import android.content.pm.PackageManagerInternal; import android.media.AudioManager; import android.os.Handler; @@ -80,10 +83,8 @@ import androidx.test.InstrumentationRegistry; import com.android.internal.util.test.FakeSettingsProvider; import com.android.internal.util.test.FakeSettingsProviderRule; -import com.android.server.LocalServices; import com.android.server.companion.virtual.VirtualDeviceManagerInternal; -import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -100,8 +101,7 @@ public class VibrationSettingsTest { @Rule public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule(); - private static final int OLD_USER_ID = 123; - private static final int NEW_USER_ID = 456; + private static final int USER_ID = 123; private static final int UID = 1; private static final int VIRTUAL_DEVICE_ID = 1; private static final String SYSUI_PACKAGE_NAME = "sysui"; @@ -130,13 +130,12 @@ public class VibrationSettingsTest { @Mock private VirtualDeviceManagerInternal mVirtualDeviceManagerInternalMock; @Mock private PackageManagerInternal mPackageManagerInternalMock; @Mock private AudioManager mAudioManagerMock; + @Mock private IActivityManager mActivityManagerMock; @Mock private VibrationConfig mVibrationConfigMock; private TestLooper mTestLooper; private ContextWrapper mContextSpy; private VibrationSettings mVibrationSettings; - private PowerManagerInternal.LowPowerModeListener mRegisteredPowerModeListener; - private BroadcastReceiver mRegisteredBatteryBroadcastReceiver; @Before public void setUp() throws Exception { @@ -144,24 +143,20 @@ public class VibrationSettingsTest { mContextSpy = spy(new ContextWrapper(InstrumentationRegistry.getContext())); ContentResolver contentResolver = mSettingsProviderRule.mockContentResolver(mContextSpy); - when(mContextSpy.getContentResolver()).thenReturn(contentResolver); - when(mContextSpy.getSystemService(eq(Context.AUDIO_SERVICE))).thenReturn(mAudioManagerMock); - doAnswer(invocation -> { - mRegisteredPowerModeListener = invocation.getArgument(0); - return null; - }).when(mPowerManagerInternalMock).registerLowPowerModeObserver(any()); + doReturn(contentResolver).when(mContextSpy).getContentResolver(); + + // Make sure broadcast receivers are not registered for this test, to avoid flakes. + doReturn(null).when(mContextSpy) + .registerReceiver(any(BroadcastReceiver.class), any(IntentFilter.class), anyInt()); when(mPackageManagerInternalMock.getSystemUiServiceComponent()) .thenReturn(new ComponentName(SYSUI_PACKAGE_NAME, "")); - removeServicesForTest(); - addServicesForTest(); - setDefaultIntensity(VIBRATION_INTENSITY_MEDIUM); setIgnoreVibrationsOnWirelessCharger(false); - createSystemReadyVibrationSettings(); mockGoToSleep(/* goToSleepTime= */ 0, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); + createSystemReadyVibrationSettings(); } private void createSystemReadyVibrationSettings() { @@ -175,38 +170,18 @@ public class VibrationSettingsTest { setUserSetting(Settings.System.APPLY_RAMPING_RINGER, 0); setRingerMode(AudioManager.RINGER_MODE_NORMAL); - mVibrationSettings.onSystemReady(); - } - - private void removeServicesForTest() { - LocalServices.removeServiceForTest(PowerManagerInternal.class); - LocalServices.removeServiceForTest(PackageManagerInternal.class); - LocalServices.removeServiceForTest(VirtualDeviceManagerInternal.class); - } - - private void addServicesForTest() { - LocalServices.addService(PowerManagerInternal.class, mPowerManagerInternalMock); - LocalServices.addService(PackageManagerInternal.class, mPackageManagerInternalMock); - LocalServices.addService(VirtualDeviceManagerInternal.class, - mVirtualDeviceManagerInternalMock); - } - - @After - public void tearDown() throws Exception { - removeServicesForTest(); + mVibrationSettings.onSystemReady(mPackageManagerInternalMock, mPowerManagerInternalMock, + mActivityManagerMock, mVirtualDeviceManagerInternalMock, mAudioManagerMock); } @Test public void create_withOnlyRequiredSystemServices() { - // The only core services that we depend on are PowerManager and PackageManager - removeServicesForTest(); - LocalServices.addService(PowerManagerInternal.class, mPowerManagerInternalMock); - LocalServices.addService(PackageManagerInternal.class, mPackageManagerInternalMock); - when(mContextSpy.getSystemService(eq(Context.AUDIO_SERVICE))).thenReturn(null); - VibrationSettings minimalVibrationSettings = new VibrationSettings(mContextSpy, new Handler(mTestLooper.getLooper()), mVibrationConfigMock); - minimalVibrationSettings.onSystemReady(); + + // The only core services that we depend on are Power, Package and Activity managers + minimalVibrationSettings.onSystemReady(mPackageManagerInternalMock, + mPowerManagerInternalMock, mActivityManagerMock, null, null); } @Test @@ -214,8 +189,8 @@ public class VibrationSettingsTest { mVibrationSettings.addListener(mListenerMock); // Testing the broadcast flow manually. - mVibrationSettings.mUserSwitchObserver.onUserSwitching(NEW_USER_ID); - mVibrationSettings.mUserSwitchObserver.onUserSwitchComplete(NEW_USER_ID); + mVibrationSettings.mUserSwitchObserver.onUserSwitching(USER_ID); + mVibrationSettings.mUserSwitchObserver.onUserSwitchComplete(USER_ID); verify(mListenerMock, times(2)).onChange(); } @@ -225,9 +200,9 @@ public class VibrationSettingsTest { mVibrationSettings.addListener(mListenerMock); // Testing the broadcast flow manually. - mVibrationSettings.mSettingChangeReceiver.onReceive(mContextSpy, + mVibrationSettings.mRingerModeBroadcastReceiver.onReceive(mContextSpy, new Intent(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION)); - mVibrationSettings.mSettingChangeReceiver.onReceive(mContextSpy, + mVibrationSettings.mRingerModeBroadcastReceiver.onReceive(mContextSpy, new Intent(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION)); verify(mListenerMock, times(2)).onChange(); @@ -249,9 +224,9 @@ public class VibrationSettingsTest { mVibrationSettings.addListener(mListenerMock); // Testing the broadcast flow manually. - mRegisteredPowerModeListener.onLowPowerModeChanged(LOW_POWER_STATE); - mRegisteredPowerModeListener.onLowPowerModeChanged(NORMAL_POWER_STATE); - mRegisteredPowerModeListener.onLowPowerModeChanged(NORMAL_POWER_STATE); // No change. + mVibrationSettings.mLowPowerModeListener.onLowPowerModeChanged(LOW_POWER_STATE); + mVibrationSettings.mLowPowerModeListener.onLowPowerModeChanged(NORMAL_POWER_STATE); + mVibrationSettings.mLowPowerModeListener.onLowPowerModeChanged(NORMAL_POWER_STATE); // Noop. verify(mListenerMock, times(2)).onChange(); } @@ -266,10 +241,9 @@ public class VibrationSettingsTest { mVibrationSettings.removeListener(mListenerMock); // Trigger multiple observers manually. - mVibrationSettings.mSettingObserver.onChange(false); - mRegisteredPowerModeListener.onLowPowerModeChanged(LOW_POWER_STATE); - mVibrationSettings.mUserSwitchObserver.onUserSwitchComplete(NEW_USER_ID); - mVibrationSettings.mSettingChangeReceiver.onReceive(mContextSpy, + mVibrationSettings.mLowPowerModeListener.onLowPowerModeChanged(LOW_POWER_STATE); + mVibrationSettings.mUserSwitchObserver.onUserSwitchComplete(USER_ID); + mVibrationSettings.mRingerModeBroadcastReceiver.onReceive(mContextSpy, new Intent(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION)); verifyNoMoreInteractions(mListenerMock); @@ -310,11 +284,12 @@ public class VibrationSettingsTest { @Test public void wirelessChargingVibrationsEnabled_doesNotRegisterBatteryReceiver_allowsAnyUsage() { - setBatteryReceiverRegistrationResult(getBatteryChangedIntent(BATTERY_PLUGGED_WIRELESS)); setIgnoreVibrationsOnWirelessCharger(false); createSystemReadyVibrationSettings(); - assertNull(mRegisteredBatteryBroadcastReceiver); + verify(mContextSpy, never()).registerReceiver(any(BroadcastReceiver.class), + argThat(filter -> filter.matchAction(Intent.ACTION_BATTERY_CHANGED)), anyInt()); + for (int usage : ALL_USAGES) { assertVibrationNotIgnoredForUsage(usage); } @@ -322,7 +297,6 @@ public class VibrationSettingsTest { @Test public void shouldIgnoreVibration_noBatteryIntentWhenSystemReady_allowsAnyUsage() { - setBatteryReceiverRegistrationResult(null); setIgnoreVibrationsOnWirelessCharger(true); createSystemReadyVibrationSettings(); @@ -334,7 +308,9 @@ public class VibrationSettingsTest { @Test public void shouldIgnoreVibration_onNonWirelessChargerWhenSystemReady_allowsAnyUsage() { Intent nonWirelessChargingIntent = getBatteryChangedIntent(BATTERY_PLUGGED_USB); - setBatteryReceiverRegistrationResult(nonWirelessChargingIntent); + doReturn(nonWirelessChargingIntent).when(mContextSpy).registerReceiver( + any(BroadcastReceiver.class), + argThat(filter -> filter.matchAction(Intent.ACTION_BATTERY_CHANGED)), anyInt()); setIgnoreVibrationsOnWirelessCharger(true); createSystemReadyVibrationSettings(); @@ -346,7 +322,9 @@ public class VibrationSettingsTest { @Test public void shouldIgnoreVibration_onWirelessChargerWhenSystemReady_doesNotAllowFromAnyUsage() { Intent wirelessChargingIntent = getBatteryChangedIntent(BATTERY_PLUGGED_WIRELESS); - setBatteryReceiverRegistrationResult(wirelessChargingIntent); + doReturn(wirelessChargingIntent).when(mContextSpy).registerReceiver( + any(BroadcastReceiver.class), + argThat(filter -> filter.matchAction(Intent.ACTION_BATTERY_CHANGED)), anyInt()); setIgnoreVibrationsOnWirelessCharger(true); createSystemReadyVibrationSettings(); @@ -357,13 +335,12 @@ public class VibrationSettingsTest { @Test public void shouldIgnoreVibration_receivesWirelessChargingIntent_doesNotAllowFromAnyUsage() { - Intent nonWirelessChargingIntent = getBatteryChangedIntent(BATTERY_PLUGGED_USB); - setBatteryReceiverRegistrationResult(nonWirelessChargingIntent); setIgnoreVibrationsOnWirelessCharger(true); createSystemReadyVibrationSettings(); Intent wirelessChargingIntent = getBatteryChangedIntent(BATTERY_PLUGGED_WIRELESS); - mRegisteredBatteryBroadcastReceiver.onReceive(mContextSpy, wirelessChargingIntent); + mVibrationSettings.mBatteryBroadcastReceiver.onReceive( + mContextSpy, wirelessChargingIntent); for (int usage : ALL_USAGES) { assertVibrationIgnoredForUsage(usage, Vibration.Status.IGNORED_ON_WIRELESS_CHARGER); @@ -372,17 +349,21 @@ public class VibrationSettingsTest { @Test public void shouldIgnoreVibration_receivesNonWirelessChargingIntent_allowsAnyUsage() { - Intent wirelessChargingIntent = getBatteryChangedIntent(BATTERY_PLUGGED_WIRELESS); - setBatteryReceiverRegistrationResult(wirelessChargingIntent); setIgnoreVibrationsOnWirelessCharger(true); createSystemReadyVibrationSettings(); + + Intent wirelessChargingIntent = getBatteryChangedIntent(BATTERY_PLUGGED_WIRELESS); + mVibrationSettings.mBatteryBroadcastReceiver.onReceive( + mContextSpy, wirelessChargingIntent); + // Check that initially, all usages are ignored due to the wireless charging. for (int usage : ALL_USAGES) { assertVibrationIgnoredForUsage(usage, Vibration.Status.IGNORED_ON_WIRELESS_CHARGER); } Intent nonWirelessChargingIntent = getBatteryChangedIntent(BATTERY_PLUGGED_USB); - mRegisteredBatteryBroadcastReceiver.onReceive(mContextSpy, nonWirelessChargingIntent); + mVibrationSettings.mBatteryBroadcastReceiver.onReceive( + mContextSpy, nonWirelessChargingIntent); for (int usage : ALL_USAGES) { assertVibrationNotIgnoredForUsage(usage); @@ -399,7 +380,7 @@ public class VibrationSettingsTest { USAGE_HARDWARE_FEEDBACK )); - mRegisteredPowerModeListener.onLowPowerModeChanged(LOW_POWER_STATE); + mVibrationSettings.mLowPowerModeListener.onLowPowerModeChanged(LOW_POWER_STATE); for (int usage : ALL_USAGES) { if (expectedAllowedVibrations.contains(usage)) { @@ -412,7 +393,7 @@ public class VibrationSettingsTest { @Test public void shouldIgnoreVibration_notInBatterySaverMode_allowsAnyUsage() { - mRegisteredPowerModeListener.onLowPowerModeChanged(NORMAL_POWER_STATE); + mVibrationSettings.mLowPowerModeListener.onLowPowerModeChanged(NORMAL_POWER_STATE); for (int usage : ALL_USAGES) { assertVibrationNotIgnoredForUsage(usage); @@ -605,7 +586,7 @@ public class VibrationSettingsTest { // Testing the broadcast flow manually. when(mAudioManagerMock.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_SILENT); - mVibrationSettings.mSettingChangeReceiver.onReceive(mContextSpy, + mVibrationSettings.mRingerModeBroadcastReceiver.onReceive(mContextSpy, new Intent(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION)); assertVibrationIgnoredForUsage(USAGE_RINGTONE, Vibration.Status.IGNORED_FOR_RINGER_MODE); @@ -868,16 +849,15 @@ public class VibrationSettingsTest { mVibrationSettings.getCurrentIntensity(USAGE_RINGTONE)); // Test early update of settings based on new user id. - putUserSetting(Settings.System.RING_VIBRATION_INTENSITY, VIBRATION_INTENSITY_LOW, - NEW_USER_ID); - mVibrationSettings.mUserSwitchObserver.onUserSwitching(NEW_USER_ID); + putUserSetting(Settings.System.RING_VIBRATION_INTENSITY, VIBRATION_INTENSITY_LOW, USER_ID); + mVibrationSettings.mUserSwitchObserver.onUserSwitching(USER_ID); assertEquals(VIBRATION_INTENSITY_LOW, mVibrationSettings.getCurrentIntensity(USAGE_RINGTONE)); // Test later update of settings for UserHandle.USER_CURRENT. putUserSetting(Settings.System.RING_VIBRATION_INTENSITY, VIBRATION_INTENSITY_LOW, UserHandle.USER_CURRENT); - mVibrationSettings.mUserSwitchObserver.onUserSwitchComplete(NEW_USER_ID); + mVibrationSettings.mUserSwitchObserver.onUserSwitchComplete(USER_ID); assertEquals(VIBRATION_INTENSITY_LOW, mVibrationSettings.getCurrentIntensity(USAGE_RINGTONE)); } @@ -1010,7 +990,7 @@ public class VibrationSettingsTest { private void setRingerMode(int ringerMode) { when(mAudioManagerMock.getRingerModeInternal()).thenReturn(ringerMode); // Mock AudioManager broadcast of internal ringer mode change. - mVibrationSettings.mSettingChangeReceiver.onReceive(mContextSpy, + mVibrationSettings.mRingerModeBroadcastReceiver.onReceive(mContextSpy, new Intent(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION)); } @@ -1025,14 +1005,6 @@ public class VibrationSettingsTest { return new Vibration.CallerInfo(attrs, uid, VIRTUAL_DEVICE_ID, opPkg, null); } - private void setBatteryReceiverRegistrationResult(Intent result) { - doAnswer(invocation -> { - mRegisteredBatteryBroadcastReceiver = invocation.getArgument(0); - return result; - }).when(mContextSpy).registerReceiver(any(BroadcastReceiver.class), - argThat(filter -> filter.matchAction(Intent.ACTION_BATTERY_CHANGED)), anyInt()); - } - private Intent getBatteryChangedIntent(int extraPluggedValue) { Intent batteryIntent = new Intent(Intent.ACTION_BATTERY_CHANGED); batteryIntent.putExtra(EXTRA_PLUGGED, extraPluggedValue); diff --git a/tests/vcn/java/com/android/server/vcn/VcnGatewayConnectionConnectedStateTest.java b/tests/vcn/java/com/android/server/vcn/VcnGatewayConnectionConnectedStateTest.java index 76be232c2fe3..74db6a5211a0 100644 --- a/tests/vcn/java/com/android/server/vcn/VcnGatewayConnectionConnectedStateTest.java +++ b/tests/vcn/java/com/android/server/vcn/VcnGatewayConnectionConnectedStateTest.java @@ -659,7 +659,6 @@ public class VcnGatewayConnectionConnectedStateTest extends VcnGatewayConnection private void verifySetSafeModeAlarm( boolean safeModeEnabledByCaller, - boolean safeModeConfigFlagEnabled, boolean expectingSafeModeEnabled) throws Exception { final VcnGatewayConnectionConfig config = @@ -670,7 +669,6 @@ public class VcnGatewayConnectionConnectedStateTest extends VcnGatewayConnection mock(VcnGatewayConnection.Dependencies.class); setUpWakeupMessage( mSafeModeTimeoutAlarm, VcnGatewayConnection.SAFEMODE_TIMEOUT_ALARM, deps); - doReturn(safeModeConfigFlagEnabled).when(mFeatureFlags).safeModeConfig(); final VcnGatewayConnection connection = new VcnGatewayConnection( @@ -694,37 +692,19 @@ public class VcnGatewayConnectionConnectedStateTest extends VcnGatewayConnection } @Test - public void testSafeModeEnabled_configFlagEnabled() throws Exception { + public void testSafeModeEnabled() throws Exception { verifySetSafeModeAlarm( true /* safeModeEnabledByCaller */, - true /* safeModeConfigFlagEnabled */, true /* expectingSafeModeEnabled */); } @Test - public void testSafeModeEnabled_configFlagDisabled() throws Exception { - verifySetSafeModeAlarm( - true /* safeModeEnabledByCaller */, - false /* safeModeConfigFlagEnabled */, - true /* expectingSafeModeEnabled */); - } - - @Test - public void testSafeModeDisabled_configFlagEnabled() throws Exception { + public void testSafeModeDisabled() throws Exception { verifySetSafeModeAlarm( false /* safeModeEnabledByCaller */, - true /* safeModeConfigFlagEnabled */, false /* expectingSafeModeEnabled */); } - @Test - public void testSafeModeDisabled_configFlagDisabled() throws Exception { - verifySetSafeModeAlarm( - false /* safeModeEnabledByCaller */, - false /* safeModeConfigFlagEnabled */, - true /* expectingSafeModeEnabled */); - } - private Consumer<VcnNetworkAgent> setupNetworkAndGetUnwantedCallback() { triggerChildOpened(); mTestLooper.dispatchAll(); |