Merge "fix RemoteView's content loss in some case" into main
diff --git a/AconfigFlags.bp b/AconfigFlags.bp
index 3191896..e71ded9 100644
--- a/AconfigFlags.bp
+++ b/AconfigFlags.bp
@@ -112,7 +112,7 @@
 
 filegroup {
     name: "framework-minus-apex-aconfig-srcjars",
-    srcs: [
+    device_common_srcs: [
         ":framework-minus-apex-aconfig-declarations{.srcjars}",
     ],
 }
diff --git a/Android.bp b/Android.bp
index b114898..d2e8003 100644
--- a/Android.bp
+++ b/Android.bp
@@ -61,7 +61,7 @@
 
 filegroup {
     name: "framework-non-updatable-sources",
-    srcs: [
+    device_common_srcs: [
         // Java/AIDL sources under frameworks/base
         ":framework-annotations",
         ":framework-blobstore-sources",
diff --git a/apct-tests/perftests/core/apps/reources_manager/Android.bp b/apct-tests/perftests/core/apps/reources_manager/Android.bp
index 96b9d6a..a95e1175 100644
--- a/apct-tests/perftests/core/apps/reources_manager/Android.bp
+++ b/apct-tests/perftests/core/apps/reources_manager/Android.bp
@@ -27,7 +27,7 @@
     static_libs: ["androidx.appcompat_appcompat"],
 }
 
-genrule {
+java_genrule {
     name: "LargeResourcesUncompressed",
     srcs: [":LargeResourcesCompressed"],
     out: ["LargeResourcesUncompressed.apk"],
diff --git a/api/Android.bp b/api/Android.bp
index 3f2316f..3c92cb2 100644
--- a/api/Android.bp
+++ b/api/Android.bp
@@ -124,7 +124,7 @@
     }),
 }
 
-genrule {
+java_genrule {
     name: "frameworks-base-api-current-compat",
     srcs: [
         ":android.api.public.latest",
@@ -140,7 +140,7 @@
         "$(location :frameworks-base-api-current.txt)",
 }
 
-genrule {
+java_genrule {
     name: "frameworks-base-api-system-current-compat",
     srcs: [
         ":android.api.public.latest",
@@ -160,7 +160,7 @@
         "$(location :frameworks-base-api-system-current.txt)",
 }
 
-genrule {
+java_genrule {
     name: "frameworks-base-api-module-lib-current-compat",
     srcs: [
         ":android.api.public.latest",
@@ -184,7 +184,7 @@
         "$(location :frameworks-base-api-module-lib-current.txt)",
 }
 
-genrule {
+java_genrule {
     name: "frameworks-base-api-current.srcjar",
     tools: ["merge_zips"],
     out: ["current.srcjar"],
@@ -209,7 +209,7 @@
         "$(location soong_zip) -o $(out) -C $(genDir)/out -D $(genDir)/out",
 }
 
-genrule {
+java_genrule {
     name: "sdk-annotations.zip",
     defaults: ["sdk-annotations-defaults"],
     srcs: [
@@ -218,7 +218,7 @@
     ],
 }
 
-genrule {
+java_genrule {
     name: "sdk-annotations-system.zip",
     defaults: ["sdk-annotations-defaults"],
     srcs: [
@@ -227,7 +227,7 @@
     ],
 }
 
-genrule {
+java_genrule {
     name: "sdk-annotations-module-lib.zip",
     defaults: ["sdk-annotations-defaults"],
     srcs: [
@@ -236,7 +236,7 @@
     ],
 }
 
-genrule {
+java_genrule {
     name: "sdk-annotations-system-server.zip",
     defaults: ["sdk-annotations-defaults"],
     srcs: [
@@ -245,7 +245,7 @@
     ],
 }
 
-genrule {
+java_genrule {
     name: "combined-removed-dex",
     visibility: [
         "//frameworks/base/boot",
@@ -460,7 +460,7 @@
     tools: ["extract-flagged-apis"],
 }
 
-genrule {
+java_genrule {
     name: "flag-api-mapping-PublicApi",
     defaults: ["flag-api-mapping-generation-defaults"],
     srcs: [":frameworks-base-api-current.txt"],
@@ -470,7 +470,7 @@
     },
 }
 
-genrule {
+java_genrule {
     name: "flag-api-mapping-SystemApi",
     defaults: ["flag-api-mapping-generation-defaults"],
     srcs: [":frameworks-base-api-system-current.txt"],
@@ -480,7 +480,7 @@
     },
 }
 
-genrule {
+java_genrule {
     name: "flag-api-mapping-ModuleLibApi",
     defaults: ["flag-api-mapping-generation-defaults"],
     srcs: [":frameworks-base-api-module-lib-current.txt"],
@@ -490,7 +490,7 @@
     },
 }
 
-genrule {
+java_genrule {
     name: "flag-api-mapping-SystemServerApi",
     defaults: ["flag-api-mapping-generation-defaults"],
     srcs: [":frameworks-base-api-system-server-current.txt"],
diff --git a/api/api.go b/api/api.go
index 1bbf370..29083df 100644
--- a/api/api.go
+++ b/api/api.go
@@ -20,7 +20,6 @@
 	"github.com/google/blueprint/proptools"
 
 	"android/soong/android"
-	"android/soong/genrule"
 	"android/soong/java"
 )
 
@@ -138,9 +137,10 @@
 }
 
 type fgProps struct {
-	Name       *string
-	Srcs       proptools.Configurable[[]string]
-	Visibility []string
+	Name               *string
+	Srcs               proptools.Configurable[[]string]
+	Device_common_srcs proptools.Configurable[[]string]
+	Visibility         []string
 }
 
 type defaultsProps struct {
@@ -201,7 +201,7 @@
 		}
 	}
 	props.Visibility = []string{"//visibility:public"}
-	ctx.CreateModule(genrule.GenRuleFactory, &props)
+	ctx.CreateModule(java.GenRuleFactory, &props)
 }
 
 func createMergedAnnotationsFilegroups(ctx android.LoadHookContext, modules, system_server_modules proptools.Configurable[[]string]) {
@@ -230,7 +230,7 @@
 	} {
 		props := fgProps{}
 		props.Name = proptools.StringPtr(i.name)
-		props.Srcs = createSrcs(i.modules, i.tag)
+		props.Device_common_srcs = createSrcs(i.modules, i.tag)
 		ctx.CreateModule(android.FileGroupFactory, &props)
 	}
 }
@@ -429,7 +429,7 @@
 func createPublicStubsSourceFilegroup(ctx android.LoadHookContext, modules proptools.Configurable[[]string]) {
 	props := fgProps{}
 	props.Name = proptools.StringPtr("all-modules-public-stubs-source")
-	props.Srcs = createSrcs(modules, "{.public.stubs.source}")
+	props.Device_common_srcs = createSrcs(modules, "{.public.stubs.source}")
 	props.Visibility = []string{"//frameworks/base"}
 	ctx.CreateModule(android.FileGroupFactory, &props)
 }
diff --git a/api/api_test.go b/api/api_test.go
index fb26f82..166f053 100644
--- a/api/api_test.go
+++ b/api/api_test.go
@@ -253,7 +253,7 @@
 	`)
 
 	subModuleDependsOnSelectAppendedModule := java.CheckModuleHasDependency(t,
-		result.TestContext, "foo-current.txt", "", "framework-foo")
+		result.TestContext, "foo-current.txt", "android_common", "framework-foo")
 	android.AssertBoolEquals(t, "Submodule expected to depend on the select-appended module",
 		true, subModuleDependsOnSelectAppendedModule)
 }
diff --git a/boot/Android.bp b/boot/Android.bp
index f60bb9e..6eead42 100644
--- a/boot/Android.bp
+++ b/boot/Android.bp
@@ -234,7 +234,7 @@
     ],
 }
 
-genrule { // This module exists to make the srcjar output available to Make.
+java_genrule { // This module exists to make the srcjar output available to Make.
     name: "platform-bootclasspath.srcjar",
     srcs: [":platform-bootclasspath{.srcjar}"],
     out: ["platform-bootclasspath.srcjar"],
diff --git a/core/api/Android.bp b/core/api/Android.bp
index 77594b7..06eea52 100644
--- a/core/api/Android.bp
+++ b/core/api/Android.bp
@@ -100,50 +100,50 @@
 // Exportable stub artifacts
 filegroup {
     name: "non-updatable-exportable-current.txt",
-    srcs: [":api-stubs-docs-non-updatable{.exportable.api.txt}"],
+    device_common_srcs: [":api-stubs-docs-non-updatable{.exportable.api.txt}"],
 }
 
 filegroup {
     name: "non-updatable-exportable-removed.txt",
-    srcs: [":api-stubs-docs-non-updatable{.exportable.removed-api.txt}"],
+    device_common_srcs: [":api-stubs-docs-non-updatable{.exportable.removed-api.txt}"],
 }
 
 filegroup {
     name: "non-updatable-exportable-system-current.txt",
-    srcs: [":system-api-stubs-docs-non-updatable{.exportable.api.txt}"],
+    device_common_srcs: [":system-api-stubs-docs-non-updatable{.exportable.api.txt}"],
 }
 
 filegroup {
     name: "non-updatable-exportable-system-removed.txt",
-    srcs: [":system-api-stubs-docs-non-updatable{.exportable.removed-api.txt}"],
+    device_common_srcs: [":system-api-stubs-docs-non-updatable{.exportable.removed-api.txt}"],
 }
 
 filegroup {
     name: "non-updatable-exportable-module-lib-current.txt",
-    srcs: [":module-lib-api-stubs-docs-non-updatable{.exportable.api.txt}"],
+    device_common_srcs: [":module-lib-api-stubs-docs-non-updatable{.exportable.api.txt}"],
 }
 
 filegroup {
     name: "non-updatable-exportable-module-lib-removed.txt",
-    srcs: [":module-lib-api-stubs-docs-non-updatable{.exportable.removed-api.txt}"],
+    device_common_srcs: [":module-lib-api-stubs-docs-non-updatable{.exportable.removed-api.txt}"],
 }
 
 filegroup {
     name: "non-updatable-exportable-test-current.txt",
-    srcs: [":test-api-stubs-docs-non-updatable{.exportable.api.txt}"],
+    device_common_srcs: [":test-api-stubs-docs-non-updatable{.exportable.api.txt}"],
 }
 
 filegroup {
     name: "non-updatable-exportable-test-removed.txt",
-    srcs: [":test-api-stubs-docs-non-updatable{.exportable.removed-api.txt}"],
+    device_common_srcs: [":test-api-stubs-docs-non-updatable{.exportable.removed-api.txt}"],
 }
 
 filegroup {
     name: "non-updatable-exportable-system-server-current.txt",
-    srcs: [":services-non-updatable-stubs{.exportable.api.txt}"],
+    device_common_srcs: [":services-non-updatable-stubs{.exportable.api.txt}"],
 }
 
 filegroup {
     name: "non-updatable-exportable-system-server-removed.txt",
-    srcs: [":services-non-updatable-stubs{.exportable.removed-api.txt}"],
+    device_common_srcs: [":services-non-updatable-stubs{.exportable.removed-api.txt}"],
 }
diff --git a/core/java/android/service/settings/OWNERS b/core/java/android/service/settings/OWNERS
new file mode 100644
index 0000000..c70c738
--- /dev/null
+++ b/core/java/android/service/settings/OWNERS
@@ -0,0 +1,7 @@
+# Bug component: 27091
+
+cantol@google.com
+cechkahn@google.com
+cipson@google.com
+dswliu@google.com
+jiannan@google.com
diff --git a/core/tests/FileSystemUtilsTest/Android.bp b/core/tests/FileSystemUtilsTest/Android.bp
index 53c22df..ae04aa4 100644
--- a/core/tests/FileSystemUtilsTest/Android.bp
+++ b/core/tests/FileSystemUtilsTest/Android.bp
@@ -69,7 +69,7 @@
         "compatibility-host-util",
         "compatibility-tradefed",
     ],
-    data: [
+    device_common_data: [
         ":embedded_native_libs_test_app",
         ":extract_native_libs_test_app",
     ],
diff --git a/core/tests/coretests/src/android/service/settings/OWNERS b/core/tests/coretests/src/android/service/settings/OWNERS
new file mode 100644
index 0000000..abd8ab0
--- /dev/null
+++ b/core/tests/coretests/src/android/service/settings/OWNERS
@@ -0,0 +1 @@
+include platform/frameworks/base:/core/java/android/service/settings/OWNERS
diff --git a/core/tests/overlaytests/remount/Android.bp b/core/tests/overlaytests/remount/Android.bp
index 0a6b88b..31c1514 100644
--- a/core/tests/overlaytests/remount/Android.bp
+++ b/core/tests/overlaytests/remount/Android.bp
@@ -32,7 +32,7 @@
         "frameworks-base-hostutils",
     ],
     test_suites: ["general-tests"],
-    java_resources: [
+    device_common_java_resources: [
         ":com.android.overlaytest.overlaid",
         ":com.android.overlaytest.overlay",
         ":OverlayRemountedTest_SharedLibrary",
diff --git a/libs/WindowManager/Shell/Android.bp b/libs/WindowManager/Shell/Android.bp
index 25d3067..4b0c700 100644
--- a/libs/WindowManager/Shell/Android.bp
+++ b/libs/WindowManager/Shell/Android.bp
@@ -79,7 +79,7 @@
     path: "src",
 }
 
-genrule {
+java_genrule {
     name: "wm_shell_protolog_src",
     srcs: [
         ":protolog-impl",
@@ -99,7 +99,7 @@
     out: ["wm_shell_protolog.srcjar"],
 }
 
-genrule {
+java_genrule {
     name: "generate-wm_shell_protolog.json",
     srcs: [
         ":wm_shell_protolog-groups",
@@ -116,7 +116,7 @@
     out: ["wm_shell_protolog.json"],
 }
 
-genrule {
+java_genrule {
     name: "gen-wmshell.protolog.pb",
     srcs: [
         ":wm_shell_protolog-groups",
@@ -133,7 +133,7 @@
     out: ["wmshell.protolog.pb"],
 }
 
-genrule {
+java_genrule {
     name: "protolog.json.gz",
     srcs: [":generate-wm_shell_protolog.json"],
     out: ["wmshell.protolog.json.gz"],
diff --git a/libs/androidfw/Android.bp b/libs/androidfw/Android.bp
index 77800a3..15ef58e 100644
--- a/libs/androidfw/Android.bp
+++ b/libs/androidfw/Android.bp
@@ -258,6 +258,8 @@
         "tests/data/**/*.apk",
         "tests/data/**/*.arsc",
         "tests/data/**/*.idmap",
+    ],
+    device_common_data: [
         ":FrameworkResourcesSparseTestApp",
         ":FrameworkResourcesNotSparseTestApp",
     ],
diff --git a/media/java/android/media/AudioHalVersionInfo.java b/media/java/android/media/AudioHalVersionInfo.java
index 2b6f72e..3e456a6 100644
--- a/media/java/android/media/AudioHalVersionInfo.java
+++ b/media/java/android/media/AudioHalVersionInfo.java
@@ -84,7 +84,7 @@
      * there is a change to supported versions.
      */
     public static final @NonNull List<AudioHalVersionInfo> VERSIONS =
-            List.of(AIDL_1_0, HIDL_7_1, HIDL_7_0, HIDL_6_0, HIDL_5_0);
+            List.of(AIDL_1_0, HIDL_7_1, HIDL_7_0, HIDL_6_0);
 
     private static final String TAG = "AudioHalVersionInfo";
     private AudioHalVersion mHalVersion = new AudioHalVersion();
diff --git a/mime/Android.bp b/mime/Android.bp
index 757862b..20110f1 100644
--- a/mime/Android.bp
+++ b/mime/Android.bp
@@ -92,7 +92,7 @@
     visibility: [
         "//visibility:private",
     ],
-    srcs: [
+    device_common_srcs: [
         ":debian.mime.types.minimized",
         ":android.mime.types.minimized",
         ":vendor.mime.types.minimized",
diff --git a/nfc/java/android/nfc/NfcOemExtension.java b/nfc/java/android/nfc/NfcOemExtension.java
index 905d6f6..520ba89 100644
--- a/nfc/java/android/nfc/NfcOemExtension.java
+++ b/nfc/java/android/nfc/NfcOemExtension.java
@@ -923,12 +923,15 @@
     }
 
     private @CardEmulation.ProtocolAndTechnologyRoute int routeStringToInt(String route) {
-        return switch (route) {
-            case "DH" -> PROTOCOL_AND_TECHNOLOGY_ROUTE_DH;
-            case "eSE" -> PROTOCOL_AND_TECHNOLOGY_ROUTE_ESE;
-            case "SIM" -> PROTOCOL_AND_TECHNOLOGY_ROUTE_UICC;
-            default -> throw new IllegalStateException("Unexpected value: " + route);
-        };
+        if (route.equals("DH")) {
+            return PROTOCOL_AND_TECHNOLOGY_ROUTE_DH;
+        } else if (route.startsWith("eSE")) {
+            return PROTOCOL_AND_TECHNOLOGY_ROUTE_ESE;
+        } else if (route.startsWith("SIM")) {
+            return PROTOCOL_AND_TECHNOLOGY_ROUTE_UICC;
+        } else {
+            throw new IllegalStateException("Unexpected value: " + route);
+        }
     }
 
     private class ReceiverWrapper<T> implements Consumer<T> {
diff --git a/packages/CtsShim/build/Android.bp b/packages/CtsShim/build/Android.bp
index 5b3d47e..bd89263 100644
--- a/packages/CtsShim/build/Android.bp
+++ b/packages/CtsShim/build/Android.bp
@@ -55,7 +55,7 @@
     ],
 }
 
-genrule {
+java_genrule {
     name: "generate_priv_manifest",
     srcs: [
         "shim_priv/AndroidManifest.xml",
@@ -169,7 +169,7 @@
     min_sdk_version: "24",
 }
 
-genrule {
+java_genrule {
     name: "generate_shim_manifest",
     srcs: [
         "shim/AndroidManifest.xml",
diff --git a/packages/SystemUI/checks/Android.bp b/packages/SystemUI/checks/Android.bp
index 04ac748..1ec2201 100644
--- a/packages/SystemUI/checks/Android.bp
+++ b/packages/SystemUI/checks/Android.bp
@@ -40,9 +40,11 @@
     data: [
         ":androidx.annotation_annotation",
         ":dagger2",
-        ":framework",
         ":kotlinx-coroutines-core",
     ],
+    device_common_data: [
+        ":framework",
+    ],
     static_libs: [
         "SystemUILintChecker",
     ],
diff --git a/ravenwood/Android.bp b/ravenwood/Android.bp
index ff2abd2..9a5e623b 100644
--- a/ravenwood/Android.bp
+++ b/ravenwood/Android.bp
@@ -310,7 +310,7 @@
     name: "ravenwood-stats-checker",
     src: "scripts/ravenwood-stats-checker.sh",
     test_suites: ["general-tests"],
-    data: [
+    device_common_data: [
         ":framework-minus-apex.ravenwood-base_all{hoststubgen_framework-minus-apex_stats.csv}",
         ":framework-minus-apex.ravenwood-base_all{hoststubgen_framework-minus-apex_apis.csv}",
         ":framework-minus-apex.ravenwood-base_all{hoststubgen_framework-minus-apex_keep_all.txt}",
@@ -319,6 +319,16 @@
         ":services.core.ravenwood-base{hoststubgen_services.core_apis.csv}",
         ":services.core.ravenwood-base{hoststubgen_services.core_keep_all.txt}",
         ":services.core.ravenwood-base{hoststubgen_services.core_dump.txt}",
+
+        ":framework-configinfrastructure.ravenwood-base{framework-configinfrastructure_stats.csv}",
+        ":framework-configinfrastructure.ravenwood-base{framework-configinfrastructure_apis.csv}",
+        ":framework-configinfrastructure.ravenwood-base{framework-configinfrastructure_keep_all.txt}",
+        ":framework-configinfrastructure.ravenwood-base{framework-configinfrastructure_dump.txt}",
+
+        ":framework-statsd.ravenwood-base{framework-statsd_stats.csv}",
+        ":framework-statsd.ravenwood-base{framework-statsd_apis.csv}",
+        ":framework-statsd.ravenwood-base{framework-statsd_keep_all.txt}",
+        ":framework-statsd.ravenwood-base{framework-statsd_dump.txt}",
     ],
 }
 
@@ -403,6 +413,9 @@
         // DeviceConfig
         "framework-configinfrastructure.ravenwood",
 
+        // StatsD
+        "framework-statsd.ravenwood",
+
         // Provide runtime versions of utils linked in below
         "junit",
         "truth",
diff --git a/ravenwood/Framework.bp b/ravenwood/Framework.bp
index 1bea434..d207738 100644
--- a/ravenwood/Framework.bp
+++ b/ravenwood/Framework.bp
@@ -344,3 +344,57 @@
         "framework-configinfrastructure.ravenwood.jar",
     ],
 }
+
+///////////////////////////////////
+// framework-statsd
+///////////////////////////////////
+
+java_genrule {
+    name: "framework-statsd.ravenwood-base",
+    tools: ["hoststubgen"],
+    cmd: "$(location hoststubgen) " +
+        "@$(location :ravenwood-standard-options) " +
+
+        "--debug-log $(location framework-statsd.log) " +
+        "--stats-file $(location framework-statsd_stats.csv) " +
+        "--supported-api-list-file $(location framework-statsd_apis.csv) " +
+        "--gen-keep-all-file $(location framework-statsd_keep_all.txt) " +
+        "--gen-input-dump-file $(location framework-statsd_dump.txt) " +
+
+        "--out-impl-jar $(location ravenwood.jar) " +
+        "--in-jar $(location :framework-statsd.impl{.jar}) " +
+
+        "--policy-override-file $(location :ravenwood-common-policies) " +
+        "--policy-override-file $(location :framework-statsd-ravenwood-policies) ",
+    srcs: [
+        ":framework-statsd.impl{.jar}",
+
+        ":ravenwood-common-policies",
+        ":framework-statsd-ravenwood-policies",
+        ":ravenwood-standard-options",
+    ],
+    out: [
+        "ravenwood.jar",
+
+        // Following files are created just as FYI.
+        "framework-statsd_keep_all.txt",
+        "framework-statsd_dump.txt",
+
+        "framework-statsd.log",
+        "framework-statsd_stats.csv",
+        "framework-statsd_apis.csv",
+    ],
+    visibility: ["//visibility:private"],
+}
+
+java_genrule {
+    name: "framework-statsd.ravenwood",
+    defaults: ["ravenwood-internal-only-visibility-genrule"],
+    cmd: "cp $(in) $(out)",
+    srcs: [
+        ":framework-statsd.ravenwood-base{ravenwood.jar}",
+    ],
+    out: [
+        "framework-statsd.ravenwood.jar",
+    ],
+}
diff --git a/ravenwood/runtime-helper-src/framework/android/util/StatsEvent.java b/ravenwood/runtime-helper-src/framework/android/util/StatsEvent.java
deleted file mode 100644
index 1e3b3fc..0000000
--- a/ravenwood/runtime-helper-src/framework/android/util/StatsEvent.java
+++ /dev/null
@@ -1,1035 +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 android.util;
-
-// [ravenwood] This is an exact copy from StatsD, until we make StatsD available on Ravenwood.
-
-import static java.nio.charset.StandardCharsets.UTF_8;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.os.Build;
-import android.os.SystemClock;
-
-import androidx.annotation.RequiresApi;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-
-/**
- * StatsEvent builds and stores the buffer sent over the statsd socket.
- * This class defines and encapsulates the socket protocol.
- *
- * <p>Usage:</p>
- * <pre>
- *      // Pushed event
- *      StatsEvent statsEvent = StatsEvent.newBuilder()
- *          .setAtomId(atomId)
- *          .writeBoolean(false)
- *          .writeString("annotated String field")
- *          .addBooleanAnnotation(annotationId, true)
- *          .usePooledBuffer()
- *          .build();
- *      StatsLog.write(statsEvent);
- *
- *      // Pulled event
- *      StatsEvent statsEvent = StatsEvent.newBuilder()
- *          .setAtomId(atomId)
- *          .writeBoolean(false)
- *          .writeString("annotated String field")
- *          .addBooleanAnnotation(annotationId, true)
- *          .build();
- * </pre>
- * @hide
- **/
-@SystemApi
-public final class StatsEvent {
-    // Type Ids.
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final byte TYPE_INT = 0x00;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final byte TYPE_LONG = 0x01;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final byte TYPE_STRING = 0x02;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final byte TYPE_LIST = 0x03;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final byte TYPE_FLOAT = 0x04;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final byte TYPE_BOOLEAN = 0x05;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final byte TYPE_BYTE_ARRAY = 0x06;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final byte TYPE_OBJECT = 0x07;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final byte TYPE_KEY_VALUE_PAIRS = 0x08;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final byte TYPE_ATTRIBUTION_CHAIN = 0x09;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final byte TYPE_ERRORS = 0x0F;
-
-    // Error flags.
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int ERROR_NO_TIMESTAMP = 0x1;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int ERROR_NO_ATOM_ID = 0x2;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int ERROR_OVERFLOW = 0x4;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int ERROR_ATTRIBUTION_CHAIN_TOO_LONG = 0x8;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int ERROR_TOO_MANY_KEY_VALUE_PAIRS = 0x10;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int ERROR_ANNOTATION_DOES_NOT_FOLLOW_FIELD = 0x20;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int ERROR_INVALID_ANNOTATION_ID = 0x40;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int ERROR_ANNOTATION_ID_TOO_LARGE = 0x80;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int ERROR_TOO_MANY_ANNOTATIONS = 0x100;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int ERROR_TOO_MANY_FIELDS = 0x200;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int ERROR_ATTRIBUTION_UIDS_TAGS_SIZES_NOT_EQUAL = 0x1000;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int ERROR_ATOM_ID_INVALID_POSITION = 0x2000;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting public static final int ERROR_LIST_TOO_LONG = 0x4000;
-
-    // Size limits.
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int MAX_ANNOTATION_COUNT = 15;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int MAX_ATTRIBUTION_NODES = 127;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int MAX_NUM_ELEMENTS = 127;
-
-    /**
-     * @hide
-     **/
-    @VisibleForTesting
-    public static final int MAX_KEY_VALUE_PAIRS = 127;
-
-    private static final int LOGGER_ENTRY_MAX_PAYLOAD = 4068;
-
-    // Max payload size is 4 bytes less as 4 bytes are reserved for statsEventTag.
-    // See android_util_StatsLog.cpp.
-    private static final int MAX_PUSH_PAYLOAD_SIZE = LOGGER_ENTRY_MAX_PAYLOAD - 4;
-
-    private static final int MAX_PULL_PAYLOAD_SIZE = 50 * 1024; // 50 KB
-
-    private final int mAtomId;
-    private final byte[] mPayload;
-    private Buffer mBuffer;
-    private final int mNumBytes;
-
-    private StatsEvent(final int atomId, @Nullable final Buffer buffer,
-            @NonNull final byte[] payload, final int numBytes) {
-        mAtomId = atomId;
-        mBuffer = buffer;
-        mPayload = payload;
-        mNumBytes = numBytes;
-    }
-
-    /**
-     * Returns a new StatsEvent.Builder for building StatsEvent object.
-     **/
-    @NonNull
-    public static Builder newBuilder() {
-        return new Builder(Buffer.obtain());
-    }
-
-    /**
-     * Get the atom Id of the atom encoded in this StatsEvent object.
-     *
-     * @hide
-     **/
-    public int getAtomId() {
-        return mAtomId;
-    }
-
-    /**
-     * Get the byte array that contains the encoded payload that can be sent to statsd.
-     *
-     * @hide
-     **/
-    @NonNull
-    public byte[] getBytes() {
-        return mPayload;
-    }
-
-    /**
-     * Get the number of bytes used to encode the StatsEvent payload.
-     *
-     * @hide
-     **/
-    public int getNumBytes() {
-        return mNumBytes;
-    }
-
-    /**
-     * Recycle resources used by this StatsEvent object.
-     * No actions should be taken on this StatsEvent after release() is called.
-     *
-     * @hide
-     **/
-    public void release() {
-        if (mBuffer != null) {
-            mBuffer.release();
-            mBuffer = null;
-        }
-    }
-
-    /**
-     * Builder for constructing a StatsEvent object.
-     *
-     * <p>This class defines and encapsulates the socket encoding for the
-     *buffer. The write methods must be called in the same order as the order of
-     *fields in the atom definition.</p>
-     *
-     * <p>setAtomId() must be called immediately after
-     *StatsEvent.newBuilder().</p>
-     *
-     * <p>Example:</p>
-     * <pre>
-     *     // Atom definition.
-     *     message MyAtom {
-     *         optional int32 field1 = 1;
-     *         optional int64 field2 = 2;
-     *         optional string field3 = 3 [(annotation1) = true];
-     *         optional repeated int32 field4 = 4;
-     *     }
-     *
-     *     // StatsEvent construction for pushed event.
-     *     StatsEvent.newBuilder()
-     *     StatsEvent statsEvent = StatsEvent.newBuilder()
-     *         .setAtomId(atomId)
-     *         .writeInt(3) // field1
-     *         .writeLong(8L) // field2
-     *         .writeString("foo") // field 3
-     *         .addBooleanAnnotation(annotation1Id, true)
-     *         .writeIntArray({ 1, 2, 3 });
-     *         .usePooledBuffer()
-     *         .build();
-     *
-     *     // StatsEvent construction for pulled event.
-     *     StatsEvent.newBuilder()
-     *     StatsEvent statsEvent = StatsEvent.newBuilder()
-     *         .setAtomId(atomId)
-     *         .writeInt(3) // field1
-     *         .writeLong(8L) // field2
-     *         .writeString("foo") // field 3
-     *         .addBooleanAnnotation(annotation1Id, true)
-     *         .writeIntArray({ 1, 2, 3 });
-     *         .build();
-     * </pre>
-     **/
-    public static final class Builder {
-        // Fixed positions.
-        private static final int POS_NUM_ELEMENTS = 1;
-        private static final int POS_TIMESTAMP_NS = POS_NUM_ELEMENTS + Byte.BYTES;
-        private static final int POS_ATOM_ID = POS_TIMESTAMP_NS + Byte.BYTES + Long.BYTES;
-
-        private final Buffer mBuffer;
-        private long mTimestampNs;
-        private int mAtomId;
-        private byte mCurrentAnnotationCount;
-        private int mPos;
-        private int mPosLastField;
-        private byte mLastType;
-        private int mNumElements;
-        private int mErrorMask;
-        private boolean mUsePooledBuffer = false;
-
-        private Builder(final Buffer buffer) {
-            mBuffer = buffer;
-            mCurrentAnnotationCount = 0;
-            mAtomId = 0;
-            mTimestampNs = SystemClock.elapsedRealtimeNanos();
-            mNumElements = 0;
-
-            // Set mPos to 0 for writing TYPE_OBJECT at 0th position.
-            mPos = 0;
-            writeTypeId(TYPE_OBJECT);
-
-            // Write timestamp.
-            mPos = POS_TIMESTAMP_NS;
-            writeLong(mTimestampNs);
-        }
-
-        /**
-         * Sets the atom id for this StatsEvent.
-         *
-         * This should be called immediately after StatsEvent.newBuilder()
-         * and should only be called once.
-         * Not calling setAtomId will result in ERROR_NO_ATOM_ID.
-         * Calling setAtomId out of order will result in ERROR_ATOM_ID_INVALID_POSITION.
-         **/
-        @NonNull
-        public Builder setAtomId(final int atomId) {
-            if (0 == mAtomId) {
-                mAtomId = atomId;
-
-                if (1 == mNumElements) { // Only timestamp is written so far.
-                    writeInt(atomId);
-                } else {
-                    // setAtomId called out of order.
-                    mErrorMask |= ERROR_ATOM_ID_INVALID_POSITION;
-                }
-            }
-
-            return this;
-        }
-
-        /**
-         * Write a boolean field to this StatsEvent.
-         **/
-        @NonNull
-        public Builder writeBoolean(final boolean value) {
-            // Write boolean typeId byte followed by boolean byte representation.
-            writeTypeId(TYPE_BOOLEAN);
-            mPos += mBuffer.putBoolean(mPos, value);
-            mNumElements++;
-            return this;
-        }
-
-        /**
-         * Write an integer field to this StatsEvent.
-         **/
-        @NonNull
-        public Builder writeInt(final int value) {
-            // Write integer typeId byte followed by 4-byte representation of value.
-            writeTypeId(TYPE_INT);
-            mPos += mBuffer.putInt(mPos, value);
-            mNumElements++;
-            return this;
-        }
-
-        /**
-         * Write a long field to this StatsEvent.
-         **/
-        @NonNull
-        public Builder writeLong(final long value) {
-            // Write long typeId byte followed by 8-byte representation of value.
-            writeTypeId(TYPE_LONG);
-            mPos += mBuffer.putLong(mPos, value);
-            mNumElements++;
-            return this;
-        }
-
-        /**
-         * Write a float field to this StatsEvent.
-         **/
-        @NonNull
-        public Builder writeFloat(final float value) {
-            // Write float typeId byte followed by 4-byte representation of value.
-            writeTypeId(TYPE_FLOAT);
-            mPos += mBuffer.putFloat(mPos, value);
-            mNumElements++;
-            return this;
-        }
-
-        /**
-         * Write a String field to this StatsEvent.
-         **/
-        @NonNull
-        public Builder writeString(@NonNull final String value) {
-            // Write String typeId byte, followed by 4-byte representation of number of bytes
-            // in the UTF-8 encoding, followed by the actual UTF-8 byte encoding of value.
-            final byte[] valueBytes = stringToBytes(value);
-            writeByteArray(valueBytes, TYPE_STRING);
-            return this;
-        }
-
-        /**
-         * Write a byte array field to this StatsEvent.
-         **/
-        @NonNull
-        public Builder writeByteArray(@NonNull final byte[] value) {
-            // Write byte array typeId byte, followed by 4-byte representation of number of bytes
-            // in value, followed by the actual byte array.
-            writeByteArray(value, TYPE_BYTE_ARRAY);
-            return this;
-        }
-
-        private void writeByteArray(@NonNull final byte[] value, final byte typeId) {
-            writeTypeId(typeId);
-            final int numBytes = value.length;
-            mPos += mBuffer.putInt(mPos, numBytes);
-            mPos += mBuffer.putByteArray(mPos, value);
-            mNumElements++;
-        }
-
-        /**
-         * Write an attribution chain field to this StatsEvent.
-         *
-         * The sizes of uids and tags must be equal. The AttributionNode at position i is
-         * made up of uids[i] and tags[i].
-         *
-         * @param uids array of uids in the attribution nodes.
-         * @param tags array of tags in the attribution nodes.
-         **/
-        @NonNull
-        public Builder writeAttributionChain(
-                @NonNull final int[] uids, @NonNull final String[] tags) {
-            final byte numUids = (byte) uids.length;
-            final byte numTags = (byte) tags.length;
-
-            if (numUids != numTags) {
-                mErrorMask |= ERROR_ATTRIBUTION_UIDS_TAGS_SIZES_NOT_EQUAL;
-            } else if (numUids > MAX_ATTRIBUTION_NODES) {
-                mErrorMask |= ERROR_ATTRIBUTION_CHAIN_TOO_LONG;
-            } else {
-                // Write attribution chain typeId byte, followed by 1-byte representation of
-                // number of attribution nodes, followed by encoding of each attribution node.
-                writeTypeId(TYPE_ATTRIBUTION_CHAIN);
-                mPos += mBuffer.putByte(mPos, numUids);
-                for (int i = 0; i < numUids; i++) {
-                    // Each uid is encoded as 4-byte representation of its int value.
-                    mPos += mBuffer.putInt(mPos, uids[i]);
-
-                    // Each tag is encoded as 4-byte representation of number of bytes in its
-                    // UTF-8 encoding, followed by the actual UTF-8 bytes.
-                    final byte[] tagBytes = stringToBytes(tags[i]);
-                    mPos += mBuffer.putInt(mPos, tagBytes.length);
-                    mPos += mBuffer.putByteArray(mPos, tagBytes);
-                }
-                mNumElements++;
-            }
-            return this;
-        }
-
-        /**
-         * Write KeyValuePairsAtom entries to this StatsEvent.
-         *
-         * @param intMap Integer key-value pairs.
-         * @param longMap Long key-value pairs.
-         * @param stringMap String key-value pairs.
-         * @param floatMap Float key-value pairs.
-         **/
-        @NonNull
-        public Builder writeKeyValuePairs(
-                @Nullable final SparseIntArray intMap,
-                @Nullable final SparseLongArray longMap,
-                @Nullable final SparseArray<String> stringMap,
-                @Nullable final SparseArray<Float> floatMap) {
-            final int intMapSize = null == intMap ? 0 : intMap.size();
-            final int longMapSize = null == longMap ? 0 : longMap.size();
-            final int stringMapSize = null == stringMap ? 0 : stringMap.size();
-            final int floatMapSize = null == floatMap ? 0 : floatMap.size();
-            final int totalCount = intMapSize + longMapSize + stringMapSize + floatMapSize;
-
-            if (totalCount > MAX_KEY_VALUE_PAIRS) {
-                mErrorMask |= ERROR_TOO_MANY_KEY_VALUE_PAIRS;
-            } else {
-                writeTypeId(TYPE_KEY_VALUE_PAIRS);
-                mPos += mBuffer.putByte(mPos, (byte) totalCount);
-
-                for (int i = 0; i < intMapSize; i++) {
-                    final int key = intMap.keyAt(i);
-                    final int value = intMap.valueAt(i);
-                    mPos += mBuffer.putInt(mPos, key);
-                    writeTypeId(TYPE_INT);
-                    mPos += mBuffer.putInt(mPos, value);
-                }
-
-                for (int i = 0; i < longMapSize; i++) {
-                    final int key = longMap.keyAt(i);
-                    final long value = longMap.valueAt(i);
-                    mPos += mBuffer.putInt(mPos, key);
-                    writeTypeId(TYPE_LONG);
-                    mPos += mBuffer.putLong(mPos, value);
-                }
-
-                for (int i = 0; i < stringMapSize; i++) {
-                    final int key = stringMap.keyAt(i);
-                    final String value = stringMap.valueAt(i);
-                    mPos += mBuffer.putInt(mPos, key);
-                    writeTypeId(TYPE_STRING);
-                    final byte[] valueBytes = stringToBytes(value);
-                    mPos += mBuffer.putInt(mPos, valueBytes.length);
-                    mPos += mBuffer.putByteArray(mPos, valueBytes);
-                }
-
-                for (int i = 0; i < floatMapSize; i++) {
-                    final int key = floatMap.keyAt(i);
-                    final float value = floatMap.valueAt(i);
-                    mPos += mBuffer.putInt(mPos, key);
-                    writeTypeId(TYPE_FLOAT);
-                    mPos += mBuffer.putFloat(mPos, value);
-                }
-
-                mNumElements++;
-            }
-
-            return this;
-        }
-
-        /**
-         * Write a repeated boolean field to this StatsEvent.
-         *
-         * The list size must not exceed 127. Otherwise, the array isn't written
-         * to the StatsEvent and ERROR_LIST_TOO_LONG is appended to the
-         * StatsEvent errors field.
-         *
-         * @param elements array of booleans.
-         **/
-        @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-        @NonNull
-        public Builder writeBooleanArray(@NonNull final boolean[] elements) {
-            final byte numElements = (byte)elements.length;
-
-            if (writeArrayInfo(numElements, TYPE_BOOLEAN)) {
-                // Write encoding of each element.
-                for (int i = 0; i < numElements; i++) {
-                    mPos += mBuffer.putBoolean(mPos, elements[i]);
-                }
-                mNumElements++;
-            }
-            return this;
-        }
-
-        /**
-         * Write a repeated int field to this StatsEvent.
-         *
-         * The list size must not exceed 127. Otherwise, the array isn't written
-         * to the StatsEvent and ERROR_LIST_TOO_LONG is appended to the
-         * StatsEvent errors field.
-         *
-         * @param elements array of ints.
-         **/
-        @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-        @NonNull
-        public Builder writeIntArray(@NonNull final int[] elements) {
-            final byte numElements = (byte)elements.length;
-
-            if (writeArrayInfo(numElements, TYPE_INT)) {
-              // Write encoding of each element.
-              for (int i = 0; i < numElements; i++) {
-                mPos += mBuffer.putInt(mPos, elements[i]);
-                }
-                mNumElements++;
-            }
-            return this;
-        }
-
-        /**
-         * Write a repeated long field to this StatsEvent.
-         *
-         * The list size must not exceed 127. Otherwise, the array isn't written
-         * to the StatsEvent and ERROR_LIST_TOO_LONG is appended to the
-         * StatsEvent errors field.
-         *
-         * @param elements array of longs.
-         **/
-        @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-        @NonNull
-        public Builder writeLongArray(@NonNull final long[] elements) {
-            final byte numElements = (byte)elements.length;
-
-            if (writeArrayInfo(numElements, TYPE_LONG)) {
-                // Write encoding of each element.
-                for (int i = 0; i < numElements; i++) {
-                    mPos += mBuffer.putLong(mPos, elements[i]);
-                }
-                mNumElements++;
-            }
-            return this;
-        }
-
-        /**
-         * Write a repeated float field to this StatsEvent.
-         *
-         * The list size must not exceed 127. Otherwise, the array isn't written
-         * to the StatsEvent and ERROR_LIST_TOO_LONG is appended to the
-         * StatsEvent errors field.
-         *
-         * @param elements array of floats.
-         **/
-        @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-        @NonNull
-        public Builder writeFloatArray(@NonNull final float[] elements) {
-            final byte numElements = (byte)elements.length;
-
-            if (writeArrayInfo(numElements, TYPE_FLOAT)) {
-                // Write encoding of each element.
-                for (int i = 0; i < numElements; i++) {
-                  mPos += mBuffer.putFloat(mPos, elements[i]);
-                }
-                mNumElements++;
-            }
-            return this;
-        }
-
-        /**
-         * Write a repeated string field to this StatsEvent.
-         *
-         * The list size must not exceed 127. Otherwise, the array isn't written
-         * to the StatsEvent and ERROR_LIST_TOO_LONG is appended to the
-         * StatsEvent errors field.
-         *
-         * @param elements array of strings.
-         **/
-        @RequiresApi(Build.VERSION_CODES.TIRAMISU)
-        @NonNull
-        public Builder writeStringArray(@NonNull final String[] elements) {
-            final byte numElements = (byte)elements.length;
-
-            if (writeArrayInfo(numElements, TYPE_STRING)) {
-                // Write encoding of each element.
-                for (int i = 0; i < numElements; i++) {
-                    final byte[] elementBytes = stringToBytes(elements[i]);
-                    mPos += mBuffer.putInt(mPos, elementBytes.length);
-                    mPos += mBuffer.putByteArray(mPos, elementBytes);
-                }
-                mNumElements++;
-            }
-            return this;
-        }
-
-        /**
-         * Write a boolean annotation for the last field written.
-         **/
-        @NonNull
-        public Builder addBooleanAnnotation(
-                final byte annotationId, final boolean value) {
-            // Ensure there's a field written to annotate.
-            if (mNumElements < 2) {
-                mErrorMask |= ERROR_ANNOTATION_DOES_NOT_FOLLOW_FIELD;
-            } else if (mCurrentAnnotationCount >= MAX_ANNOTATION_COUNT) {
-                mErrorMask |= ERROR_TOO_MANY_ANNOTATIONS;
-            } else {
-                mPos += mBuffer.putByte(mPos, annotationId);
-                mPos += mBuffer.putByte(mPos, TYPE_BOOLEAN);
-                mPos += mBuffer.putBoolean(mPos, value);
-                mCurrentAnnotationCount++;
-                writeAnnotationCount();
-            }
-
-            return this;
-        }
-
-        /**
-         * Write an integer annotation for the last field written.
-         **/
-        @NonNull
-        public Builder addIntAnnotation(final byte annotationId, final int value) {
-            if (mNumElements < 2) {
-                mErrorMask |= ERROR_ANNOTATION_DOES_NOT_FOLLOW_FIELD;
-            } else if (mCurrentAnnotationCount >= MAX_ANNOTATION_COUNT) {
-                mErrorMask |= ERROR_TOO_MANY_ANNOTATIONS;
-            } else {
-                mPos += mBuffer.putByte(mPos, annotationId);
-                mPos += mBuffer.putByte(mPos, TYPE_INT);
-                mPos += mBuffer.putInt(mPos, value);
-                mCurrentAnnotationCount++;
-                writeAnnotationCount();
-            }
-
-            return this;
-        }
-
-        /**
-         * Indicates to reuse Buffer's byte array as the underlying payload in StatsEvent.
-         * This should be called for pushed events to reduce memory allocations and garbage
-         * collections.
-         **/
-        @NonNull
-        public Builder usePooledBuffer() {
-            mUsePooledBuffer = true;
-            mBuffer.setMaxSize(MAX_PUSH_PAYLOAD_SIZE, mPos);
-            return this;
-        }
-
-        /**
-         * Builds a StatsEvent object with values entered in this Builder.
-         **/
-        @NonNull
-        public StatsEvent build() {
-            if (0L == mTimestampNs) {
-                mErrorMask |= ERROR_NO_TIMESTAMP;
-            }
-            if (0 == mAtomId) {
-                mErrorMask |= ERROR_NO_ATOM_ID;
-            }
-            if (mBuffer.hasOverflowed()) {
-                mErrorMask |= ERROR_OVERFLOW;
-            }
-            if (mNumElements > MAX_NUM_ELEMENTS) {
-                mErrorMask |= ERROR_TOO_MANY_FIELDS;
-            }
-
-            if (0 == mErrorMask) {
-                mBuffer.putByte(POS_NUM_ELEMENTS, (byte) mNumElements);
-            } else {
-                // Write atom id and error mask. Overwrite any annotations for atom Id.
-                mPos = POS_ATOM_ID;
-                mPos += mBuffer.putByte(mPos, TYPE_INT);
-                mPos += mBuffer.putInt(mPos, mAtomId);
-                mPos += mBuffer.putByte(mPos, TYPE_ERRORS);
-                mPos += mBuffer.putInt(mPos, mErrorMask);
-                mBuffer.putByte(POS_NUM_ELEMENTS, (byte) 3);
-            }
-
-            final int size = mPos;
-
-            if (mUsePooledBuffer) {
-                return new StatsEvent(mAtomId, mBuffer, mBuffer.getBytes(), size);
-            } else {
-                // Create a copy of the buffer with the required number of bytes.
-                final byte[] payload = new byte[size];
-                System.arraycopy(mBuffer.getBytes(), 0, payload, 0, size);
-
-                // Return Buffer instance to the pool.
-                mBuffer.release();
-
-                return new StatsEvent(mAtomId, null, payload, size);
-            }
-        }
-
-        private void writeTypeId(final byte typeId) {
-            mPosLastField = mPos;
-            mLastType = typeId;
-            mCurrentAnnotationCount = 0;
-            final byte encodedId = (byte) (typeId & 0x0F);
-            mPos += mBuffer.putByte(mPos, encodedId);
-        }
-
-        private void writeAnnotationCount() {
-            // Use first 4 bits for annotation count and last 4 bits for typeId.
-            final byte encodedId = (byte) ((mCurrentAnnotationCount << 4) | (mLastType & 0x0F));
-            mBuffer.putByte(mPosLastField, encodedId);
-        }
-
-        @NonNull
-        private static byte[] stringToBytes(@Nullable final String value) {
-            return (null == value ? "" : value).getBytes(UTF_8);
-        }
-
-        private boolean writeArrayInfo(final byte numElements,
-                                       final byte elementTypeId) {
-            if (numElements > MAX_NUM_ELEMENTS) {
-                mErrorMask |= ERROR_LIST_TOO_LONG;
-                return false;
-            }
-            // Write list typeId byte, 1-byte representation of number of
-            // elements, and element typeId byte.
-            writeTypeId(TYPE_LIST);
-            mPos += mBuffer.putByte(mPos, numElements);
-            // Write element typeId byte without setting mPosLastField and mLastType (i.e. don't use
-            // #writeTypeId)
-            final byte encodedId = (byte) (elementTypeId & 0x0F);
-            mPos += mBuffer.putByte(mPos, encodedId);
-            return true;
-        }
-    }
-
-    private static final class Buffer {
-        private static Object sLock = new Object();
-
-        @GuardedBy("sLock")
-        private static Buffer sPool;
-
-        private byte[] mBytes;
-        private boolean mOverflow = false;
-        private int mMaxSize = MAX_PULL_PAYLOAD_SIZE;
-
-        @NonNull
-        private static Buffer obtain() {
-            final Buffer buffer;
-            synchronized (sLock) {
-                buffer = null == sPool ? new Buffer() : sPool;
-                sPool = null;
-            }
-            buffer.reset();
-            return buffer;
-        }
-
-        private Buffer() {
-            final ByteBuffer tempBuffer = ByteBuffer.allocateDirect(MAX_PUSH_PAYLOAD_SIZE);
-            mBytes = tempBuffer.hasArray() ? tempBuffer.array() : new byte [MAX_PUSH_PAYLOAD_SIZE];
-        }
-
-        @NonNull
-        private byte[] getBytes() {
-            return mBytes;
-        }
-
-        private void release() {
-            // Recycle this Buffer if its size is MAX_PUSH_PAYLOAD_SIZE or under.
-            if (mMaxSize <= MAX_PUSH_PAYLOAD_SIZE) {
-                synchronized (sLock) {
-                    if (null == sPool) {
-                        sPool = this;
-                    }
-                }
-            }
-        }
-
-        private void reset() {
-            mOverflow = false;
-            mMaxSize = MAX_PULL_PAYLOAD_SIZE;
-        }
-
-        private void setMaxSize(final int maxSize, final int numBytesWritten) {
-            mMaxSize = maxSize;
-            if (numBytesWritten > maxSize) {
-                mOverflow = true;
-            }
-        }
-
-        private boolean hasOverflowed() {
-            return mOverflow;
-        }
-
-        /**
-         * Checks for available space in the byte array.
-         *
-         * @param index starting position in the buffer to start the check.
-         * @param numBytes number of bytes to check from index.
-         * @return true if space is available, false otherwise.
-         **/
-        private boolean hasEnoughSpace(final int index, final int numBytes) {
-            final int totalBytesNeeded = index + numBytes;
-
-            if (totalBytesNeeded > mMaxSize) {
-                mOverflow = true;
-                return false;
-            }
-
-            // Expand buffer if needed.
-            if (mBytes.length < mMaxSize && totalBytesNeeded > mBytes.length) {
-                int newSize = mBytes.length;
-                do {
-                    newSize *= 2;
-                } while (newSize <= totalBytesNeeded);
-
-                if (newSize > mMaxSize) {
-                    newSize = mMaxSize;
-                }
-
-                mBytes = Arrays.copyOf(mBytes, newSize);
-            }
-
-            return true;
-        }
-
-        /**
-         * Writes a byte into the buffer.
-         *
-         * @param index position in the buffer where the byte is written.
-         * @param value the byte to write.
-         * @return number of bytes written to buffer from this write operation.
-         **/
-        private int putByte(final int index, final byte value) {
-            if (hasEnoughSpace(index, Byte.BYTES)) {
-                mBytes[index] = (byte) (value);
-                return Byte.BYTES;
-            }
-            return 0;
-        }
-
-        /**
-         * Writes a boolean into the buffer.
-         *
-         * @param index position in the buffer where the boolean is written.
-         * @param value the boolean to write.
-         * @return number of bytes written to buffer from this write operation.
-         **/
-        private int putBoolean(final int index, final boolean value) {
-            return putByte(index, (byte) (value ? 1 : 0));
-        }
-
-        /**
-         * Writes an integer into the buffer.
-         *
-         * @param index position in the buffer where the integer is written.
-         * @param value the integer to write.
-         * @return number of bytes written to buffer from this write operation.
-         **/
-        private int putInt(final int index, final int value) {
-            if (hasEnoughSpace(index, Integer.BYTES)) {
-                // Use little endian byte order.
-                mBytes[index] = (byte) (value);
-                mBytes[index + 1] = (byte) (value >> 8);
-                mBytes[index + 2] = (byte) (value >> 16);
-                mBytes[index + 3] = (byte) (value >> 24);
-                return Integer.BYTES;
-            }
-            return 0;
-        }
-
-        /**
-         * Writes a long into the buffer.
-         *
-         * @param index position in the buffer where the long is written.
-         * @param value the long to write.
-         * @return number of bytes written to buffer from this write operation.
-         **/
-        private int putLong(final int index, final long value) {
-            if (hasEnoughSpace(index, Long.BYTES)) {
-                // Use little endian byte order.
-                mBytes[index] = (byte) (value);
-                mBytes[index + 1] = (byte) (value >> 8);
-                mBytes[index + 2] = (byte) (value >> 16);
-                mBytes[index + 3] = (byte) (value >> 24);
-                mBytes[index + 4] = (byte) (value >> 32);
-                mBytes[index + 5] = (byte) (value >> 40);
-                mBytes[index + 6] = (byte) (value >> 48);
-                mBytes[index + 7] = (byte) (value >> 56);
-                return Long.BYTES;
-            }
-            return 0;
-        }
-
-        /**
-         * Writes a float into the buffer.
-         *
-         * @param index position in the buffer where the float is written.
-         * @param value the float to write.
-         * @return number of bytes written to buffer from this write operation.
-         **/
-        private int putFloat(final int index, final float value) {
-            return putInt(index, Float.floatToIntBits(value));
-        }
-
-        /**
-         * Copies a byte array into the buffer.
-         *
-         * @param index position in the buffer where the byte array is copied.
-         * @param value the byte array to copy.
-         * @return number of bytes written to buffer from this write operation.
-         **/
-        private int putByteArray(final int index, @NonNull final byte[] value) {
-            final int numBytes = value.length;
-            if (hasEnoughSpace(index, numBytes)) {
-                System.arraycopy(value, 0, mBytes, index, numBytes);
-                return numBytes;
-            }
-            return 0;
-        }
-    }
-}
diff --git a/ravenwood/runtime-helper-src/framework/android/util/StatsLog.java b/ravenwood/runtime-helper-src/framework/android/util/StatsLog.java
deleted file mode 100644
index c1c20cf..0000000
--- a/ravenwood/runtime-helper-src/framework/android/util/StatsLog.java
+++ /dev/null
@@ -1,478 +0,0 @@
-/*
- * Copyright (C) 2017 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.util;
-
-/*
- * [Ravenwood] This is copied from StatsD, with the following changes:
- * - The static {} is commented out.
- * - All references to IStatsD and StatsdStatsLog are commented out.
- * - The native method is no-oped.
- */
-
-import static android.Manifest.permission.DUMP;
-import static android.Manifest.permission.PACKAGE_USAGE_STATS;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.RequiresPermission;
-import android.annotation.SuppressLint;
-import android.annotation.SystemApi;
-import android.os.Build;
-//import android.os.IStatsd;
-import android.os.Process;
-import android.util.proto.ProtoOutputStream;
-
-import androidx.annotation.RequiresApi;
-
-//import com.android.internal.statsd.StatsdStatsLog;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-/**
- * StatsLog provides an API for developers to send events to statsd. The events can be used to
- * define custom metrics in side statsd.
- */
-public final class StatsLog {
-
-//    // Load JNI library
-//    static {
-//        System.loadLibrary("stats_jni");
-//    }
-    private static final String TAG = "StatsLog";
-    private static final boolean DEBUG = false;
-    private static final int EXPERIMENT_IDS_FIELD_ID = 1;
-
-    /**
-     * Annotation ID constant for logging UID field.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    public static final byte ANNOTATION_ID_IS_UID = 1;
-
-    /**
-     * Annotation ID constant to indicate logged atom event's timestamp should be truncated.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    public static final byte ANNOTATION_ID_TRUNCATE_TIMESTAMP = 2;
-
-    /**
-     * Annotation ID constant for a state atom's primary field.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    public static final byte ANNOTATION_ID_PRIMARY_FIELD = 3;
-
-    /**
-     * Annotation ID constant for state atom's state field.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    public static final byte ANNOTATION_ID_EXCLUSIVE_STATE = 4;
-
-    /**
-     * Annotation ID constant to indicate the first UID in the attribution chain
-     * is a primary field.
-     * Should only be used for attribution chain fields.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    public static final byte ANNOTATION_ID_PRIMARY_FIELD_FIRST_UID = 5;
-
-    /**
-     * Annotation ID constant to indicate which state is default for the state atom.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    public static final byte ANNOTATION_ID_DEFAULT_STATE = 6;
-
-    /**
-     * Annotation ID constant to signal all states should be reset to the default state.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    public static final byte ANNOTATION_ID_TRIGGER_STATE_RESET = 7;
-
-    /**
-     * Annotation ID constant to indicate state changes need to account for nesting.
-     * This should only be used with binary state atoms.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    public static final byte ANNOTATION_ID_STATE_NESTED = 8;
-
-    /**
-     * Annotation ID constant to indicate the restriction category of an atom.
-     * This annotation must only be attached to the atom id. This is an int annotation.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final byte ANNOTATION_ID_RESTRICTION_CATEGORY = 9;
-
-    /**
-     * Annotation ID to indicate that a field of an atom contains peripheral device info.
-     * This is a bool annotation.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final byte ANNOTATION_ID_FIELD_RESTRICTION_PERIPHERAL_DEVICE_INFO = 10;
-
-    /**
-     * Annotation ID to indicate that a field of an atom contains app usage information.
-     * This is a bool annotation.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final byte ANNOTATION_ID_FIELD_RESTRICTION_APP_USAGE = 11;
-
-    /**
-     * Annotation ID to indicate that a field of an atom contains app activity information.
-     * This is a bool annotation.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final byte ANNOTATION_ID_FIELD_RESTRICTION_APP_ACTIVITY = 12;
-
-    /**
-     * Annotation ID to indicate that a field of an atom contains health connect information.
-     * This is a bool annotation.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final byte ANNOTATION_ID_FIELD_RESTRICTION_HEALTH_CONNECT = 13;
-
-    /**
-     * Annotation ID to indicate that a field of an atom contains accessibility information.
-     * This is a bool annotation.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final byte ANNOTATION_ID_FIELD_RESTRICTION_ACCESSIBILITY = 14;
-
-    /**
-     * Annotation ID to indicate that a field of an atom contains system search information.
-     * This is a bool annotation.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final byte ANNOTATION_ID_FIELD_RESTRICTION_SYSTEM_SEARCH = 15;
-
-    /**
-     * Annotation ID to indicate that a field of an atom contains user engagement information.
-     * This is a bool annotation.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final byte ANNOTATION_ID_FIELD_RESTRICTION_USER_ENGAGEMENT = 16;
-
-    /**
-     * Annotation ID to indicate that a field of an atom contains ambient sensing information.
-     * This is a bool annotation.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final byte ANNOTATION_ID_FIELD_RESTRICTION_AMBIENT_SENSING = 17;
-
-    /**
-     * Annotation ID to indicate that a field of an atom contains demographic classification
-     * information. This is a bool annotation.
-     *
-     * The ID is a byte since StatsEvent.addBooleanAnnotation() and StatsEvent.addIntAnnotation()
-     * accept byte as the type for annotation ids to save space.
-     *
-     * @hide
-     */
-    @SuppressLint("NoByteOrShort")
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final byte ANNOTATION_ID_FIELD_RESTRICTION_DEMOGRAPHIC_CLASSIFICATION = 18;
-
-
-    /** @hide */
-    @IntDef(prefix = { "RESTRICTION_CATEGORY_" }, value = {
-            RESTRICTION_CATEGORY_DIAGNOSTIC,
-            RESTRICTION_CATEGORY_SYSTEM_INTELLIGENCE,
-            RESTRICTION_CATEGORY_AUTHENTICATION,
-            RESTRICTION_CATEGORY_FRAUD_AND_ABUSE})
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface RestrictionCategory {}
-
-    /**
-     * Restriction category for atoms about diagnostics.
-     *
-     * @hide
-     */
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final int RESTRICTION_CATEGORY_DIAGNOSTIC = 1;
-
-    /**
-     * Restriction category for atoms about system intelligence.
-     *
-     * @hide
-     */
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final int RESTRICTION_CATEGORY_SYSTEM_INTELLIGENCE = 2;
-
-    /**
-     * Restriction category for atoms about authentication.
-     *
-     * @hide
-     */
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final int RESTRICTION_CATEGORY_AUTHENTICATION = 3;
-
-    /**
-     * Restriction category for atoms about fraud and abuse.
-     *
-     * @hide
-     */
-    @SystemApi
-    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
-    public static final int RESTRICTION_CATEGORY_FRAUD_AND_ABUSE = 4;
-
-    private StatsLog() {
-    }
-
-    /**
-     * Logs a start event.
-     *
-     * @param label developer-chosen label.
-     * @return True if the log request was sent to statsd.
-     */
-    public static boolean logStart(int label) {
-        int callingUid = Process.myUid();
-//        StatsdStatsLog.write(
-//                StatsdStatsLog.APP_BREADCRUMB_REPORTED,
-//                callingUid,
-//                label,
-//                StatsdStatsLog.APP_BREADCRUMB_REPORTED__STATE__START);
-        return true;
-    }
-
-    /**
-     * Logs a stop event.
-     *
-     * @param label developer-chosen label.
-     * @return True if the log request was sent to statsd.
-     */
-    public static boolean logStop(int label) {
-        int callingUid = Process.myUid();
-//        StatsdStatsLog.write(
-//                StatsdStatsLog.APP_BREADCRUMB_REPORTED,
-//                callingUid,
-//                label,
-//                StatsdStatsLog.APP_BREADCRUMB_REPORTED__STATE__STOP);
-        return true;
-    }
-
-    /**
-     * Logs an event that does not represent a start or stop boundary.
-     *
-     * @param label developer-chosen label.
-     * @return True if the log request was sent to statsd.
-     */
-    public static boolean logEvent(int label) {
-        int callingUid = Process.myUid();
-//        StatsdStatsLog.write(
-//                StatsdStatsLog.APP_BREADCRUMB_REPORTED,
-//                callingUid,
-//                label,
-//                StatsdStatsLog.APP_BREADCRUMB_REPORTED__STATE__UNSPECIFIED);
-        return true;
-    }
-
-    /**
-     * Logs an event for binary push for module updates.
-     *
-     * @param trainName        name of install train.
-     * @param trainVersionCode version code of the train.
-     * @param options          optional flags about this install.
-     *                         The last 3 bits indicate options:
-     *                             0x01: FLAG_REQUIRE_STAGING
-     *                             0x02: FLAG_ROLLBACK_ENABLED
-     *                             0x04: FLAG_REQUIRE_LOW_LATENCY_MONITOR
-     * @param state            current install state. Defined as State enums in
-     *                         BinaryPushStateChanged atom in
-     *                         frameworks/proto_logging/stats/atoms.proto
-     * @param experimentIds    experiment ids.
-     * @return True if the log request was sent to statsd.
-     */
-    @RequiresPermission(allOf = {DUMP, PACKAGE_USAGE_STATS})
-    public static boolean logBinaryPushStateChanged(@NonNull String trainName,
-            long trainVersionCode, int options, int state,
-            @NonNull long[] experimentIds) {
-        ProtoOutputStream proto = new ProtoOutputStream();
-        for (long id : experimentIds) {
-            proto.write(
-                    ProtoOutputStream.FIELD_TYPE_INT64
-                    | ProtoOutputStream.FIELD_COUNT_REPEATED
-                    | EXPERIMENT_IDS_FIELD_ID,
-                    id);
-        }
-//        StatsdStatsLog.write(StatsdStatsLog.BINARY_PUSH_STATE_CHANGED,
-//                trainName,
-//                trainVersionCode,
-//                (options & IStatsd.FLAG_REQUIRE_STAGING) > 0,
-//                (options & IStatsd.FLAG_ROLLBACK_ENABLED) > 0,
-//                (options & IStatsd.FLAG_REQUIRE_LOW_LATENCY_MONITOR) > 0,
-//                state,
-//                proto.getBytes(),
-//                0,
-//                0,
-//                false);
-        return true;
-    }
-
-    /**
-     * Write an event to stats log using the raw format.
-     *
-     * @param buffer    The encoded buffer of data to write.
-     * @param size      The number of bytes from the buffer to write.
-     * @hide
-     * @deprecated Use {@link write(final StatsEvent statsEvent)} instead.
-     *
-     */
-    @Deprecated
-    @SystemApi
-    public static void writeRaw(@NonNull byte[] buffer, int size) {
-        writeImpl(buffer, size, 0);
-    }
-
-    /**
-     * Write an event to stats log using the raw format.
-     *
-     * @param buffer    The encoded buffer of data to write.
-     * @param size      The number of bytes from the buffer to write.
-     * @param atomId    The id of the atom to which the event belongs.
-     */
-//    private static native void writeImpl(@NonNull byte[] buffer, int size, int atomId);
-    private static void writeImpl(@NonNull byte[] buffer, int size, int atomId) {
-        // no-op for now
-    }
-
-    /**
-     * Write an event to stats log using the raw format encapsulated in StatsEvent.
-     * After writing to stats log, release() is called on the StatsEvent object.
-     * No further action should be taken on the StatsEvent object following this call.
-     *
-     * @param statsEvent    The StatsEvent object containing the encoded buffer of data to write.
-     * @hide
-     */
-    @SystemApi
-    public static void write(@NonNull final StatsEvent statsEvent) {
-        writeImpl(statsEvent.getBytes(), statsEvent.getNumBytes(), statsEvent.getAtomId());
-        statsEvent.release();
-    }
-}
diff --git a/ravenwood/scripts/ravenwood-stats-collector.sh b/ravenwood/scripts/ravenwood-stats-collector.sh
index 36601bd..b83216a 100755
--- a/ravenwood/scripts/ravenwood-stats-collector.sh
+++ b/ravenwood/scripts/ravenwood-stats-collector.sh
@@ -62,6 +62,8 @@
 
         dump "framework-minus-apex" hoststubgen_framework-minus-apex_stats.csv
         dump "service.core"  hoststubgen_services.core_stats.csv
+        dump "framework-configinfrastructure"  framework-configinfrastructure_stats.csv
+        dump "framework-statsd"  framework-statsd_stats.csv
     } > "$out"
 
     echo "Stats CVS created at $out"
@@ -76,6 +78,8 @@
 
         dump "framework-minus-apex"  hoststubgen_framework-minus-apex_apis.csv
         dump "service.core"  hoststubgen_services.core_apis.csv
+        dump "framework-configinfrastructure"  framework-configinfrastructure_apis.csv
+        dump "framework-statsd"  framework-statsd_apis.csv
     } > "$out"
 
     echo "API CVS created at $out"
diff --git a/ravenwood/scripts/run-ravenwood-tests.sh b/ravenwood/scripts/run-ravenwood-tests.sh
index 926c08f..5d623e0 100755
--- a/ravenwood/scripts/run-ravenwood-tests.sh
+++ b/ravenwood/scripts/run-ravenwood-tests.sh
@@ -14,15 +14,42 @@
 # limitations under the License.
 
 # Run all the ravenwood tests + hoststubgen unit tests.
+#
+# Options:
+#
+#   -s: "Smoke" test -- skip slow tests (SysUI, ICU)
 
-all_tests="hoststubgentest tiny-framework-dump-test hoststubgen-invoke-test ravenwood-stats-checker"
+smoke=0
+while getopts "s" opt; do
+case "$opt" in
+    s)
+        smoke=1
+        ;;
+    '?')
+        exit 1
+        ;;
+esac
+done
+shift $(($OPTIND - 1))
 
-# "echo" is to remove the newlines
-all_tests="$all_tests $(echo $(${0%/*}/list-ravenwood-tests.sh) )"
+all_tests=(hoststubgentest tiny-framework-dump-test hoststubgen-invoke-test ravenwood-stats-checker)
+all_tests+=( $(${0%/*}/list-ravenwood-tests.sh) )
+
+# Regex to identify slow tests, in PCRE
+slow_tests_re='^(SystemUiRavenTests|CtsIcuTestCasesRavenwood)$'
+
+if (( $smoke )) ; then
+    # Remove the slow tests.
+    all_tests=( $(
+        for t in "${all_tests[@]}"; do
+            echo $t | grep -vP "$slow_tests_re"
+        done
+    ) )
+fi
 
 run() {
     echo "Running: $*"
     "${@}"
 }
 
-run ${ATEST:-atest} $all_tests
+run ${ATEST:-atest} "${all_tests[@]}"
diff --git a/ravenwood/tests/coretest/Android.bp b/ravenwood/tests/coretest/Android.bp
index 85f1baf..412744e 100644
--- a/ravenwood/tests/coretest/Android.bp
+++ b/ravenwood/tests/coretest/Android.bp
@@ -23,6 +23,7 @@
     ],
     srcs: [
         "test/**/*.java",
+        "test/**/*.kt",
     ],
     ravenizer: {
         strip_mockito: true,
diff --git a/ravenwood/tests/coretest/test/com/android/ravenwoodtest/coretest/RavenwoodStatsDTest.kt b/ravenwood/tests/coretest/test/com/android/ravenwoodtest/coretest/RavenwoodStatsDTest.kt
new file mode 100644
index 0000000..d5f5e29
--- /dev/null
+++ b/ravenwood/tests/coretest/test/com/android/ravenwoodtest/coretest/RavenwoodStatsDTest.kt
@@ -0,0 +1,26 @@
+/*
+ * 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 com.android.ravenwoodtest.coretest
+
+import com.android.internal.util.FrameworkStatsLog
+import org.junit.Test
+
+class RavenwoodStatsDTest {
+    @Test
+    fun testFrameworkStatsLog() {
+        FrameworkStatsLog.write(FrameworkStatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, 123)
+    }
+}
\ No newline at end of file
diff --git a/ravenwood/texts/ravenwood-framework-policies.txt b/ravenwood/texts/ravenwood-framework-policies.txt
index b64944e..80126df 100644
--- a/ravenwood/texts/ravenwood-framework-policies.txt
+++ b/ravenwood/texts/ravenwood-framework-policies.txt
@@ -5,8 +5,7 @@
 rename com/.*/nano/   devicenano/
 rename android/.*/nano/   devicenano/
 
-
-# StatsD autogenerated classes. Maybe add a heuristic?
+# StatsD auto-generated
 class com.android.internal.util.FrameworkStatsLog keepclass
 
 # Exported to Mainline modules; cannot use annotations
diff --git a/services/core/Android.bp b/services/core/Android.bp
index 3532b0a..349f3ee 100644
--- a/services/core/Android.bp
+++ b/services/core/Android.bp
@@ -50,7 +50,7 @@
     ],
 }
 
-genrule {
+java_genrule {
     name: "services.core.protologsrc",
     srcs: [
         ":protolog-impl",
@@ -70,7 +70,7 @@
     out: ["services.core.protolog.srcjar"],
 }
 
-genrule {
+java_genrule {
     name: "generate-protolog.json",
     srcs: [
         ":protolog-groups",
@@ -87,7 +87,7 @@
     out: ["services.core.protolog.json"],
 }
 
-genrule {
+java_genrule {
     name: "gen-core.protolog.pb",
     srcs: [
         ":protolog-groups",
@@ -281,7 +281,7 @@
     src: "java/com/android/server/location/gnss/gps_debug.conf",
 }
 
-genrule {
+java_genrule {
     name: "services.core.json.gz",
     srcs: [":generate-protolog.json"],
     out: ["services.core.protolog.json.gz"],
diff --git a/services/core/java/com/android/server/OWNERS b/services/core/java/com/android/server/OWNERS
index 37dddc6..c15cf34 100644
--- a/services/core/java/com/android/server/OWNERS
+++ b/services/core/java/com/android/server/OWNERS
@@ -48,3 +48,6 @@
 
 # CertBlocklister
 per-file Cert*.java = tweek@google.com, brambonne@google.com, prb@google.com, miguelaranda@google.com
+
+# TradeInMode
+per-file TradeInModeService.java = dvander@google.com, paullawrence@google.com
diff --git a/services/core/java/com/android/server/Watchdog.java b/services/core/java/com/android/server/Watchdog.java
index 918f130..0dedb73 100644
--- a/services/core/java/com/android/server/Watchdog.java
+++ b/services/core/java/com/android/server/Watchdog.java
@@ -289,7 +289,7 @@
         public void scheduleCheckLocked(long handlerCheckerTimeoutMillis) {
             mWaitMaxMillis = handlerCheckerTimeoutMillis;
 
-            if (mCompleted) {
+            if (mCompleted && !mMonitorQueue.isEmpty()) {
                 // Safe to update monitors in queue, Handler is not in the middle of work
                 mMonitors.addAll(mMonitorQueue);
                 mMonitorQueue.clear();
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 4efe62c..f549c7b 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -2884,23 +2884,24 @@
                 addServiceToMap(mAppBindArgs, Context.INPUT_METHOD_SERVICE);
                 addServiceToMap(mAppBindArgs, Context.INPUT_SERVICE);
                 addServiceToMap(mAppBindArgs, "graphicsstats");
-                addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE);
                 addServiceToMap(mAppBindArgs, "content");
                 addServiceToMap(mAppBindArgs, Context.JOB_SCHEDULER_SERVICE);
                 addServiceToMap(mAppBindArgs, Context.NOTIFICATION_SERVICE);
                 addServiceToMap(mAppBindArgs, Context.VIBRATOR_SERVICE);
                 addServiceToMap(mAppBindArgs, Context.ACCOUNT_SERVICE);
                 addServiceToMap(mAppBindArgs, Context.POWER_SERVICE);
-                addServiceToMap(mAppBindArgs, Context.USER_SERVICE);
                 addServiceToMap(mAppBindArgs, "mount");
                 addServiceToMap(mAppBindArgs, Context.PLATFORM_COMPAT_SERVICE);
             }
             // See b/79378449
             // Getting the window service and package service binder from servicemanager
             // is blocked for Apps. However they are necessary for apps.
+            // Removing User Service and App Ops Service from cache breaks boot for auto.
             // TODO: remove exception
+            addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE);
             addServiceToMap(mAppBindArgs, "package");
             addServiceToMap(mAppBindArgs, Context.WINDOW_SERVICE);
+            addServiceToMap(mAppBindArgs, Context.USER_SERVICE);
         }
         return mAppBindArgs;
     }
diff --git a/services/core/java/com/android/server/appop/AppOpsService.java b/services/core/java/com/android/server/appop/AppOpsService.java
index d67d3ca..7600855 100644
--- a/services/core/java/com/android/server/appop/AppOpsService.java
+++ b/services/core/java/com/android/server/appop/AppOpsService.java
@@ -4973,17 +4973,7 @@
                     }
 
                     success = true;
-                } catch (IllegalStateException e) {
-                    Slog.w(TAG, "Failed parsing " + e);
-                } catch (NullPointerException e) {
-                    Slog.w(TAG, "Failed parsing " + e);
-                } catch (NumberFormatException e) {
-                    Slog.w(TAG, "Failed parsing " + e);
-                } catch (XmlPullParserException e) {
-                    Slog.w(TAG, "Failed parsing " + e);
-                } catch (IOException e) {
-                    Slog.w(TAG, "Failed parsing " + e);
-                } catch (IndexOutOfBoundsException e) {
+                } catch (Exception e) {
                     Slog.w(TAG, "Failed parsing " + e);
                 } finally {
                     if (!success) {
diff --git a/services/core/java/com/android/server/appop/LegacyAppOpStateParser.java b/services/core/java/com/android/server/appop/LegacyAppOpStateParser.java
index 9ed3a99..b677a1d 100644
--- a/services/core/java/com/android/server/appop/LegacyAppOpStateParser.java
+++ b/services/core/java/com/android/server/appop/LegacyAppOpStateParser.java
@@ -50,6 +50,10 @@
     public int readState(AtomicFile file, SparseArray<SparseIntArray> uidModes,
             SparseArray<ArrayMap<String, SparseIntArray>> userPackageModes) {
         try (FileInputStream stream = file.openRead()) {
+            SparseArray<SparseIntArray> parsedUidModes = new SparseArray<>();
+            SparseArray<ArrayMap<String, SparseIntArray>> parsedUserPackageModes =
+                    new SparseArray<>();
+
             TypedXmlPullParser parser = Xml.resolvePullParser(stream);
             int type;
             while ((type = parser.next()) != XmlPullParser.START_TAG
@@ -75,26 +79,37 @@
                     // version 2 has the structure pkg -> uid -> op ->
                     // in version 3, since pkg and uid states are kept completely
                     // independent we switch to user -> pkg -> op
-                    readPackage(parser, userPackageModes);
+                    readPackage(parser, parsedUserPackageModes);
                 } else if (tagName.equals("uid")) {
-                    readUidOps(parser, uidModes);
+                    readUidOps(parser, parsedUidModes);
                 } else if (tagName.equals("user")) {
-                    readUser(parser, userPackageModes);
+                    readUser(parser, parsedUserPackageModes);
                 } else {
                     Slog.w(TAG, "Unknown element under <app-ops>: "
                             + parser.getName());
                     XmlUtils.skipCurrentTag(parser);
                 }
             }
+
+            // Parsing is complete, copy all parsed values to output
+            final int parsedUidModesSize = parsedUidModes.size();
+            for (int i = 0; i < parsedUidModesSize; i++) {
+                uidModes.put(parsedUidModes.keyAt(i), parsedUidModes.valueAt(i));
+            }
+            final int parsedUserPackageModesSize = parsedUserPackageModes.size();
+            for (int i = 0; i < parsedUserPackageModesSize; i++) {
+                userPackageModes.put(parsedUserPackageModes.keyAt(i),
+                                     parsedUserPackageModes.valueAt(i));
+            }
+
             return versionAtBoot;
         } catch (FileNotFoundException e) {
             Slog.i(TAG, "No existing app ops " + file.getBaseFile() + "; starting empty");
-            return NO_FILE_VERSION;
-        } catch (XmlPullParserException e) {
-            throw new RuntimeException(e);
-        } catch (IOException e) {
-            throw new RuntimeException(e);
+        } catch (Exception e) {
+            // All exceptions must be caught, otherwise device will not be able to boot
+            Slog.wtf(TAG, "Failed parsing " + e);
         }
+        return NO_FILE_VERSION;
     }
 
     private void readPackage(TypedXmlPullParser parser,
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index b0590fe..2d3b7f3 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -787,9 +787,11 @@
             AudioSystem.DEVICE_OUT_HDMI_EARC
     ));
 
+    private final Object mAbsoluteVolumeDeviceInfoMapLock = new Object();
     // Devices where the framework sends a full scale audio signal, and controls the volume of
     // the external audio system separately.
     // For possible volume behaviors, see {@link AudioManager.AbsoluteDeviceVolumeBehavior}.
+    @GuardedBy("mAbsoluteVolumeDeviceInfoMapLock")
     Map<Integer, AbsoluteVolumeDeviceInfo> mAbsoluteVolumeDeviceInfoMap = new ArrayMap<>();
 
     /**
@@ -3729,9 +3731,8 @@
         int oldIndex = mStreamStates[streamType].getIndex(device);
 
         // Check if the volume adjustment should be handled by an absolute volume controller instead
-        if (isAbsoluteVolumeDevice(device)
-                && (flags & AudioManager.FLAG_ABSOLUTE_VOLUME) == 0) {
-            AbsoluteVolumeDeviceInfo info = mAbsoluteVolumeDeviceInfoMap.get(device);
+        if (isAbsoluteVolumeDevice(device) && (flags & AudioManager.FLAG_ABSOLUTE_VOLUME) == 0) {
+            final AbsoluteVolumeDeviceInfo info = getAbsoluteVolumeDeviceInfo(device);
             if (info.mHandlesVolumeAdjustment) {
                 dispatchAbsoluteVolumeAdjusted(streamType, info, oldIndex, direction,
                         keyEventMode);
@@ -3798,7 +3799,7 @@
                 mDeviceBroker.postSetAvrcpAbsoluteVolumeIndex(newIndex / 10);
             } else if (isAbsoluteVolumeDevice(device)
                     && (flags & AudioManager.FLAG_ABSOLUTE_VOLUME) == 0) {
-                AbsoluteVolumeDeviceInfo info = mAbsoluteVolumeDeviceInfoMap.get(device);
+                final AbsoluteVolumeDeviceInfo info = getAbsoluteVolumeDeviceInfo(device);
                 dispatchAbsoluteVolumeChanged(streamType, info, newIndex);
             }
 
@@ -4801,7 +4802,7 @@
             mDeviceBroker.postSetAvrcpAbsoluteVolumeIndex(index / 10);
         } else if (isAbsoluteVolumeDevice(device)
                 && ((flags & AudioManager.FLAG_ABSOLUTE_VOLUME) == 0)) {
-            AbsoluteVolumeDeviceInfo info = mAbsoluteVolumeDeviceInfoMap.get(device);
+            final AbsoluteVolumeDeviceInfo info = getAbsoluteVolumeDeviceInfo(device);
 
             dispatchAbsoluteVolumeChanged(streamType, info, index);
         }
@@ -7603,7 +7604,8 @@
         if (register) {
             AbsoluteVolumeDeviceInfo info = new AbsoluteVolumeDeviceInfo(
                     device, volumes, cb, handlesVolumeAdjustment, deviceVolumeBehavior);
-            AbsoluteVolumeDeviceInfo oldInfo = mAbsoluteVolumeDeviceInfoMap.get(deviceOut);
+            final AbsoluteVolumeDeviceInfo oldInfo = getAbsoluteVolumeDeviceInfo(deviceOut);
+
             boolean volumeBehaviorChanged = (oldInfo == null)
                     || (oldInfo.mDeviceVolumeBehavior != deviceVolumeBehavior);
             if (volumeBehaviorChanged) {
@@ -7763,8 +7765,10 @@
         if (mAbsVolumeMultiModeCaseDevices.contains(audioSystemDeviceOut)) {
             return AudioManager.DEVICE_VOLUME_BEHAVIOR_ABSOLUTE_MULTI_MODE;
         }
-        if (mAbsoluteVolumeDeviceInfoMap.containsKey(audioSystemDeviceOut)) {
-            return mAbsoluteVolumeDeviceInfoMap.get(audioSystemDeviceOut).mDeviceVolumeBehavior;
+        synchronized (mAbsoluteVolumeDeviceInfoMapLock) {
+            if (mAbsoluteVolumeDeviceInfoMap.containsKey(audioSystemDeviceOut)) {
+                return mAbsoluteVolumeDeviceInfoMap.get(audioSystemDeviceOut).mDeviceVolumeBehavior;
+            }
         }
 
         if (isA2dpAbsoluteVolumeDevice(audioSystemDeviceOut)
@@ -11806,10 +11810,12 @@
     }
 
     private Set<Integer> getAbsoluteVolumeDevicesWithBehavior(int behavior) {
-        return mAbsoluteVolumeDeviceInfoMap.entrySet().stream()
-                .filter(entry -> entry.getValue().mDeviceVolumeBehavior == behavior)
-                .map(Map.Entry::getKey)
-                .collect(Collectors.toSet());
+        synchronized (mAbsoluteVolumeDeviceInfoMapLock) {
+            return mAbsoluteVolumeDeviceInfoMap.entrySet().stream()
+                    .filter(entry -> entry.getValue().mDeviceVolumeBehavior == behavior)
+                    .map(Map.Entry::getKey)
+                    .collect(Collectors.toSet());
+        }
     }
 
     private String dumpDeviceTypes(@NonNull Set<Integer> deviceTypes) {
@@ -14302,14 +14308,26 @@
     }
 
     /**
+     * Returns the input device which uses absolute volume behavior, including its variants,
+     * or {@code null} if there is no mapping for the device type
+     */
+    @Nullable
+    private AbsoluteVolumeDeviceInfo getAbsoluteVolumeDeviceInfo(int deviceType) {
+        synchronized (mAbsoluteVolumeDeviceInfoMapLock) {
+            return mAbsoluteVolumeDeviceInfoMap.get(deviceType);
+        }
+    }
+
+    /**
      * Returns whether the input device uses absolute volume behavior, including its variants.
      * For included volume behaviors, see {@link AudioManager.AbsoluteDeviceVolumeBehavior}.
-     *
-     * This is distinct from Bluetooth A2DP absolute volume behavior
+     * <p>This is distinct from Bluetooth A2DP absolute volume behavior
      * ({@link #isA2dpAbsoluteVolumeDevice}).
      */
     private boolean isAbsoluteVolumeDevice(int deviceType) {
-        return mAbsoluteVolumeDeviceInfoMap.containsKey(deviceType);
+        synchronized (mAbsoluteVolumeDeviceInfoMapLock) {
+            return mAbsoluteVolumeDeviceInfoMap.containsKey(deviceType);
+        }
     }
 
     /**
@@ -14421,7 +14439,9 @@
                     + AudioDeviceVolumeManager.volumeBehaviorName(info.mDeviceVolumeBehavior)
             );
         }
-        mAbsoluteVolumeDeviceInfoMap.put(audioSystemDeviceOut, info);
+        synchronized (mAbsoluteVolumeDeviceInfoMapLock) {
+            mAbsoluteVolumeDeviceInfoMap.put(audioSystemDeviceOut, info);
+        }
     }
 
     private AbsoluteVolumeDeviceInfo removeAudioSystemDeviceOutFromAbsVolumeDevices(
@@ -14430,7 +14450,10 @@
             Log.d(TAG, "Removing DeviceType: 0x" + Integer.toHexString(audioSystemDeviceOut)
                     + " from mAbsoluteVolumeDeviceInfoMap");
         }
-        return mAbsoluteVolumeDeviceInfoMap.remove(audioSystemDeviceOut);
+
+        synchronized (mAbsoluteVolumeDeviceInfoMapLock) {
+            return mAbsoluteVolumeDeviceInfoMap.remove(audioSystemDeviceOut);
+        }
     }
 
     //====================
diff --git a/services/core/java/com/android/server/integrity/IntegrityFileManager.java b/services/core/java/com/android/server/integrity/IntegrityFileManager.java
deleted file mode 100644
index 7f0231e..0000000
--- a/services/core/java/com/android/server/integrity/IntegrityFileManager.java
+++ /dev/null
@@ -1,218 +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 android.annotation.Nullable;
-import android.content.integrity.AppInstallMetadata;
-import android.content.integrity.Rule;
-import android.os.Environment;
-import android.util.Slog;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.server.integrity.model.RuleMetadata;
-import com.android.server.integrity.parser.RandomAccessObject;
-import com.android.server.integrity.parser.RuleBinaryParser;
-import com.android.server.integrity.parser.RuleIndexRange;
-import com.android.server.integrity.parser.RuleIndexingController;
-import com.android.server.integrity.parser.RuleMetadataParser;
-import com.android.server.integrity.parser.RuleParseException;
-import com.android.server.integrity.parser.RuleParser;
-import com.android.server.integrity.serializer.RuleBinarySerializer;
-import com.android.server.integrity.serializer.RuleMetadataSerializer;
-import com.android.server.integrity.serializer.RuleSerializeException;
-import com.android.server.integrity.serializer.RuleSerializer;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-
-/** Abstraction over the underlying storage of rules and other metadata. */
-public class IntegrityFileManager {
-    private static final String TAG = "IntegrityFileManager";
-
-    private static final String METADATA_FILE = "metadata";
-    private static final String RULES_FILE = "rules";
-    private static final String INDEXING_FILE = "indexing";
-    private static final Object RULES_LOCK = new Object();
-
-    private static IntegrityFileManager sInstance = null;
-
-    private final RuleParser mRuleParser;
-    private final RuleSerializer mRuleSerializer;
-
-    private final File mDataDir;
-    // mRulesDir contains data of the actual rules currently stored.
-    private final File mRulesDir;
-    // mStagingDir is used to store the temporary rules / metadata during updating, since we want to
-    // update rules atomically.
-    private final File mStagingDir;
-
-    @Nullable private RuleMetadata mRuleMetadataCache;
-    @Nullable private RuleIndexingController mRuleIndexingController;
-
-    /** Get the singleton instance of this class. */
-    public static synchronized IntegrityFileManager getInstance() {
-        if (sInstance == null) {
-            sInstance = new IntegrityFileManager();
-        }
-        return sInstance;
-    }
-
-    private IntegrityFileManager() {
-        this(
-                new RuleBinaryParser(),
-                new RuleBinarySerializer(),
-                Environment.getDataSystemDirectory());
-    }
-
-    @VisibleForTesting
-    IntegrityFileManager(RuleParser ruleParser, RuleSerializer ruleSerializer, File dataDir) {
-        mRuleParser = ruleParser;
-        mRuleSerializer = ruleSerializer;
-        mDataDir = dataDir;
-
-        mRulesDir = new File(dataDir, "integrity_rules");
-        mStagingDir = new File(dataDir, "integrity_staging");
-
-        if (!mStagingDir.mkdirs() || !mRulesDir.mkdirs()) {
-            Slog.e(TAG, "Error creating staging and rules directory");
-            // TODO: maybe throw an exception?
-        }
-
-        File metadataFile = new File(mRulesDir, METADATA_FILE);
-        if (metadataFile.exists()) {
-            try (FileInputStream inputStream = new FileInputStream(metadataFile)) {
-                mRuleMetadataCache = RuleMetadataParser.parse(inputStream);
-            } catch (Exception e) {
-                Slog.e(TAG, "Error reading metadata file.", e);
-            }
-        }
-
-        updateRuleIndexingController();
-    }
-
-    /**
-     * Returns if the rules have been initialized.
-     *
-     * <p>Used to fail early if there are no rules (so we don't need to parse the apk at all).
-     */
-    public boolean initialized() {
-        return new File(mRulesDir, RULES_FILE).exists()
-                && new File(mRulesDir, METADATA_FILE).exists()
-                && new File(mRulesDir, INDEXING_FILE).exists();
-    }
-
-    /** Write rules to persistent storage. */
-    public void writeRules(String version, String ruleProvider, List<Rule> rules)
-            throws IOException, RuleSerializeException {
-        try {
-            writeMetadata(mStagingDir, ruleProvider, version);
-        } catch (IOException e) {
-            Slog.e(TAG, "Error writing metadata.", e);
-            // We don't consider this fatal so we continue execution.
-        }
-
-        try (FileOutputStream ruleFileOutputStream =
-                        new FileOutputStream(new File(mStagingDir, RULES_FILE));
-                FileOutputStream indexingFileOutputStream =
-                        new FileOutputStream(new File(mStagingDir, INDEXING_FILE))) {
-            mRuleSerializer.serialize(
-                    rules, Optional.empty(), ruleFileOutputStream, indexingFileOutputStream);
-        }
-
-        switchStagingRulesDir();
-
-        // Update object holding the indexing information.
-        updateRuleIndexingController();
-    }
-
-    /**
-     * Read rules from persistent storage.
-     *
-     * @param appInstallMetadata information about the install used to select rules to read. If
-     *     null, all rules will be read.
-     */
-    public List<Rule> readRules(@Nullable AppInstallMetadata appInstallMetadata)
-            throws IOException, RuleParseException {
-        synchronized (RULES_LOCK) {
-            // Try to identify indexes from the index file.
-            List<RuleIndexRange> ruleReadingIndexes = Collections.emptyList();
-            if (appInstallMetadata != null) {
-                try {
-                    ruleReadingIndexes =
-                            mRuleIndexingController.identifyRulesToEvaluate(appInstallMetadata);
-                } catch (Exception e) {
-                    Slog.w(TAG, "Error identifying the rule indexes. Trying unindexed.", e);
-                }
-            }
-
-            // Read the rules based on the index information when available.
-            File ruleFile = new File(mRulesDir, RULES_FILE);
-            List<Rule> rules =
-                    mRuleParser.parse(RandomAccessObject.ofFile(ruleFile), ruleReadingIndexes);
-            return rules;
-        }
-    }
-
-    /** Read the metadata of the current rules in storage. */
-    @Nullable
-    public RuleMetadata readMetadata() {
-        return mRuleMetadataCache;
-    }
-
-    private void switchStagingRulesDir() throws IOException {
-        synchronized (RULES_LOCK) {
-            File tmpDir = new File(mDataDir, "temp");
-
-            if (!(mRulesDir.renameTo(tmpDir)
-                    && mStagingDir.renameTo(mRulesDir)
-                    && tmpDir.renameTo(mStagingDir))) {
-                throw new IOException("Error switching staging/rules directory");
-            }
-
-            for (File file : mStagingDir.listFiles()) {
-                file.delete();
-            }
-        }
-    }
-
-    private void updateRuleIndexingController() {
-        File ruleIndexingFile = new File(mRulesDir, INDEXING_FILE);
-        if (ruleIndexingFile.exists()) {
-            try (FileInputStream inputStream = new FileInputStream(ruleIndexingFile)) {
-                mRuleIndexingController = new RuleIndexingController(inputStream);
-            } catch (Exception e) {
-                Slog.e(TAG, "Error parsing the rule indexing file.", e);
-            }
-        }
-    }
-
-    private void writeMetadata(File directory, String ruleProvider, String version)
-            throws IOException {
-        mRuleMetadataCache = new RuleMetadata(ruleProvider, version);
-
-        File metadataFile = new File(directory, METADATA_FILE);
-
-        try (FileOutputStream outputStream = new FileOutputStream(metadataFile)) {
-            RuleMetadataSerializer.serialize(mRuleMetadataCache, outputStream);
-        }
-    }
-}
diff --git a/services/core/java/com/android/server/location/provider/LocationProviderManager.java b/services/core/java/com/android/server/location/provider/LocationProviderManager.java
index 542a29a..4a9bf88 100644
--- a/services/core/java/com/android/server/location/provider/LocationProviderManager.java
+++ b/services/core/java/com/android/server/location/provider/LocationProviderManager.java
@@ -2584,6 +2584,9 @@
                 registration -> {
                     if (registration.getIdentity().getPackageName().equals(
                             packageName)) {
+                        if (D) {
+                            Log.d(TAG, "package reset remove registration " + registration);
+                        }
                         registration.remove();
                     }
 
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index cae941f..52a2fd6 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -2970,8 +2970,13 @@
                     || context.getPackageManager().hasSystemFeature(
                             PackageManager.FEATURE_WIFI_RTT)) {
                 t.traceBegin("RangingService");
-                mSystemServiceManager.startServiceFromJar(RANGING_SERVICE_CLASS,
-                        RANGING_APEX_SERVICE_JAR_PATH);
+                // TODO: b/375264320 - Remove after RELEASE_RANGING_STACK is ramped to next.
+                try {
+                    mSystemServiceManager.startServiceFromJar(RANGING_SERVICE_CLASS,
+                            RANGING_APEX_SERVICE_JAR_PATH);
+                } catch (Throwable e) {
+                    Slog.d(TAG, "service-ranging.jar not found, not starting RangingService");
+                }
                 t.traceEnd();
             }
         }
diff --git a/services/tests/BackgroundInstallControlServiceTests/host/Android.bp b/services/tests/BackgroundInstallControlServiceTests/host/Android.bp
index 682ed91..8e10136 100644
--- a/services/tests/BackgroundInstallControlServiceTests/host/Android.bp
+++ b/services/tests/BackgroundInstallControlServiceTests/host/Android.bp
@@ -28,7 +28,7 @@
         "compatibility-tradefed",
         "compatibility-host-util",
     ],
-    data: [
+    device_common_data: [
         ":BackgroundInstallControlServiceTestApp",
         ":BackgroundInstallControlMockApp1",
         ":BackgroundInstallControlMockApp2",
diff --git a/services/tests/PackageManagerServiceTests/host/Android.bp b/services/tests/PackageManagerServiceTests/host/Android.bp
index b46a6ff..6ad40f4 100644
--- a/services/tests/PackageManagerServiceTests/host/Android.bp
+++ b/services/tests/PackageManagerServiceTests/host/Android.bp
@@ -44,7 +44,7 @@
         "block_device_writer_jar",
     ],
     test_suites: ["device-tests"],
-    data: [
+    device_common_data: [
         ":PackageManagerTestApex",
         ":PackageManagerTestApexApp",
         ":PackageManagerServiceServerTests",
@@ -53,7 +53,7 @@
         "block_device_writer",
         "fsverity_multilib",
     ],
-    java_resources: [
+    device_common_java_resources: [
         ":PackageManagerTestOverlayActor",
         ":PackageManagerTestOverlay",
         ":PackageManagerTestOverlayTarget",
@@ -73,7 +73,7 @@
     ],
 }
 
-genrule {
+java_genrule {
     name: "PackageManagerTestAppVersion3Invalid",
     tools: [
         "soong_zip",
diff --git a/services/tests/apexsystemservices/Android.bp b/services/tests/apexsystemservices/Android.bp
index 9dacfea..d0a2eb8 100644
--- a/services/tests/apexsystemservices/Android.bp
+++ b/services/tests/apexsystemservices/Android.bp
@@ -27,7 +27,7 @@
     name: "ApexSystemServicesTestCases",
     srcs: ["src/**/*.java"],
     libs: ["tradefed"],
-    java_resources: [
+    device_common_java_resources: [
         ":test_com.android.server",
     ],
     static_libs: [
diff --git a/services/tests/servicestests/src/com/android/server/integrity/IntegrityFileManagerTest.java b/services/tests/servicestests/src/com/android/server/integrity/IntegrityFileManagerTest.java
deleted file mode 100644
index 096c80b..0000000
--- a/services/tests/servicestests/src/com/android/server/integrity/IntegrityFileManagerTest.java
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Copyright (C) 2020 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 com.android.server.integrity.model.IndexingFileConstants.INDEXING_BLOCK_SIZE;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.content.integrity.AppInstallMetadata;
-import android.content.integrity.AtomicFormula;
-import android.content.integrity.AtomicFormula.LongAtomicFormula;
-import android.content.integrity.AtomicFormula.StringAtomicFormula;
-import android.content.integrity.CompoundFormula;
-import android.content.integrity.Rule;
-import android.util.Slog;
-
-import com.android.server.integrity.parser.RuleBinaryParser;
-import com.android.server.integrity.serializer.RuleBinarySerializer;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-import java.io.File;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-
-/** Unit test for {@link IntegrityFileManager} */
-@RunWith(JUnit4.class)
-public class IntegrityFileManagerTest {
-    private static final String TAG = "IntegrityFileManagerTest";
-
-    private static final String VERSION = "version";
-    private static final String RULE_PROVIDER = "rule_provider";
-
-    private File mTmpDir;
-
-    // under test
-    private IntegrityFileManager mIntegrityFileManager;
-
-    @Before
-    public void setUp() throws Exception {
-        mTmpDir = Files.createTempDirectory("IntegrityFileManagerTest").toFile();
-        Slog.i(TAG, "Using temp directory " + mTmpDir);
-
-        // Use Xml Parser/Serializer to help with debugging since we can just print the file.
-        mIntegrityFileManager =
-                new IntegrityFileManager(
-                        new RuleBinaryParser(), new RuleBinarySerializer(), mTmpDir);
-        Files.walk(mTmpDir.toPath())
-                .forEach(
-                        path -> {
-                            Slog.i(TAG, "before " + path);
-                        });
-    }
-
-    @After
-    public void tearDown() throws Exception {
-        Files.walk(mTmpDir.toPath())
-                .forEach(
-                        path -> {
-                            Slog.i(TAG, "after " + path);
-                        });
-        // Sorting paths in reverse order guarantees that we delete inside files before deleting
-        // directory.
-        Files.walk(mTmpDir.toPath())
-                .sorted(Comparator.reverseOrder())
-                .map(Path::toFile)
-                .forEach(File::delete);
-    }
-
-    @Test
-    public void testGetMetadata() throws Exception {
-        assertThat(mIntegrityFileManager.readMetadata()).isNull();
-        mIntegrityFileManager.writeRules(VERSION, RULE_PROVIDER, Collections.EMPTY_LIST);
-
-        assertThat(mIntegrityFileManager.readMetadata()).isNotNull();
-        assertThat(mIntegrityFileManager.readMetadata().getVersion()).isEqualTo(VERSION);
-        assertThat(mIntegrityFileManager.readMetadata().getRuleProvider()).isEqualTo(RULE_PROVIDER);
-    }
-
-    @Test
-    public void testIsInitialized() throws Exception {
-        assertThat(mIntegrityFileManager.initialized()).isFalse();
-        mIntegrityFileManager.writeRules(VERSION, RULE_PROVIDER, Collections.EMPTY_LIST);
-        assertThat(mIntegrityFileManager.initialized()).isTrue();
-    }
-
-    @Test
-    public void testGetRules() throws Exception {
-        String packageName = "package";
-        String packageCert = "cert";
-        int version = 123;
-        Rule packageNameRule = getPackageNameIndexedRule(packageName);
-        Rule packageCertRule = getAppCertificateIndexedRule(packageCert);
-        Rule versionCodeRule =
-                new Rule(
-                        new LongAtomicFormula(
-                                AtomicFormula.VERSION_CODE, AtomicFormula.EQ, version),
-                        Rule.DENY);
-        Rule randomRule =
-                new Rule(
-                        new CompoundFormula(
-                                CompoundFormula.OR,
-                                Arrays.asList(
-                                        new StringAtomicFormula(
-                                                AtomicFormula.PACKAGE_NAME,
-                                                "abc",
-                                                /* isHashedValue= */ false),
-                                        new LongAtomicFormula(
-                                                AtomicFormula.VERSION_CODE,
-                                                AtomicFormula.EQ,
-                                                version))),
-                        Rule.DENY);
-
-        List<Rule> rules =
-                Arrays.asList(packageNameRule, packageCertRule, versionCodeRule, randomRule);
-        mIntegrityFileManager.writeRules(VERSION, RULE_PROVIDER, rules);
-
-        AppInstallMetadata appInstallMetadata =
-                new AppInstallMetadata.Builder()
-                        .setPackageName(packageName)
-                        .setAppCertificates(Collections.singletonList(packageCert))
-                        .setAppCertificateLineage(Collections.singletonList(packageCert))
-                        .setVersionCode(version)
-                        .setInstallerName("abc")
-                        .setInstallerCertificates(Collections.singletonList("abc"))
-                        .setIsPreInstalled(true)
-                        .build();
-        List<Rule> rulesFetched = mIntegrityFileManager.readRules(appInstallMetadata);
-
-        assertThat(rulesFetched)
-                .containsExactly(packageNameRule, packageCertRule, versionCodeRule, randomRule);
-    }
-
-    @Test
-    public void testGetRules_indexedForManyRules() throws Exception {
-        String packageName = "package";
-        String installerName = "installer";
-        String appCertificate = "cert";
-
-        // Create a rule set with 2500 package name indexed, 2500 app certificate indexed and
-        // 500 unindexed rules.
-        List<Rule> rules = new ArrayList<>();
-        int unindexedRuleCount = 70;
-
-        for (int i = 0; i < 2500; i++) {
-            rules.add(getPackageNameIndexedRule(String.format("%s%04d", packageName, i)));
-            rules.add(getAppCertificateIndexedRule(String.format("%s%04d", appCertificate, i)));
-        }
-
-        for (int i = 0; i < unindexedRuleCount; i++) {
-            rules.add(getInstallerCertificateRule(String.format("%s%04d", installerName, i)));
-        }
-
-        // Write the rules and get them indexed.
-        mIntegrityFileManager.writeRules(VERSION, RULE_PROVIDER, rules);
-
-        // Read the rules for a specific rule.
-        String installedPackageName = String.format("%s%04d", packageName, 264);
-        String installedAppCertificate = String.format("%s%04d", appCertificate, 1264);
-        AppInstallMetadata appInstallMetadata =
-                new AppInstallMetadata.Builder()
-                        .setPackageName(installedPackageName)
-                        .setAppCertificates(Collections.singletonList(installedAppCertificate))
-                        .setAppCertificateLineage(
-                                Collections.singletonList(installedAppCertificate))
-                        .setVersionCode(250)
-                        .setInstallerName("abc")
-                        .setInstallerCertificates(Collections.singletonList("abc"))
-                        .setIsPreInstalled(true)
-                        .build();
-        List<Rule> rulesFetched = mIntegrityFileManager.readRules(appInstallMetadata);
-
-        // Verify that we do not load all the rules and we have the necessary rules to evaluate.
-        assertThat(rulesFetched.size())
-                .isEqualTo(INDEXING_BLOCK_SIZE * 2 + unindexedRuleCount);
-        assertThat(rulesFetched)
-                .containsAtLeast(
-                        getPackageNameIndexedRule(installedPackageName),
-                        getAppCertificateIndexedRule(installedAppCertificate));
-    }
-
-    private Rule getPackageNameIndexedRule(String packageName) {
-        return new Rule(
-                new StringAtomicFormula(
-                        AtomicFormula.PACKAGE_NAME, packageName, /* isHashedValue= */false),
-                Rule.DENY);
-    }
-
-    private Rule getAppCertificateIndexedRule(String appCertificate) {
-        return new Rule(
-                new StringAtomicFormula(
-                        AtomicFormula.APP_CERTIFICATE,
-                        appCertificate, /* isHashedValue= */ false),
-                Rule.DENY);
-    }
-
-    private Rule getInstallerCertificateRule(String installerCert) {
-        return new Rule(
-                new StringAtomicFormula(
-                        AtomicFormula.INSTALLER_NAME, installerCert, /* isHashedValue= */false),
-                Rule.DENY);
-    }
-
-    @Test
-    public void testStagingDirectoryCleared() throws Exception {
-        // We must push rules two times to ensure that staging directory is empty because we cleared
-        // it, rather than because original rules directory is empty.
-        mIntegrityFileManager.writeRules(VERSION, RULE_PROVIDER, Collections.EMPTY_LIST);
-        mIntegrityFileManager.writeRules(VERSION, RULE_PROVIDER, Collections.EMPTY_LIST);
-
-        assertStagingDirectoryCleared();
-    }
-
-    private void assertStagingDirectoryCleared() {
-        File stagingDir = new File(mTmpDir, "integrity_staging");
-        assertThat(stagingDir.exists()).isTrue();
-        assertThat(stagingDir.isDirectory()).isTrue();
-        assertThat(stagingDir.listFiles()).isEmpty();
-    }
-}
diff --git a/services/tests/servicestests/src/com/android/server/security/advancedprotection/OWNERS b/services/tests/servicestests/src/com/android/server/security/advancedprotection/OWNERS
new file mode 100644
index 0000000..9bf5e58
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/security/advancedprotection/OWNERS
@@ -0,0 +1 @@
+file:platform/frameworks/base:main:/core/java/android/security/advancedprotection/OWNERS
diff --git a/services/tests/wmtests/Android.bp b/services/tests/wmtests/Android.bp
index 76ff231..d99a6e9 100644
--- a/services/tests/wmtests/Android.bp
+++ b/services/tests/wmtests/Android.bp
@@ -19,7 +19,7 @@
     ],
 }
 
-genrule {
+java_genrule {
     name: "wmtests.protologsrc",
     srcs: [
         ":protolog-impl",
diff --git a/tests/BinaryTransparencyHostTest/Android.bp b/tests/BinaryTransparencyHostTest/Android.bp
index 38cb9869..e14e5fe 100644
--- a/tests/BinaryTransparencyHostTest/Android.bp
+++ b/tests/BinaryTransparencyHostTest/Android.bp
@@ -32,7 +32,7 @@
     static_libs: [
         "truth",
     ],
-    data: [
+    device_common_data: [
         ":BinaryTransparencyTestApp",
         ":EasterEgg",
         ":FeatureSplitBase",
diff --git a/tests/CompanionDeviceMultiDeviceTests/host/Android.bp b/tests/CompanionDeviceMultiDeviceTests/host/Android.bp
index 37cb850..a0e0477 100644
--- a/tests/CompanionDeviceMultiDeviceTests/host/Android.bp
+++ b/tests/CompanionDeviceMultiDeviceTests/host/Android.bp
@@ -36,7 +36,7 @@
         unit_test: false,
         tags: ["mobly"],
     },
-    data: [
+    device_common_data: [
         ":cdm_snippet_legacy",
     ],
     version: {
diff --git a/tests/DynamicCodeLoggerIntegrationTests/Android.bp b/tests/DynamicCodeLoggerIntegrationTests/Android.bp
index 3f2c808..45bbcb4 100644
--- a/tests/DynamicCodeLoggerIntegrationTests/Android.bp
+++ b/tests/DynamicCodeLoggerIntegrationTests/Android.bp
@@ -55,6 +55,8 @@
 
     java_resources: [
         ":DynamicCodeLoggerTestLibrary",
+    ],
+    device_first_java_resources: [
         ":DynamicCodeLoggerNativeExecutable",
     ],
 }
diff --git a/tests/FsVerityTest/Android.bp b/tests/FsVerityTest/Android.bp
index 02268c3..c2dfa0f 100644
--- a/tests/FsVerityTest/Android.bp
+++ b/tests/FsVerityTest/Android.bp
@@ -43,7 +43,7 @@
     data_device_bins_both: [
         "block_device_writer",
     ],
-    data: [
+    device_common_data: [
         ":FsVerityTestApp",
     ],
 }
diff --git a/tests/OdmApps/Android.bp b/tests/OdmApps/Android.bp
index a5c6d65..9f32d46 100644
--- a/tests/OdmApps/Android.bp
+++ b/tests/OdmApps/Android.bp
@@ -26,7 +26,7 @@
     srcs: ["src/**/*.java"],
     libs: ["tradefed"],
     test_suites: ["device-tests"],
-    data: [
+    device_common_data: [
         ":TestOdmApp",
         ":TestOdmPrivApp",
     ],
diff --git a/tests/RollbackTest/Android.bp b/tests/RollbackTest/Android.bp
index 21007ef..766ff4a 100644
--- a/tests/RollbackTest/Android.bp
+++ b/tests/RollbackTest/Android.bp
@@ -26,7 +26,11 @@
     manifest: "RollbackTest/AndroidManifest.xml",
     platform_apis: true,
     srcs: ["RollbackTest/src/**/*.java"],
-    static_libs: ["androidx.test.rules", "cts-rollback-lib", "cts-install-lib"],
+    static_libs: [
+        "androidx.test.rules",
+        "cts-rollback-lib",
+        "cts-install-lib",
+    ],
     test_suites: ["general-tests"],
     test_config: "RollbackTest.xml",
     java_resources: [
@@ -48,7 +52,7 @@
     ],
     test_suites: ["general-tests"],
     test_config: "StagedRollbackTest.xml",
-    data: [
+    device_common_data: [
         ":com.android.apex.apkrollback.test_v1",
         ":test.rebootless_apex_v1",
         ":RollbackTest",
@@ -59,10 +63,13 @@
     name: "NetworkStagedRollbackTest",
     srcs: ["NetworkStagedRollbackTest/src/**/*.java"],
     libs: ["tradefed"],
-    static_libs: ["RollbackTestLib", "frameworks-base-hostutils"],
+    static_libs: [
+        "RollbackTestLib",
+        "frameworks-base-hostutils",
+    ],
     test_suites: ["general-tests"],
     test_config: "NetworkStagedRollbackTest.xml",
-    data: [":RollbackTest"],
+    device_common_data: [":RollbackTest"],
 }
 
 java_test_host {
@@ -74,7 +81,7 @@
     ],
     test_suites: ["general-tests"],
     test_config: "MultiUserRollbackTest.xml",
-    data : [":RollbackTest"],
+    device_common_data: [":RollbackTest"],
 }
 
 java_library_host {
@@ -84,55 +91,55 @@
 }
 
 genrule {
-  name: "com.android.apex.apkrollback.test.pem",
-  out: ["com.android.apex.apkrollback.test.pem"],
-  cmd: "openssl genrsa -out $(out) 4096",
+    name: "com.android.apex.apkrollback.test.pem",
+    out: ["com.android.apex.apkrollback.test.pem"],
+    cmd: "openssl genrsa -out $(out) 4096",
 }
 
 genrule {
-  name: "com.android.apex.apkrollback.test.pubkey",
-  srcs: [":com.android.apex.apkrollback.test.pem"],
-  out: ["com.android.apex.apkrollback.test.pubkey"],
-  tools: ["avbtool"],
-  cmd: "$(location avbtool) extract_public_key --key $(in) --output $(out)",
+    name: "com.android.apex.apkrollback.test.pubkey",
+    srcs: [":com.android.apex.apkrollback.test.pem"],
+    out: ["com.android.apex.apkrollback.test.pubkey"],
+    tools: ["avbtool"],
+    cmd: "$(location avbtool) extract_public_key --key $(in) --output $(out)",
 }
 
 apex_key {
-  name: "com.android.apex.apkrollback.test.key",
-  private_key: ":com.android.apex.apkrollback.test.pem",
-  public_key: ":com.android.apex.apkrollback.test.pubkey",
-  installable: false,
+    name: "com.android.apex.apkrollback.test.key",
+    private_key: ":com.android.apex.apkrollback.test.pem",
+    public_key: ":com.android.apex.apkrollback.test.pubkey",
+    installable: false,
 }
 
 apex {
-  name: "com.android.apex.apkrollback.test_v1",
-  manifest: "testdata/manifest_v1.json",
-  androidManifest: "testdata/AndroidManifest.xml",
-  file_contexts: ":apex.test-file_contexts",
-  key: "com.android.apex.apkrollback.test.key",
-  apps: ["TestAppAv1"],
-  installable: false,
-  updatable: false,
+    name: "com.android.apex.apkrollback.test_v1",
+    manifest: "testdata/manifest_v1.json",
+    androidManifest: "testdata/AndroidManifest.xml",
+    file_contexts: ":apex.test-file_contexts",
+    key: "com.android.apex.apkrollback.test.key",
+    apps: ["TestAppAv1"],
+    installable: false,
+    updatable: false,
 }
 
 apex {
-  name: "com.android.apex.apkrollback.test_v2",
-  manifest: "testdata/manifest_v2.json",
-  androidManifest: "testdata/AndroidManifest.xml",
-  file_contexts: ":apex.test-file_contexts",
-  key: "com.android.apex.apkrollback.test.key",
-  apps: ["TestAppAv2"],
-  installable: false,
-  updatable: false,
+    name: "com.android.apex.apkrollback.test_v2",
+    manifest: "testdata/manifest_v2.json",
+    androidManifest: "testdata/AndroidManifest.xml",
+    file_contexts: ":apex.test-file_contexts",
+    key: "com.android.apex.apkrollback.test.key",
+    apps: ["TestAppAv2"],
+    installable: false,
+    updatable: false,
 }
 
 apex {
-  name: "com.android.apex.apkrollback.test_v2Crashing",
-  manifest: "testdata/manifest_v2.json",
-  androidManifest: "testdata/AndroidManifest.xml",
-  file_contexts: ":apex.test-file_contexts",
-  key: "com.android.apex.apkrollback.test.key",
-  apps: ["TestAppACrashingV2"],
-  installable: false,
-  updatable: false,
+    name: "com.android.apex.apkrollback.test_v2Crashing",
+    manifest: "testdata/manifest_v2.json",
+    androidManifest: "testdata/AndroidManifest.xml",
+    file_contexts: ":apex.test-file_contexts",
+    key: "com.android.apex.apkrollback.test.key",
+    apps: ["TestAppACrashingV2"],
+    installable: false,
+    updatable: false,
 }
diff --git a/tests/SharedLibraryLoadingTest/Android.bp b/tests/SharedLibraryLoadingTest/Android.bp
index 088278d..8027519 100644
--- a/tests/SharedLibraryLoadingTest/Android.bp
+++ b/tests/SharedLibraryLoadingTest/Android.bp
@@ -28,7 +28,7 @@
         "junit",
     ],
     test_suites: ["general-tests"],
-    data: [
+    device_common_data: [
         ":SharedLibraryLoadingTests_StandardSharedLibrary",
         ":SharedLibraryLoadingTests_SharedLibraryLoadedAfter",
         ":SharedLibraryLoadingTests_SharedLibraryClientTests",
diff --git a/tests/StagedInstallTest/Android.bp b/tests/StagedInstallTest/Android.bp
index 2751141..451870e 100644
--- a/tests/StagedInstallTest/Android.bp
+++ b/tests/StagedInstallTest/Android.bp
@@ -55,7 +55,7 @@
         "frameworks-base-hostutils",
         "cts-install-lib-host",
     ],
-    data: [
+    device_common_data: [
         ":StagedInstallInternalTestApp",
         ":apex.apexd_test",
         ":com.android.apex.apkrollback.test_v1",
diff --git a/tests/SystemMemoryTest/host/Android.bp b/tests/SystemMemoryTest/host/Android.bp
index cc8bc45..1535697 100644
--- a/tests/SystemMemoryTest/host/Android.bp
+++ b/tests/SystemMemoryTest/host/Android.bp
@@ -26,7 +26,7 @@
     srcs: ["src/**/*.java"],
     libs: ["tradefed"],
     test_suites: ["general-tests"],
-    data: [
+    device_common_data: [
         ":SystemMemoryTestDevice",
     ],
 }
diff --git a/tools/lint/global/integration_tests/Android.bp b/tools/lint/global/integration_tests/Android.bp
index 40281d2..05ba405 100644
--- a/tools/lint/global/integration_tests/Android.bp
+++ b/tools/lint/global/integration_tests/Android.bp
@@ -38,7 +38,7 @@
 
 python_library_host {
     name: "AndroidGlobalLintTestNoAidl_py",
-    data: [":AndroidGlobalLintTestNoAidl{.lint}"],
+    device_common_data: [":AndroidGlobalLintTestNoAidl{.lint}"],
     pkg_path: "no_aidl",
 }
 
@@ -53,7 +53,7 @@
 
 python_library_host {
     name: "AndroidGlobalLintTestMissingAnnotation_py",
-    data: [":AndroidGlobalLintTestMissingAnnotation{.lint}"],
+    device_common_data: [":AndroidGlobalLintTestMissingAnnotation{.lint}"],
     pkg_path: "missing_annotation",
 }
 
diff --git a/tools/preload-check/Android.bp b/tools/preload-check/Android.bp
index 73caac6..24ec12c 100644
--- a/tools/preload-check/Android.bp
+++ b/tools/preload-check/Android.bp
@@ -28,5 +28,5 @@
     libs: ["tradefed"],
     test_suites: ["general-tests"],
     required: ["preload-check-device"],
-    data: [":preload-check-device"],
+    device_common_data: [":preload-check-device"],
 }