Import 18th Mar 2025 ToT Cronet from Chromium to AOSP

Generated by Copybara via Chromium's ci/android-cronet-arm64-gn2bp-dbg:
https://ci.chromium.org/ui/p/chromium/builders/ci/android-cronet-arm64-gn2bp-dbg/7609/overview.
Then updated to include a cherry-pick of
https://chromium-review.googlesource.com/c/chromium/src/+/6383356.

These can also be seen from the branch representing this import:
https://chromium.googlesource.com/experimental/chromium/src/+/refs/wip/cronet/aosp-tot_import_mar_18_25.
With commit SHA: 3e3cc0341bdf13d1c6593a9f206eaf7f13c463e1.

This commit can be reproduced by running:
$ gclient config --spec 'solutions = [
  {
    "name": "src",
    "url":
"https://chromium.googlesource.com/experimental/chromium/src.git",
    "managed": False,
    "custom_deps": {},
    "custom_vars": {
      "checkout_copybara": True,
    },
  },
]
target_os = ["android"]
' &&
gclient sync --rev=refs/wip/cronet/aosp-tot_import_mar_18_25 --shallow &&
cd src &&
vpython3 components/cronet/gn2bp/run_gn2bp.py

Additionally, manual tweaks have been applied after patchset 1. These
are required to:
1. Fix naming in non-versioned/templated top-level Android.bp
2. Resolve merge conflicts
3. Update consistency files with changes (1) and (2)

Bug: b:403544010
FolderOrigin-RevId: /b/s/w/ir/cache/builder/src
Change-Id: I15308a1c82a99a6d850bfb0ed37dbbf91439b9ea
diff --git a/Android.bp b/Android.bp
index 7a706c5..7951779 100644
--- a/Android.bp
+++ b/Android.bp
@@ -79,7 +79,7 @@
         enable_cronet_tot: {
             static_libs: [
                 "tot_cronet_components_cronet_android_cronet_impl_native_java",
-                "tot_cronet_components_cronet_android_cronet_jni_registration_java",
+                "tot_cronet_components_cronet_android_cronet_build_config_and_jni_registration_java",
             ],
             conditions_default: {
                 static_libs: [
@@ -97,7 +97,7 @@
         enable_cronet_tot: {
             static_libs: [
                 "tot_cronet_components_cronet_android_cronet_impl_native_java__testing",
-                "tot_cronet_components_cronet_android_cronet_jni_registration_java__testing",
+                "tot_cronet_components_cronet_android_cronet_build_config_and_jni_registration_java__testing",
                 "tot_cronet_components_cronet_android_cronet_tests_jni_registration_java__testing",
             ],
             conditions_default: {
diff --git a/tot/Android.bp b/tot/Android.bp
index a567290..2b733bb 100644
--- a/tot/Android.bp
+++ b/tot/Android.bp
@@ -40,15 +40,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -61,15 +59,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -82,15 +78,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -103,15 +97,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -124,15 +116,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -173,15 +163,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -193,15 +181,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -213,15 +199,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -233,15 +217,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -253,15 +235,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -274,15 +254,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=no",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -325,15 +303,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -345,15 +321,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -365,15 +339,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -385,15 +357,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -405,15 +375,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -426,15 +394,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=no",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -476,15 +442,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -496,15 +460,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -516,15 +478,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -536,15 +496,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -556,15 +514,13 @@
             edition: "2021",
             cfgs: [
                 "cpp",
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -602,15 +558,13 @@
         android_arm: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -621,15 +575,13 @@
         android_arm64: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -640,15 +592,13 @@
         android_riscv64: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -659,15 +609,13 @@
         android_x86: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -678,15 +626,13 @@
         android_x86_64: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -724,15 +670,13 @@
         android_arm: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -743,15 +687,13 @@
         android_arm64: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -762,15 +704,13 @@
         android_riscv64: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -781,15 +721,13 @@
         android_x86: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -800,15 +738,13 @@
         android_x86_64: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -822,12 +758,78 @@
     },
 }
 
+// GN: //base:activity_state_java__process_device
+java_genrule {
+    name: "tot_cronet_base_activity_state_java__process_device",
+    srcs: [
+        ":tot_cronet_base_activity_state_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/activity_state_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:activity_state_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_activity_state_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_activity_state_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/activity_state_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base/allocator:buildflags
 cc_genrule {
     name: "tot_cronet_base_allocator_buildflags",
-    cmd: "mkdir -p $(genDir)/base/allocator && echo '--flags USE_PARTITION_ALLOC_AS_GWP_ASAN_STORE=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base/allocator &&  " +
+         "echo '--flags USE_PARTITION_ALLOC_AS_GWP_ASAN_STORE=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator:buildflags " +
          "--gen-dir " +
@@ -852,9 +854,11 @@
 // GN: //base/allocator:buildflags__testing
 cc_genrule {
     name: "tot_cronet_base_allocator_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/base/allocator && echo '--flags USE_PARTITION_ALLOC_AS_GWP_ASAN_STORE=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base/allocator &&  " +
+         "echo '--flags USE_PARTITION_ALLOC_AS_GWP_ASAN_STORE=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator:buildflags " +
          "--gen-dir " +
@@ -882,64 +886,74 @@
     name: "tot_cronet_base_allocator_partition_allocator_src_partition_alloc_buildflags",
     cmd: "if [[ ( $$CC_ARCH == 'arm' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc && echo '--flags ASSERT_CPP_20=\"true\" BACKUP_REF_PTR_EXTRA_OOB_CHECKS=\"false\" BACKUP_REF_PTR_POISON_OOB_PTR=\"false\" ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=\"false\" ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=\"false\" ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=\"false\" ENABLE_BACKUP_REF_PTR_SUPPORT=\"false\" ENABLE_DANGLING_RAW_PTR_CHECKS=\"false\" ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=\"false\" ENABLE_GWP_ASAN_SUPPORT=\"false\" ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=\"false\" ENABLE_PKEYS=\"false\" ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=\"true\" ENABLE_POINTER_COMPRESSION=\"false\" ENABLE_POINTER_SUBTRACTION_CHECK=\"false\" ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=\"false\" ENABLE_THREAD_ISOLATION=\"false\" FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=\"false\" FORCE_ENABLE_RAW_PTR_EXCLUSION=\"false\" FORWARD_THROUGH_MALLOC=\"false\" HAS_64_BIT_POINTERS=\"false\" HAS_MEMORY_TAGGING=\"false\" IS_ANDROID=\"true\" IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" IS_CHROMEOS=\"false\" IS_DEBUG=\"false\" RAW_PTR_ZERO_ON_CONSTRUCT=\"true\" RAW_PTR_ZERO_ON_DESTRUCT=\"false\" RAW_PTR_ZERO_ON_MOVE=\"true\" RECORD_ALLOC_INFO=\"false\" SMALLER_PARTITION_COOKIE=\"false\" STACK_SCAN_SUPPORTED=\"true\" USE_ALLOCATOR_SHIM=\"false\" USE_ASAN_BACKUP_REF_PTR=\"false\" USE_FREELIST_DISPATCHER=\"false\" USE_FREESLOT_BITMAP=\"false\" USE_FULL_MTE=\"false\" USE_LARGE_EMPTY_SLOT_SPAN_RING=\"true\" USE_PARTITION_ALLOC=\"false\" USE_PARTITION_ALLOC_AS_MALLOC=\"false\" USE_PARTITION_COOKIE=\"false\" USE_RAW_PTR_ASAN_UNOWNED_IMPL=\"false\" USE_RAW_PTR_BACKUP_REF_IMPL=\"false\" USE_RAW_PTR_HOOKABLE_IMPL=\"false\" ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=\"false\" DCHECKS_ARE_ON=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" DCHECK_IS_CONFIGURABLE=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"false\"' | " +
-         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc &&  " +
+         "echo '--flags ASSERT_CPP_20=true BACKUP_REF_PTR_EXTRA_OOB_CHECKS=false BACKUP_REF_PTR_POISON_OOB_PTR=false CAN_UNWIND_WITH_FRAME_POINTERS=false DCHECKS_ARE_ON=false DCHECK_IS_CONFIGURABLE=false ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=false ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=false ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=false ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=false ENABLE_BACKUP_REF_PTR_SUPPORT=false ENABLE_DANGLING_RAW_PTR_CHECKS=false ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=false ENABLE_GWP_ASAN_SUPPORT=false ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=false ENABLE_PKEYS=false ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=true ENABLE_POINTER_COMPRESSION=false ENABLE_POINTER_SUBTRACTION_CHECK=false ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=false ENABLE_THREAD_ISOLATION=false EXPENSIVE_DCHECKS_ARE_ON=false FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=false FORCE_ENABLE_RAW_PTR_EXCLUSION=false FORWARD_THROUGH_MALLOC=false HAS_64_BIT_POINTERS=false HAS_MEMORY_TAGGING=false IS_ANDROID=true IS_CASTOS=false IS_CAST_ANDROID=false IS_CHROMEOS=false IS_DEBUG=false RAW_PTR_ZERO_ON_CONSTRUCT=true RAW_PTR_ZERO_ON_DESTRUCT=false RAW_PTR_ZERO_ON_MOVE=true REALLOC_GROWTH_FACTOR_MITIGATION=false RECORD_ALLOC_INFO=false SMALLER_PARTITION_COOKIE=false STACK_SCAN_SUPPORTED=true USE_ALLOCATOR_SHIM=false USE_ASAN_BACKUP_REF_PTR=false USE_FREELIST_DISPATCHER=false USE_FREESLOT_BITMAP=false USE_FULL_MTE=false USE_LARGE_EMPTY_SLOT_SPAN_RING=true USE_PARTITION_ALLOC=false USE_PARTITION_ALLOC_AS_MALLOC=false USE_PARTITION_COOKIE=false USE_RAW_PTR_ASAN_UNOWNED_IMPL=false USE_RAW_PTR_BACKUP_REF_IMPL=false USE_RAW_PTR_HOOKABLE_IMPL=false' | " +
+         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator/partition_allocator/src/partition_alloc:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'arm64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc && echo '--flags ASSERT_CPP_20=\"true\" BACKUP_REF_PTR_EXTRA_OOB_CHECKS=\"false\" BACKUP_REF_PTR_POISON_OOB_PTR=\"false\" ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=\"false\" ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=\"false\" ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=\"false\" ENABLE_BACKUP_REF_PTR_SUPPORT=\"false\" ENABLE_DANGLING_RAW_PTR_CHECKS=\"false\" ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=\"false\" ENABLE_GWP_ASAN_SUPPORT=\"false\" ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=\"false\" ENABLE_PKEYS=\"false\" ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=\"true\" ENABLE_POINTER_COMPRESSION=\"false\" ENABLE_POINTER_SUBTRACTION_CHECK=\"false\" ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=\"false\" ENABLE_THREAD_ISOLATION=\"false\" FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=\"false\" FORCE_ENABLE_RAW_PTR_EXCLUSION=\"false\" FORWARD_THROUGH_MALLOC=\"false\" HAS_64_BIT_POINTERS=\"true\" HAS_MEMORY_TAGGING=\"true\" IS_ANDROID=\"true\" IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" IS_CHROMEOS=\"false\" IS_DEBUG=\"false\" RAW_PTR_ZERO_ON_CONSTRUCT=\"true\" RAW_PTR_ZERO_ON_DESTRUCT=\"false\" RAW_PTR_ZERO_ON_MOVE=\"true\" RECORD_ALLOC_INFO=\"false\" SMALLER_PARTITION_COOKIE=\"false\" STACK_SCAN_SUPPORTED=\"true\" USE_ALLOCATOR_SHIM=\"false\" USE_ASAN_BACKUP_REF_PTR=\"false\" USE_FREELIST_DISPATCHER=\"true\" USE_FREESLOT_BITMAP=\"false\" USE_FULL_MTE=\"false\" USE_LARGE_EMPTY_SLOT_SPAN_RING=\"true\" USE_PARTITION_ALLOC=\"false\" USE_PARTITION_ALLOC_AS_MALLOC=\"false\" USE_PARTITION_COOKIE=\"false\" USE_RAW_PTR_ASAN_UNOWNED_IMPL=\"false\" USE_RAW_PTR_BACKUP_REF_IMPL=\"false\" USE_RAW_PTR_HOOKABLE_IMPL=\"false\" ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=\"false\" DCHECKS_ARE_ON=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" DCHECK_IS_CONFIGURABLE=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"true\"' | " +
-         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc &&  " +
+         "echo '--flags ASSERT_CPP_20=true BACKUP_REF_PTR_EXTRA_OOB_CHECKS=false BACKUP_REF_PTR_POISON_OOB_PTR=false CAN_UNWIND_WITH_FRAME_POINTERS=true DCHECKS_ARE_ON=false DCHECK_IS_CONFIGURABLE=false ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=false ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=false ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=false ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=false ENABLE_BACKUP_REF_PTR_SUPPORT=false ENABLE_DANGLING_RAW_PTR_CHECKS=false ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=false ENABLE_GWP_ASAN_SUPPORT=false ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=false ENABLE_PKEYS=false ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=true ENABLE_POINTER_COMPRESSION=false ENABLE_POINTER_SUBTRACTION_CHECK=false ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=false ENABLE_THREAD_ISOLATION=false EXPENSIVE_DCHECKS_ARE_ON=false FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=false FORCE_ENABLE_RAW_PTR_EXCLUSION=false FORWARD_THROUGH_MALLOC=false HAS_64_BIT_POINTERS=true HAS_MEMORY_TAGGING=true IS_ANDROID=true IS_CASTOS=false IS_CAST_ANDROID=false IS_CHROMEOS=false IS_DEBUG=false RAW_PTR_ZERO_ON_CONSTRUCT=true RAW_PTR_ZERO_ON_DESTRUCT=false RAW_PTR_ZERO_ON_MOVE=true REALLOC_GROWTH_FACTOR_MITIGATION=false RECORD_ALLOC_INFO=false SMALLER_PARTITION_COOKIE=false STACK_SCAN_SUPPORTED=true USE_ALLOCATOR_SHIM=false USE_ASAN_BACKUP_REF_PTR=false USE_FREELIST_DISPATCHER=true USE_FREESLOT_BITMAP=false USE_FULL_MTE=false USE_LARGE_EMPTY_SLOT_SPAN_RING=true USE_PARTITION_ALLOC=false USE_PARTITION_ALLOC_AS_MALLOC=false USE_PARTITION_COOKIE=false USE_RAW_PTR_ASAN_UNOWNED_IMPL=false USE_RAW_PTR_BACKUP_REF_IMPL=false USE_RAW_PTR_HOOKABLE_IMPL=false' | " +
+         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator/partition_allocator/src/partition_alloc:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'riscv64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc && echo '--flags ASSERT_CPP_20=\"true\" BACKUP_REF_PTR_EXTRA_OOB_CHECKS=\"false\" BACKUP_REF_PTR_POISON_OOB_PTR=\"false\" ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=\"false\" ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=\"false\" ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=\"false\" ENABLE_BACKUP_REF_PTR_SUPPORT=\"false\" ENABLE_DANGLING_RAW_PTR_CHECKS=\"false\" ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=\"false\" ENABLE_GWP_ASAN_SUPPORT=\"false\" ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=\"false\" ENABLE_PKEYS=\"false\" ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=\"true\" ENABLE_POINTER_COMPRESSION=\"false\" ENABLE_POINTER_SUBTRACTION_CHECK=\"false\" ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=\"false\" ENABLE_THREAD_ISOLATION=\"false\" FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=\"false\" FORCE_ENABLE_RAW_PTR_EXCLUSION=\"false\" FORWARD_THROUGH_MALLOC=\"false\" HAS_64_BIT_POINTERS=\"true\" HAS_MEMORY_TAGGING=\"false\" IS_ANDROID=\"true\" IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" IS_CHROMEOS=\"false\" IS_DEBUG=\"false\" RAW_PTR_ZERO_ON_CONSTRUCT=\"true\" RAW_PTR_ZERO_ON_DESTRUCT=\"false\" RAW_PTR_ZERO_ON_MOVE=\"true\" RECORD_ALLOC_INFO=\"false\" SMALLER_PARTITION_COOKIE=\"false\" STACK_SCAN_SUPPORTED=\"true\" USE_ALLOCATOR_SHIM=\"false\" USE_ASAN_BACKUP_REF_PTR=\"false\" USE_FREELIST_DISPATCHER=\"true\" USE_FREESLOT_BITMAP=\"false\" USE_FULL_MTE=\"false\" USE_LARGE_EMPTY_SLOT_SPAN_RING=\"true\" USE_PARTITION_ALLOC=\"false\" USE_PARTITION_ALLOC_AS_MALLOC=\"false\" USE_PARTITION_COOKIE=\"false\" USE_RAW_PTR_ASAN_UNOWNED_IMPL=\"false\" USE_RAW_PTR_BACKUP_REF_IMPL=\"false\" USE_RAW_PTR_HOOKABLE_IMPL=\"false\" ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=\"false\" DCHECKS_ARE_ON=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" DCHECK_IS_CONFIGURABLE=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"false\"' | " +
-         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc &&  " +
+         "echo '--flags ASSERT_CPP_20=true BACKUP_REF_PTR_EXTRA_OOB_CHECKS=false BACKUP_REF_PTR_POISON_OOB_PTR=false CAN_UNWIND_WITH_FRAME_POINTERS=false DCHECKS_ARE_ON=false DCHECK_IS_CONFIGURABLE=false ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=false ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=false ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=false ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=false ENABLE_BACKUP_REF_PTR_SUPPORT=false ENABLE_DANGLING_RAW_PTR_CHECKS=false ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=false ENABLE_GWP_ASAN_SUPPORT=false ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=false ENABLE_PKEYS=false ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=true ENABLE_POINTER_COMPRESSION=false ENABLE_POINTER_SUBTRACTION_CHECK=false ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=false ENABLE_THREAD_ISOLATION=false EXPENSIVE_DCHECKS_ARE_ON=false FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=false FORCE_ENABLE_RAW_PTR_EXCLUSION=false FORWARD_THROUGH_MALLOC=false HAS_64_BIT_POINTERS=true HAS_MEMORY_TAGGING=false IS_ANDROID=true IS_CASTOS=false IS_CAST_ANDROID=false IS_CHROMEOS=false IS_DEBUG=false RAW_PTR_ZERO_ON_CONSTRUCT=true RAW_PTR_ZERO_ON_DESTRUCT=false RAW_PTR_ZERO_ON_MOVE=true REALLOC_GROWTH_FACTOR_MITIGATION=false RECORD_ALLOC_INFO=false SMALLER_PARTITION_COOKIE=false STACK_SCAN_SUPPORTED=true USE_ALLOCATOR_SHIM=false USE_ASAN_BACKUP_REF_PTR=false USE_FREELIST_DISPATCHER=true USE_FREESLOT_BITMAP=false USE_FULL_MTE=false USE_LARGE_EMPTY_SLOT_SPAN_RING=true USE_PARTITION_ALLOC=false USE_PARTITION_ALLOC_AS_MALLOC=false USE_PARTITION_COOKIE=false USE_RAW_PTR_ASAN_UNOWNED_IMPL=false USE_RAW_PTR_BACKUP_REF_IMPL=false USE_RAW_PTR_HOOKABLE_IMPL=false' | " +
+         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator/partition_allocator/src/partition_alloc:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc && echo '--flags ASSERT_CPP_20=\"true\" BACKUP_REF_PTR_EXTRA_OOB_CHECKS=\"false\" BACKUP_REF_PTR_POISON_OOB_PTR=\"false\" ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=\"false\" ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=\"false\" ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=\"false\" ENABLE_BACKUP_REF_PTR_SUPPORT=\"false\" ENABLE_DANGLING_RAW_PTR_CHECKS=\"false\" ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=\"false\" ENABLE_GWP_ASAN_SUPPORT=\"false\" ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=\"false\" ENABLE_PKEYS=\"false\" ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=\"true\" ENABLE_POINTER_COMPRESSION=\"false\" ENABLE_POINTER_SUBTRACTION_CHECK=\"false\" ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=\"false\" ENABLE_THREAD_ISOLATION=\"false\" FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=\"false\" FORCE_ENABLE_RAW_PTR_EXCLUSION=\"false\" FORWARD_THROUGH_MALLOC=\"false\" HAS_64_BIT_POINTERS=\"false\" HAS_MEMORY_TAGGING=\"false\" IS_ANDROID=\"true\" IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" IS_CHROMEOS=\"false\" IS_DEBUG=\"false\" RAW_PTR_ZERO_ON_CONSTRUCT=\"true\" RAW_PTR_ZERO_ON_DESTRUCT=\"false\" RAW_PTR_ZERO_ON_MOVE=\"true\" RECORD_ALLOC_INFO=\"false\" SMALLER_PARTITION_COOKIE=\"false\" STACK_SCAN_SUPPORTED=\"true\" USE_ALLOCATOR_SHIM=\"false\" USE_ASAN_BACKUP_REF_PTR=\"false\" USE_FREELIST_DISPATCHER=\"false\" USE_FREESLOT_BITMAP=\"false\" USE_FULL_MTE=\"false\" USE_LARGE_EMPTY_SLOT_SPAN_RING=\"true\" USE_PARTITION_ALLOC=\"false\" USE_PARTITION_ALLOC_AS_MALLOC=\"false\" USE_PARTITION_COOKIE=\"false\" USE_RAW_PTR_ASAN_UNOWNED_IMPL=\"false\" USE_RAW_PTR_BACKUP_REF_IMPL=\"false\" USE_RAW_PTR_HOOKABLE_IMPL=\"false\" ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=\"false\" DCHECKS_ARE_ON=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" DCHECK_IS_CONFIGURABLE=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"true\"' | " +
-         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc &&  " +
+         "echo '--flags ASSERT_CPP_20=true BACKUP_REF_PTR_EXTRA_OOB_CHECKS=false BACKUP_REF_PTR_POISON_OOB_PTR=false CAN_UNWIND_WITH_FRAME_POINTERS=true DCHECKS_ARE_ON=false DCHECK_IS_CONFIGURABLE=false ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=false ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=false ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=false ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=false ENABLE_BACKUP_REF_PTR_SUPPORT=false ENABLE_DANGLING_RAW_PTR_CHECKS=false ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=false ENABLE_GWP_ASAN_SUPPORT=false ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=false ENABLE_PKEYS=false ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=true ENABLE_POINTER_COMPRESSION=false ENABLE_POINTER_SUBTRACTION_CHECK=false ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=false ENABLE_THREAD_ISOLATION=false EXPENSIVE_DCHECKS_ARE_ON=false FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=false FORCE_ENABLE_RAW_PTR_EXCLUSION=false FORWARD_THROUGH_MALLOC=false HAS_64_BIT_POINTERS=false HAS_MEMORY_TAGGING=false IS_ANDROID=true IS_CASTOS=false IS_CAST_ANDROID=false IS_CHROMEOS=false IS_DEBUG=false RAW_PTR_ZERO_ON_CONSTRUCT=true RAW_PTR_ZERO_ON_DESTRUCT=false RAW_PTR_ZERO_ON_MOVE=true REALLOC_GROWTH_FACTOR_MITIGATION=false RECORD_ALLOC_INFO=false SMALLER_PARTITION_COOKIE=false STACK_SCAN_SUPPORTED=true USE_ALLOCATOR_SHIM=false USE_ASAN_BACKUP_REF_PTR=false USE_FREELIST_DISPATCHER=false USE_FREESLOT_BITMAP=false USE_FULL_MTE=false USE_LARGE_EMPTY_SLOT_SPAN_RING=true USE_PARTITION_ALLOC=false USE_PARTITION_ALLOC_AS_MALLOC=false USE_PARTITION_COOKIE=false USE_RAW_PTR_ASAN_UNOWNED_IMPL=false USE_RAW_PTR_BACKUP_REF_IMPL=false USE_RAW_PTR_HOOKABLE_IMPL=false' | " +
+         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator/partition_allocator/src/partition_alloc:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86_64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc && echo '--flags ASSERT_CPP_20=\"true\" BACKUP_REF_PTR_EXTRA_OOB_CHECKS=\"false\" BACKUP_REF_PTR_POISON_OOB_PTR=\"false\" ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=\"false\" ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=\"false\" ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=\"false\" ENABLE_BACKUP_REF_PTR_SUPPORT=\"false\" ENABLE_DANGLING_RAW_PTR_CHECKS=\"false\" ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=\"false\" ENABLE_GWP_ASAN_SUPPORT=\"false\" ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=\"false\" ENABLE_PKEYS=\"false\" ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=\"true\" ENABLE_POINTER_COMPRESSION=\"false\" ENABLE_POINTER_SUBTRACTION_CHECK=\"false\" ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=\"false\" ENABLE_THREAD_ISOLATION=\"false\" FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=\"false\" FORCE_ENABLE_RAW_PTR_EXCLUSION=\"false\" FORWARD_THROUGH_MALLOC=\"false\" HAS_64_BIT_POINTERS=\"true\" HAS_MEMORY_TAGGING=\"false\" IS_ANDROID=\"true\" IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" IS_CHROMEOS=\"false\" IS_DEBUG=\"false\" RAW_PTR_ZERO_ON_CONSTRUCT=\"true\" RAW_PTR_ZERO_ON_DESTRUCT=\"false\" RAW_PTR_ZERO_ON_MOVE=\"true\" RECORD_ALLOC_INFO=\"false\" SMALLER_PARTITION_COOKIE=\"false\" STACK_SCAN_SUPPORTED=\"true\" USE_ALLOCATOR_SHIM=\"false\" USE_ASAN_BACKUP_REF_PTR=\"false\" USE_FREELIST_DISPATCHER=\"true\" USE_FREESLOT_BITMAP=\"false\" USE_FULL_MTE=\"false\" USE_LARGE_EMPTY_SLOT_SPAN_RING=\"true\" USE_PARTITION_ALLOC=\"false\" USE_PARTITION_ALLOC_AS_MALLOC=\"false\" USE_PARTITION_COOKIE=\"false\" USE_RAW_PTR_ASAN_UNOWNED_IMPL=\"false\" USE_RAW_PTR_BACKUP_REF_IMPL=\"false\" USE_RAW_PTR_HOOKABLE_IMPL=\"false\" ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=\"false\" DCHECKS_ARE_ON=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" DCHECK_IS_CONFIGURABLE=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"false\"' | " +
-         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc &&  " +
+         "echo '--flags ASSERT_CPP_20=true BACKUP_REF_PTR_EXTRA_OOB_CHECKS=false BACKUP_REF_PTR_POISON_OOB_PTR=false CAN_UNWIND_WITH_FRAME_POINTERS=false DCHECKS_ARE_ON=false DCHECK_IS_CONFIGURABLE=false ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=false ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=false ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=false ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=false ENABLE_BACKUP_REF_PTR_SUPPORT=false ENABLE_DANGLING_RAW_PTR_CHECKS=false ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=false ENABLE_GWP_ASAN_SUPPORT=false ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=false ENABLE_PKEYS=false ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=true ENABLE_POINTER_COMPRESSION=false ENABLE_POINTER_SUBTRACTION_CHECK=false ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=false ENABLE_THREAD_ISOLATION=false EXPENSIVE_DCHECKS_ARE_ON=false FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=false FORCE_ENABLE_RAW_PTR_EXCLUSION=false FORWARD_THROUGH_MALLOC=false HAS_64_BIT_POINTERS=true HAS_MEMORY_TAGGING=false IS_ANDROID=true IS_CASTOS=false IS_CAST_ANDROID=false IS_CHROMEOS=false IS_DEBUG=false RAW_PTR_ZERO_ON_CONSTRUCT=true RAW_PTR_ZERO_ON_DESTRUCT=false RAW_PTR_ZERO_ON_MOVE=true REALLOC_GROWTH_FACTOR_MITIGATION=false RECORD_ALLOC_INFO=false SMALLER_PARTITION_COOKIE=false STACK_SCAN_SUPPORTED=true USE_ALLOCATOR_SHIM=false USE_ASAN_BACKUP_REF_PTR=false USE_FREELIST_DISPATCHER=true USE_FREESLOT_BITMAP=false USE_FULL_MTE=false USE_LARGE_EMPTY_SLOT_SPAN_RING=true USE_PARTITION_ALLOC=false USE_PARTITION_ALLOC_AS_MALLOC=false USE_PARTITION_COOKIE=false USE_RAW_PTR_ASAN_UNOWNED_IMPL=false USE_RAW_PTR_BACKUP_REF_IMPL=false USE_RAW_PTR_HOOKABLE_IMPL=false' | " +
+         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator/partition_allocator/src/partition_alloc:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi;",
+         "/dev/stdin " +
+         ";fi;",
     host_cross_supported: false,
     out: [
         "base/allocator/partition_allocator/src/partition_alloc/buildflags.h",
@@ -964,76 +978,88 @@
     name: "tot_cronet_base_allocator_partition_allocator_src_partition_alloc_buildflags__testing",
     cmd: "if [[ ( $$CC_ARCH == 'arm' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc && echo '--flags ASSERT_CPP_20=\"true\" BACKUP_REF_PTR_EXTRA_OOB_CHECKS=\"false\" BACKUP_REF_PTR_POISON_OOB_PTR=\"false\" ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=\"false\" ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=\"false\" ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=\"false\" ENABLE_BACKUP_REF_PTR_SUPPORT=\"false\" ENABLE_DANGLING_RAW_PTR_CHECKS=\"false\" ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=\"false\" ENABLE_GWP_ASAN_SUPPORT=\"false\" ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=\"false\" ENABLE_PKEYS=\"false\" ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=\"true\" ENABLE_POINTER_COMPRESSION=\"false\" ENABLE_POINTER_SUBTRACTION_CHECK=\"false\" ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=\"false\" ENABLE_THREAD_ISOLATION=\"false\" FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=\"false\" FORCE_ENABLE_RAW_PTR_EXCLUSION=\"false\" FORWARD_THROUGH_MALLOC=\"false\" HAS_64_BIT_POINTERS=\"false\" HAS_MEMORY_TAGGING=\"false\" IS_ANDROID=\"true\" IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" IS_CHROMEOS=\"false\" IS_DEBUG=\"false\" RAW_PTR_ZERO_ON_CONSTRUCT=\"true\" RAW_PTR_ZERO_ON_DESTRUCT=\"false\" RAW_PTR_ZERO_ON_MOVE=\"true\" RECORD_ALLOC_INFO=\"false\" SMALLER_PARTITION_COOKIE=\"false\" STACK_SCAN_SUPPORTED=\"true\" USE_ALLOCATOR_SHIM=\"false\" USE_ASAN_BACKUP_REF_PTR=\"false\" USE_FREELIST_DISPATCHER=\"false\" USE_FREESLOT_BITMAP=\"false\" USE_FULL_MTE=\"false\" USE_LARGE_EMPTY_SLOT_SPAN_RING=\"true\" USE_PARTITION_ALLOC=\"false\" USE_PARTITION_ALLOC_AS_MALLOC=\"false\" USE_PARTITION_COOKIE=\"false\" USE_RAW_PTR_ASAN_UNOWNED_IMPL=\"false\" USE_RAW_PTR_BACKUP_REF_IMPL=\"false\" USE_RAW_PTR_HOOKABLE_IMPL=\"false\" ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=\"false\" DCHECKS_ARE_ON=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" DCHECK_IS_CONFIGURABLE=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"false\"' | " +
-         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc &&  " +
+         "echo '--flags ASSERT_CPP_20=true BACKUP_REF_PTR_EXTRA_OOB_CHECKS=false BACKUP_REF_PTR_POISON_OOB_PTR=false CAN_UNWIND_WITH_FRAME_POINTERS=false DCHECKS_ARE_ON=false DCHECK_IS_CONFIGURABLE=false ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=false ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=false ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=false ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=false ENABLE_BACKUP_REF_PTR_SUPPORT=false ENABLE_DANGLING_RAW_PTR_CHECKS=false ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=false ENABLE_GWP_ASAN_SUPPORT=false ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=false ENABLE_PKEYS=false ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=true ENABLE_POINTER_COMPRESSION=false ENABLE_POINTER_SUBTRACTION_CHECK=false ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=false ENABLE_THREAD_ISOLATION=false EXPENSIVE_DCHECKS_ARE_ON=false FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=false FORCE_ENABLE_RAW_PTR_EXCLUSION=false FORWARD_THROUGH_MALLOC=false HAS_64_BIT_POINTERS=false HAS_MEMORY_TAGGING=false IS_ANDROID=true IS_CASTOS=false IS_CAST_ANDROID=false IS_CHROMEOS=false IS_DEBUG=false RAW_PTR_ZERO_ON_CONSTRUCT=true RAW_PTR_ZERO_ON_DESTRUCT=false RAW_PTR_ZERO_ON_MOVE=true REALLOC_GROWTH_FACTOR_MITIGATION=false RECORD_ALLOC_INFO=false SMALLER_PARTITION_COOKIE=false STACK_SCAN_SUPPORTED=true USE_ALLOCATOR_SHIM=false USE_ASAN_BACKUP_REF_PTR=false USE_FREELIST_DISPATCHER=false USE_FREESLOT_BITMAP=false USE_FULL_MTE=false USE_LARGE_EMPTY_SLOT_SPAN_RING=true USE_PARTITION_ALLOC=false USE_PARTITION_ALLOC_AS_MALLOC=false USE_PARTITION_COOKIE=false USE_RAW_PTR_ASAN_UNOWNED_IMPL=false USE_RAW_PTR_BACKUP_REF_IMPL=false USE_RAW_PTR_HOOKABLE_IMPL=false' | " +
+         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator/partition_allocator/src/partition_alloc:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'arm64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc && echo '--flags ASSERT_CPP_20=\"true\" BACKUP_REF_PTR_EXTRA_OOB_CHECKS=\"false\" BACKUP_REF_PTR_POISON_OOB_PTR=\"false\" ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=\"false\" ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=\"false\" ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=\"false\" ENABLE_BACKUP_REF_PTR_SUPPORT=\"false\" ENABLE_DANGLING_RAW_PTR_CHECKS=\"false\" ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=\"false\" ENABLE_GWP_ASAN_SUPPORT=\"false\" ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=\"false\" ENABLE_PKEYS=\"false\" ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=\"true\" ENABLE_POINTER_COMPRESSION=\"false\" ENABLE_POINTER_SUBTRACTION_CHECK=\"false\" ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=\"false\" ENABLE_THREAD_ISOLATION=\"false\" FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=\"false\" FORCE_ENABLE_RAW_PTR_EXCLUSION=\"false\" FORWARD_THROUGH_MALLOC=\"false\" HAS_64_BIT_POINTERS=\"true\" HAS_MEMORY_TAGGING=\"true\" IS_ANDROID=\"true\" IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" IS_CHROMEOS=\"false\" IS_DEBUG=\"false\" RAW_PTR_ZERO_ON_CONSTRUCT=\"true\" RAW_PTR_ZERO_ON_DESTRUCT=\"false\" RAW_PTR_ZERO_ON_MOVE=\"true\" RECORD_ALLOC_INFO=\"false\" SMALLER_PARTITION_COOKIE=\"false\" STACK_SCAN_SUPPORTED=\"true\" USE_ALLOCATOR_SHIM=\"false\" USE_ASAN_BACKUP_REF_PTR=\"false\" USE_FREELIST_DISPATCHER=\"true\" USE_FREESLOT_BITMAP=\"false\" USE_FULL_MTE=\"false\" USE_LARGE_EMPTY_SLOT_SPAN_RING=\"true\" USE_PARTITION_ALLOC=\"false\" USE_PARTITION_ALLOC_AS_MALLOC=\"false\" USE_PARTITION_COOKIE=\"false\" USE_RAW_PTR_ASAN_UNOWNED_IMPL=\"false\" USE_RAW_PTR_BACKUP_REF_IMPL=\"false\" USE_RAW_PTR_HOOKABLE_IMPL=\"false\" ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=\"false\" DCHECKS_ARE_ON=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" DCHECK_IS_CONFIGURABLE=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"true\"' | " +
-         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc &&  " +
+         "echo '--flags ASSERT_CPP_20=true BACKUP_REF_PTR_EXTRA_OOB_CHECKS=false BACKUP_REF_PTR_POISON_OOB_PTR=false CAN_UNWIND_WITH_FRAME_POINTERS=true DCHECKS_ARE_ON=false DCHECK_IS_CONFIGURABLE=false ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=false ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=false ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=false ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=false ENABLE_BACKUP_REF_PTR_SUPPORT=false ENABLE_DANGLING_RAW_PTR_CHECKS=false ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=false ENABLE_GWP_ASAN_SUPPORT=false ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=false ENABLE_PKEYS=false ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=true ENABLE_POINTER_COMPRESSION=false ENABLE_POINTER_SUBTRACTION_CHECK=false ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=false ENABLE_THREAD_ISOLATION=false EXPENSIVE_DCHECKS_ARE_ON=false FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=false FORCE_ENABLE_RAW_PTR_EXCLUSION=false FORWARD_THROUGH_MALLOC=false HAS_64_BIT_POINTERS=true HAS_MEMORY_TAGGING=true IS_ANDROID=true IS_CASTOS=false IS_CAST_ANDROID=false IS_CHROMEOS=false IS_DEBUG=false RAW_PTR_ZERO_ON_CONSTRUCT=true RAW_PTR_ZERO_ON_DESTRUCT=false RAW_PTR_ZERO_ON_MOVE=true REALLOC_GROWTH_FACTOR_MITIGATION=false RECORD_ALLOC_INFO=false SMALLER_PARTITION_COOKIE=false STACK_SCAN_SUPPORTED=true USE_ALLOCATOR_SHIM=false USE_ASAN_BACKUP_REF_PTR=false USE_FREELIST_DISPATCHER=true USE_FREESLOT_BITMAP=false USE_FULL_MTE=false USE_LARGE_EMPTY_SLOT_SPAN_RING=true USE_PARTITION_ALLOC=false USE_PARTITION_ALLOC_AS_MALLOC=false USE_PARTITION_COOKIE=false USE_RAW_PTR_ASAN_UNOWNED_IMPL=false USE_RAW_PTR_BACKUP_REF_IMPL=false USE_RAW_PTR_HOOKABLE_IMPL=false' | " +
+         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator/partition_allocator/src/partition_alloc:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'riscv64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc && echo '--flags ASSERT_CPP_20=\"true\" BACKUP_REF_PTR_EXTRA_OOB_CHECKS=\"false\" BACKUP_REF_PTR_POISON_OOB_PTR=\"false\" ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=\"false\" ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=\"false\" ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=\"false\" ENABLE_BACKUP_REF_PTR_SUPPORT=\"false\" ENABLE_DANGLING_RAW_PTR_CHECKS=\"false\" ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=\"false\" ENABLE_GWP_ASAN_SUPPORT=\"false\" ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=\"false\" ENABLE_PKEYS=\"false\" ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=\"true\" ENABLE_POINTER_COMPRESSION=\"false\" ENABLE_POINTER_SUBTRACTION_CHECK=\"false\" ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=\"false\" ENABLE_THREAD_ISOLATION=\"false\" FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=\"false\" FORCE_ENABLE_RAW_PTR_EXCLUSION=\"false\" FORWARD_THROUGH_MALLOC=\"false\" HAS_64_BIT_POINTERS=\"true\" HAS_MEMORY_TAGGING=\"false\" IS_ANDROID=\"true\" IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" IS_CHROMEOS=\"false\" IS_DEBUG=\"false\" RAW_PTR_ZERO_ON_CONSTRUCT=\"true\" RAW_PTR_ZERO_ON_DESTRUCT=\"false\" RAW_PTR_ZERO_ON_MOVE=\"true\" RECORD_ALLOC_INFO=\"false\" SMALLER_PARTITION_COOKIE=\"false\" STACK_SCAN_SUPPORTED=\"true\" USE_ALLOCATOR_SHIM=\"false\" USE_ASAN_BACKUP_REF_PTR=\"false\" USE_FREELIST_DISPATCHER=\"true\" USE_FREESLOT_BITMAP=\"false\" USE_FULL_MTE=\"false\" USE_LARGE_EMPTY_SLOT_SPAN_RING=\"true\" USE_PARTITION_ALLOC=\"false\" USE_PARTITION_ALLOC_AS_MALLOC=\"false\" USE_PARTITION_COOKIE=\"false\" USE_RAW_PTR_ASAN_UNOWNED_IMPL=\"false\" USE_RAW_PTR_BACKUP_REF_IMPL=\"false\" USE_RAW_PTR_HOOKABLE_IMPL=\"false\" ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=\"false\" DCHECKS_ARE_ON=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" DCHECK_IS_CONFIGURABLE=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"false\"' | " +
-         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc &&  " +
+         "echo '--flags ASSERT_CPP_20=true BACKUP_REF_PTR_EXTRA_OOB_CHECKS=false BACKUP_REF_PTR_POISON_OOB_PTR=false CAN_UNWIND_WITH_FRAME_POINTERS=false DCHECKS_ARE_ON=false DCHECK_IS_CONFIGURABLE=false ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=false ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=false ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=false ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=false ENABLE_BACKUP_REF_PTR_SUPPORT=false ENABLE_DANGLING_RAW_PTR_CHECKS=false ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=false ENABLE_GWP_ASAN_SUPPORT=false ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=false ENABLE_PKEYS=false ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=true ENABLE_POINTER_COMPRESSION=false ENABLE_POINTER_SUBTRACTION_CHECK=false ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=false ENABLE_THREAD_ISOLATION=false EXPENSIVE_DCHECKS_ARE_ON=false FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=false FORCE_ENABLE_RAW_PTR_EXCLUSION=false FORWARD_THROUGH_MALLOC=false HAS_64_BIT_POINTERS=true HAS_MEMORY_TAGGING=false IS_ANDROID=true IS_CASTOS=false IS_CAST_ANDROID=false IS_CHROMEOS=false IS_DEBUG=false RAW_PTR_ZERO_ON_CONSTRUCT=true RAW_PTR_ZERO_ON_DESTRUCT=false RAW_PTR_ZERO_ON_MOVE=true REALLOC_GROWTH_FACTOR_MITIGATION=false RECORD_ALLOC_INFO=false SMALLER_PARTITION_COOKIE=false STACK_SCAN_SUPPORTED=true USE_ALLOCATOR_SHIM=false USE_ASAN_BACKUP_REF_PTR=false USE_FREELIST_DISPATCHER=true USE_FREESLOT_BITMAP=false USE_FULL_MTE=false USE_LARGE_EMPTY_SLOT_SPAN_RING=true USE_PARTITION_ALLOC=false USE_PARTITION_ALLOC_AS_MALLOC=false USE_PARTITION_COOKIE=false USE_RAW_PTR_ASAN_UNOWNED_IMPL=false USE_RAW_PTR_BACKUP_REF_IMPL=false USE_RAW_PTR_HOOKABLE_IMPL=false' | " +
+         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator/partition_allocator/src/partition_alloc:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc && echo '--flags ASSERT_CPP_20=\"true\" BACKUP_REF_PTR_EXTRA_OOB_CHECKS=\"false\" BACKUP_REF_PTR_POISON_OOB_PTR=\"false\" ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=\"false\" ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=\"false\" ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=\"false\" ENABLE_BACKUP_REF_PTR_SUPPORT=\"false\" ENABLE_DANGLING_RAW_PTR_CHECKS=\"false\" ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=\"false\" ENABLE_GWP_ASAN_SUPPORT=\"false\" ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=\"false\" ENABLE_PKEYS=\"false\" ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=\"true\" ENABLE_POINTER_COMPRESSION=\"false\" ENABLE_POINTER_SUBTRACTION_CHECK=\"false\" ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=\"false\" ENABLE_THREAD_ISOLATION=\"false\" FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=\"false\" FORCE_ENABLE_RAW_PTR_EXCLUSION=\"false\" FORWARD_THROUGH_MALLOC=\"false\" HAS_64_BIT_POINTERS=\"false\" HAS_MEMORY_TAGGING=\"false\" IS_ANDROID=\"true\" IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" IS_CHROMEOS=\"false\" IS_DEBUG=\"false\" RAW_PTR_ZERO_ON_CONSTRUCT=\"true\" RAW_PTR_ZERO_ON_DESTRUCT=\"false\" RAW_PTR_ZERO_ON_MOVE=\"true\" RECORD_ALLOC_INFO=\"false\" SMALLER_PARTITION_COOKIE=\"false\" STACK_SCAN_SUPPORTED=\"true\" USE_ALLOCATOR_SHIM=\"false\" USE_ASAN_BACKUP_REF_PTR=\"false\" USE_FREELIST_DISPATCHER=\"false\" USE_FREESLOT_BITMAP=\"false\" USE_FULL_MTE=\"false\" USE_LARGE_EMPTY_SLOT_SPAN_RING=\"true\" USE_PARTITION_ALLOC=\"false\" USE_PARTITION_ALLOC_AS_MALLOC=\"false\" USE_PARTITION_COOKIE=\"false\" USE_RAW_PTR_ASAN_UNOWNED_IMPL=\"false\" USE_RAW_PTR_BACKUP_REF_IMPL=\"false\" USE_RAW_PTR_HOOKABLE_IMPL=\"false\" ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=\"false\" DCHECKS_ARE_ON=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" DCHECK_IS_CONFIGURABLE=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"true\"' | " +
-         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc &&  " +
+         "echo '--flags ASSERT_CPP_20=true BACKUP_REF_PTR_EXTRA_OOB_CHECKS=false BACKUP_REF_PTR_POISON_OOB_PTR=false CAN_UNWIND_WITH_FRAME_POINTERS=true DCHECKS_ARE_ON=false DCHECK_IS_CONFIGURABLE=false ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=false ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=false ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=false ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=false ENABLE_BACKUP_REF_PTR_SUPPORT=false ENABLE_DANGLING_RAW_PTR_CHECKS=false ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=false ENABLE_GWP_ASAN_SUPPORT=false ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=false ENABLE_PKEYS=false ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=true ENABLE_POINTER_COMPRESSION=false ENABLE_POINTER_SUBTRACTION_CHECK=false ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=false ENABLE_THREAD_ISOLATION=false EXPENSIVE_DCHECKS_ARE_ON=false FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=false FORCE_ENABLE_RAW_PTR_EXCLUSION=false FORWARD_THROUGH_MALLOC=false HAS_64_BIT_POINTERS=false HAS_MEMORY_TAGGING=false IS_ANDROID=true IS_CASTOS=false IS_CAST_ANDROID=false IS_CHROMEOS=false IS_DEBUG=false RAW_PTR_ZERO_ON_CONSTRUCT=true RAW_PTR_ZERO_ON_DESTRUCT=false RAW_PTR_ZERO_ON_MOVE=true REALLOC_GROWTH_FACTOR_MITIGATION=false RECORD_ALLOC_INFO=false SMALLER_PARTITION_COOKIE=false STACK_SCAN_SUPPORTED=true USE_ALLOCATOR_SHIM=false USE_ASAN_BACKUP_REF_PTR=false USE_FREELIST_DISPATCHER=false USE_FREESLOT_BITMAP=false USE_FULL_MTE=false USE_LARGE_EMPTY_SLOT_SPAN_RING=true USE_PARTITION_ALLOC=false USE_PARTITION_ALLOC_AS_MALLOC=false USE_PARTITION_COOKIE=false USE_RAW_PTR_ASAN_UNOWNED_IMPL=false USE_RAW_PTR_BACKUP_REF_IMPL=false USE_RAW_PTR_HOOKABLE_IMPL=false' | " +
+         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator/partition_allocator/src/partition_alloc:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86_64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc && echo '--flags ASSERT_CPP_20=\"true\" BACKUP_REF_PTR_EXTRA_OOB_CHECKS=\"false\" BACKUP_REF_PTR_POISON_OOB_PTR=\"false\" ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=\"false\" ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=\"false\" ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=\"false\" ENABLE_BACKUP_REF_PTR_SUPPORT=\"false\" ENABLE_DANGLING_RAW_PTR_CHECKS=\"false\" ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=\"false\" ENABLE_GWP_ASAN_SUPPORT=\"false\" ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=\"false\" ENABLE_PKEYS=\"false\" ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=\"true\" ENABLE_POINTER_COMPRESSION=\"false\" ENABLE_POINTER_SUBTRACTION_CHECK=\"false\" ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=\"false\" ENABLE_THREAD_ISOLATION=\"false\" FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=\"false\" FORCE_ENABLE_RAW_PTR_EXCLUSION=\"false\" FORWARD_THROUGH_MALLOC=\"false\" HAS_64_BIT_POINTERS=\"true\" HAS_MEMORY_TAGGING=\"false\" IS_ANDROID=\"true\" IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" IS_CHROMEOS=\"false\" IS_DEBUG=\"false\" RAW_PTR_ZERO_ON_CONSTRUCT=\"true\" RAW_PTR_ZERO_ON_DESTRUCT=\"false\" RAW_PTR_ZERO_ON_MOVE=\"true\" RECORD_ALLOC_INFO=\"false\" SMALLER_PARTITION_COOKIE=\"false\" STACK_SCAN_SUPPORTED=\"true\" USE_ALLOCATOR_SHIM=\"false\" USE_ASAN_BACKUP_REF_PTR=\"false\" USE_FREELIST_DISPATCHER=\"true\" USE_FREESLOT_BITMAP=\"false\" USE_FULL_MTE=\"false\" USE_LARGE_EMPTY_SLOT_SPAN_RING=\"true\" USE_PARTITION_ALLOC=\"false\" USE_PARTITION_ALLOC_AS_MALLOC=\"false\" USE_PARTITION_COOKIE=\"false\" USE_RAW_PTR_ASAN_UNOWNED_IMPL=\"false\" USE_RAW_PTR_BACKUP_REF_IMPL=\"false\" USE_RAW_PTR_HOOKABLE_IMPL=\"false\" ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=\"false\" DCHECKS_ARE_ON=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" DCHECK_IS_CONFIGURABLE=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"false\"' | " +
-         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc &&  " +
+         "echo '--flags ASSERT_CPP_20=true BACKUP_REF_PTR_EXTRA_OOB_CHECKS=false BACKUP_REF_PTR_POISON_OOB_PTR=false CAN_UNWIND_WITH_FRAME_POINTERS=false DCHECKS_ARE_ON=false DCHECK_IS_CONFIGURABLE=false ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=false ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=false ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=false ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=false ENABLE_BACKUP_REF_PTR_SUPPORT=false ENABLE_DANGLING_RAW_PTR_CHECKS=false ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=false ENABLE_GWP_ASAN_SUPPORT=false ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=false ENABLE_PKEYS=false ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=true ENABLE_POINTER_COMPRESSION=false ENABLE_POINTER_SUBTRACTION_CHECK=false ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=false ENABLE_THREAD_ISOLATION=false EXPENSIVE_DCHECKS_ARE_ON=false FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=false FORCE_ENABLE_RAW_PTR_EXCLUSION=false FORWARD_THROUGH_MALLOC=false HAS_64_BIT_POINTERS=true HAS_MEMORY_TAGGING=false IS_ANDROID=true IS_CASTOS=false IS_CAST_ANDROID=false IS_CHROMEOS=false IS_DEBUG=false RAW_PTR_ZERO_ON_CONSTRUCT=true RAW_PTR_ZERO_ON_DESTRUCT=false RAW_PTR_ZERO_ON_MOVE=true REALLOC_GROWTH_FACTOR_MITIGATION=false RECORD_ALLOC_INFO=false SMALLER_PARTITION_COOKIE=false STACK_SCAN_SUPPORTED=true USE_ALLOCATOR_SHIM=false USE_ASAN_BACKUP_REF_PTR=false USE_FREELIST_DISPATCHER=true USE_FREESLOT_BITMAP=false USE_FULL_MTE=false USE_LARGE_EMPTY_SLOT_SPAN_RING=true USE_PARTITION_ALLOC=false USE_PARTITION_ALLOC_AS_MALLOC=false USE_PARTITION_COOKIE=false USE_RAW_PTR_ASAN_UNOWNED_IMPL=false USE_RAW_PTR_BACKUP_REF_IMPL=false USE_RAW_PTR_HOOKABLE_IMPL=false' | " +
+         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator/partition_allocator/src/partition_alloc:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ $$CC_OS != 'android' ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc && echo '--flags ASSERT_CPP_20=\"true\" BACKUP_REF_PTR_EXTRA_OOB_CHECKS=\"false\" BACKUP_REF_PTR_POISON_OOB_PTR=\"false\" ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=\"false\" ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=\"false\" ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=\"false\" ENABLE_BACKUP_REF_PTR_SUPPORT=\"false\" ENABLE_DANGLING_RAW_PTR_CHECKS=\"false\" ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=\"false\" ENABLE_GWP_ASAN_SUPPORT=\"false\" ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=\"false\" ENABLE_PKEYS=\"false\" ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=\"true\" ENABLE_POINTER_COMPRESSION=\"false\" ENABLE_POINTER_SUBTRACTION_CHECK=\"false\" ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=\"true\" ENABLE_THREAD_ISOLATION=\"false\" FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=\"false\" FORCE_ENABLE_RAW_PTR_EXCLUSION=\"false\" FORWARD_THROUGH_MALLOC=\"false\" HAS_64_BIT_POINTERS=\"true\" HAS_MEMORY_TAGGING=\"false\" IS_ANDROID=\"false\" IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" IS_CHROMEOS=\"false\" IS_DEBUG=\"false\" RAW_PTR_ZERO_ON_CONSTRUCT=\"true\" RAW_PTR_ZERO_ON_DESTRUCT=\"false\" RAW_PTR_ZERO_ON_MOVE=\"true\" RECORD_ALLOC_INFO=\"false\" SMALLER_PARTITION_COOKIE=\"false\" STACK_SCAN_SUPPORTED=\"true\" USE_ALLOCATOR_SHIM=\"false\" USE_ASAN_BACKUP_REF_PTR=\"false\" USE_FREELIST_DISPATCHER=\"true\" USE_FREESLOT_BITMAP=\"false\" USE_FULL_MTE=\"false\" USE_LARGE_EMPTY_SLOT_SPAN_RING=\"true\" USE_PARTITION_ALLOC=\"false\" USE_PARTITION_ALLOC_AS_MALLOC=\"false\" USE_PARTITION_COOKIE=\"false\" USE_RAW_PTR_ASAN_UNOWNED_IMPL=\"false\" USE_RAW_PTR_BACKUP_REF_IMPL=\"false\" USE_RAW_PTR_HOOKABLE_IMPL=\"false\" ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=\"false\" DCHECKS_ARE_ON=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" DCHECK_IS_CONFIGURABLE=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"true\"' | " +
-         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/allocator/partition_allocator/src/partition_alloc &&  " +
+         "echo '--flags ASSERT_CPP_20=true BACKUP_REF_PTR_EXTRA_OOB_CHECKS=false BACKUP_REF_PTR_POISON_OOB_PTR=false CAN_UNWIND_WITH_FRAME_POINTERS=true DCHECKS_ARE_ON=false DCHECK_IS_CONFIGURABLE=false ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT=false ENABLE_BACKUP_REF_PTR_FEATURE_FLAG=false ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER=false ENABLE_BACKUP_REF_PTR_SLOW_CHECKS=false ENABLE_BACKUP_REF_PTR_SUPPORT=false ENABLE_DANGLING_RAW_PTR_CHECKS=false ENABLE_DANGLING_RAW_PTR_FEATURE_FLAG=false ENABLE_GWP_ASAN_SUPPORT=false ENABLE_PARTITION_LOCK_REENTRANCY_CHECK=false ENABLE_PKEYS=false ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK=true ENABLE_POINTER_COMPRESSION=false ENABLE_POINTER_SUBTRACTION_CHECK=false ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS=true ENABLE_THREAD_ISOLATION=false EXPENSIVE_DCHECKS_ARE_ON=false FORCE_DISABLE_BACKUP_REF_PTR_FEATURE=false FORCE_ENABLE_RAW_PTR_EXCLUSION=false FORWARD_THROUGH_MALLOC=false HAS_64_BIT_POINTERS=true HAS_MEMORY_TAGGING=false IS_ANDROID=false IS_CASTOS=false IS_CAST_ANDROID=false IS_CHROMEOS=false IS_DEBUG=false RAW_PTR_ZERO_ON_CONSTRUCT=true RAW_PTR_ZERO_ON_DESTRUCT=false RAW_PTR_ZERO_ON_MOVE=true REALLOC_GROWTH_FACTOR_MITIGATION=false RECORD_ALLOC_INFO=false SMALLER_PARTITION_COOKIE=false STACK_SCAN_SUPPORTED=true USE_ALLOCATOR_SHIM=false USE_ASAN_BACKUP_REF_PTR=false USE_FREELIST_DISPATCHER=true USE_FREESLOT_BITMAP=false USE_FULL_MTE=false USE_LARGE_EMPTY_SLOT_SPAN_RING=true USE_PARTITION_ALLOC=false USE_PARTITION_ALLOC_AS_MALLOC=false USE_PARTITION_COOKIE=false USE_RAW_PTR_ASAN_UNOWNED_IMPL=false USE_RAW_PTR_BACKUP_REF_IMPL=false USE_RAW_PTR_HOOKABLE_IMPL=false' | " +
+         "$(location base/allocator/partition_allocator/src/partition_alloc/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base/allocator/partition_allocator/src/partition_alloc:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi;",
+         "/dev/stdin " +
+         ";fi;",
     host_supported: true,
     host_cross_supported: false,
     out: [
@@ -1059,64 +1085,74 @@
     name: "tot_cronet_base_anchor_functions_buildflags",
     cmd: "if [[ ( $$CC_ARCH == 'arm' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/android/library_loader && echo '--flags USE_LLD=\"true\" SUPPORTS_CODE_ORDERING=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/android/library_loader &&  " +
+         "echo '--flags USE_LLD=true SUPPORTS_CODE_ORDERING=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:anchor_functions_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'arm64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/android/library_loader && echo '--flags USE_LLD=\"true\" SUPPORTS_CODE_ORDERING=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/android/library_loader &&  " +
+         "echo '--flags USE_LLD=true SUPPORTS_CODE_ORDERING=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:anchor_functions_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'riscv64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/android/library_loader && echo '--flags USE_LLD=\"true\" SUPPORTS_CODE_ORDERING=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/android/library_loader &&  " +
+         "echo '--flags USE_LLD=true SUPPORTS_CODE_ORDERING=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:anchor_functions_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/android/library_loader && echo '--flags USE_LLD=\"true\" SUPPORTS_CODE_ORDERING=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/android/library_loader &&  " +
+         "echo '--flags USE_LLD=true SUPPORTS_CODE_ORDERING=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:anchor_functions_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86_64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/android/library_loader && echo '--flags USE_LLD=\"true\" SUPPORTS_CODE_ORDERING=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/android/library_loader &&  " +
+         "echo '--flags USE_LLD=true SUPPORTS_CODE_ORDERING=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:anchor_functions_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi;",
+         "/dev/stdin " +
+         ";fi;",
     host_cross_supported: false,
     out: [
         "base/android/library_loader/anchor_functions_buildflags.h",
@@ -1137,76 +1173,88 @@
     name: "tot_cronet_base_anchor_functions_buildflags__testing",
     cmd: "if [[ ( $$CC_ARCH == 'arm' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/android/library_loader && echo '--flags USE_LLD=\"true\" SUPPORTS_CODE_ORDERING=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/android/library_loader &&  " +
+         "echo '--flags USE_LLD=true SUPPORTS_CODE_ORDERING=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:anchor_functions_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'arm64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/android/library_loader && echo '--flags USE_LLD=\"true\" SUPPORTS_CODE_ORDERING=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/android/library_loader &&  " +
+         "echo '--flags USE_LLD=true SUPPORTS_CODE_ORDERING=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:anchor_functions_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'riscv64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/android/library_loader && echo '--flags USE_LLD=\"true\" SUPPORTS_CODE_ORDERING=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/android/library_loader &&  " +
+         "echo '--flags USE_LLD=true SUPPORTS_CODE_ORDERING=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:anchor_functions_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/android/library_loader && echo '--flags USE_LLD=\"true\" SUPPORTS_CODE_ORDERING=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/android/library_loader &&  " +
+         "echo '--flags USE_LLD=true SUPPORTS_CODE_ORDERING=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:anchor_functions_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86_64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/android/library_loader && echo '--flags USE_LLD=\"true\" SUPPORTS_CODE_ORDERING=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/android/library_loader &&  " +
+         "echo '--flags USE_LLD=true SUPPORTS_CODE_ORDERING=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:anchor_functions_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ $$CC_OS != 'android' ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/android/library_loader && echo '--flags USE_LLD=\"true\" SUPPORTS_CODE_ORDERING=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/android/library_loader &&  " +
+         "echo '--flags USE_LLD=true SUPPORTS_CODE_ORDERING=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:anchor_functions_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi;",
+         "/dev/stdin " +
+         ";fi;",
     host_supported: true,
     host_cross_supported: false,
     out: [
@@ -1223,21 +1271,331 @@
     ],
 }
 
+// GN: //base:android_info_java__process_device
+java_genrule {
+    name: "tot_cronet_base_android_info_java__process_device",
+    srcs: [
+        ":tot_cronet_base_android_info_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/android_info_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:android_info_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_android_info_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_android_info_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/android_info_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:android_info_jni__action
+cc_genrule {
+    name: "tot_cronet_base_android_info_jni__action",
+    srcs: [
+        "base/android/java/src/org/chromium/base/AndroidInfo.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/android_info_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/android_info_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/android_info_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/android_info_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "AndroidInfo_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/AndroidInfo.java)' " +
+         "--package-prefix " +
+         "android.net.connectivity",
+    host_cross_supported: false,
+    out: [
+        "base/android_info_jni.srcjar",
+        "base/android_info_jni/AndroidInfo_jni.h",
+        "base/android_info_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:android_info_jni__action
+java_genrule {
+    name: "tot_cronet_base_android_info_jni__action__java",
+    srcs: [
+        "base/android/java/src/org/chromium/base/AndroidInfo.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/android_info_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/android_info_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/android_info_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/android_info_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "AndroidInfo_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/AndroidInfo.java)' " +
+         "--package-prefix " +
+         "android.net.connectivity",
+    out: [
+        "base/android_info_jni.srcjar",
+        "base/android_info_jni/AndroidInfo_jni.h",
+        "base/android_info_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:android_info_jni__action
+java_genrule {
+    name: "tot_cronet_base_android_info_jni__action__java_proxy_only",
+    srcs: [
+        ":tot_cronet_base_android_info_jni__action__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "android_info_jni.srcjar",
+    ],
+}
+
+// GN: //base:android_info_jni__action__testing
+cc_genrule {
+    name: "tot_cronet_base_android_info_jni__action__testing",
+    srcs: [
+        "base/android/java/src/org/chromium/base/AndroidInfo.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/android_info_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/android_info_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/android_info_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/android_info_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "AndroidInfo_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/AndroidInfo.java)'",
+    host_cross_supported: false,
+    out: [
+        "base/android_info_jni.srcjar",
+        "base/android_info_jni/AndroidInfo_jni.h",
+        "base/android_info_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:android_info_jni__action__testing
+java_genrule {
+    name: "tot_cronet_base_android_info_jni__action__testing__java",
+    srcs: [
+        "base/android/java/src/org/chromium/base/AndroidInfo.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/android_info_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/android_info_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/android_info_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/android_info_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "AndroidInfo_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/AndroidInfo.java)'",
+    out: [
+        "base/android_info_jni.srcjar",
+        "base/android_info_jni/AndroidInfo_jni.h",
+        "base/android_info_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:android_info_jni__action__testing
+java_genrule {
+    name: "tot_cronet_base_android_info_jni__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_base_android_info_jni__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "android_info_jni.srcjar",
+    ],
+}
+
 // GN: //base:android_runtime_jni_headers__action
 cc_genrule {
     name: "tot_cronet_base_android_runtime_jni_headers__action",
     tools: [
         ":javap",
     ],
-    cmd: "mkdir -p $(genDir)/jni_headers/base/android_runtime_jni_headers && $(location third_party/jni_zero/jni_zero.py) from-jar " +
+    cmd: "mkdir -p $(genDir)/jni_headers/base/android_runtime_jni_headers &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-jar " +
          "--output-dir " +
-         "$(genDir)/base/android_runtime_jni_headers " +
+         "'$(genDir)/base/android_runtime_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--jar-file " +
-         "$(location :current_android_jar) " +
+         "'$(location :current_android_jar)' " +
          "--javap " +
-         "$(location :javap) " +
+         "'$(location :javap)' " +
          "--output-name " +
          "Runnable_jni.h " +
          "--output-name " +
@@ -1290,15 +1648,17 @@
     tools: [
         ":javap",
     ],
-    cmd: "mkdir -p $(genDir)/jni_headers/base/android_runtime_jni_headers && $(location third_party/jni_zero/jni_zero.py) from-jar " +
+    cmd: "mkdir -p $(genDir)/jni_headers/base/android_runtime_jni_headers &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-jar " +
          "--output-dir " +
-         "$(genDir)/base/android_runtime_jni_headers " +
+         "'$(genDir)/base/android_runtime_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--jar-file " +
-         "$(location :current_android_jar) " +
+         "'$(location :current_android_jar)' " +
          "--javap " +
-         "$(location :javap) " +
+         "'$(location :javap)' " +
          "--output-name " +
          "Runnable_jni.h " +
          "--output-name " +
@@ -1348,9 +1708,11 @@
 // GN: //base:application_status_enum_srcjar
 java_genrule {
     name: "tot_cronet_base_application_status_enum_srcjar",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/android/application_status_listener.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/android/application_status_listener.h)'",
     out: [
         "base/application_status_enum_srcjar.srcjar",
     ],
@@ -1372,9 +1734,11 @@
 // GN: //base:application_status_enum_srcjar__testing
 java_genrule {
     name: "tot_cronet_base_application_status_enum_srcjar__testing",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/android/application_status_listener.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/android/application_status_listener.h)'",
     out: [
         "base/application_status_enum_srcjar.srcjar",
     ],
@@ -1396,12 +1760,14 @@
 // GN: //base:base_android_java_enums_srcjar
 java_genrule {
     name: "tot_cronet_base_base_android_java_enums_srcjar",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/android/child_process_binding_types.h) " +
-         "$(location base/power_monitor/power_observer.h) " +
-         "$(location base/process/kill.h) " +
-         "$(location base/task/task_traits.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/android/child_process_binding_types.h)' " +
+         "'$(location base/power_monitor/power_observer.h)' " +
+         "'$(location base/process/kill.h)' " +
+         "'$(location base/task/task_traits.h)'",
     out: [
         "base/base_android_java_enums_srcjar.srcjar",
     ],
@@ -1426,12 +1792,14 @@
 // GN: //base:base_android_java_enums_srcjar__testing
 java_genrule {
     name: "tot_cronet_base_base_android_java_enums_srcjar__testing",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/android/child_process_binding_types.h) " +
-         "$(location base/power_monitor/power_observer.h) " +
-         "$(location base/process/kill.h) " +
-         "$(location base/task/task_traits.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/android/child_process_binding_types.h)' " +
+         "'$(location base/power_monitor/power_observer.h)' " +
+         "'$(location base/process/kill.h)' " +
+         "'$(location base/task/task_traits.h)'",
     out: [
         "base/base_android_java_enums_srcjar.srcjar",
     ],
@@ -1453,13 +1821,172 @@
     ],
 }
 
+// GN: //base:base_cached_flags_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_base_cached_flags_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_base_cached_flags_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/base_cached_flags_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_java__process_device
+java_genrule {
+    name: "tot_cronet_base_base_java__process_device",
+    srcs: [
+        ":tot_cronet_base_base_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/base_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_base_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_base_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/base_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_java_test_support__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_base_java_test_support__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_base_java_test_support__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/base_java_test_support.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_java_url_utils_for_test__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_base_java_url_utils_for_test__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_base_java_url_utils_for_test__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/base_java_url_utils_for_test.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:base_jni__action
 cc_genrule {
     name: "tot_cronet_base_base_jni__action",
     srcs: [
         "base/android/java/src/org/chromium/base/ApkAssets.java",
         "base/android/java/src/org/chromium/base/BaseFeatureMap.java",
-        "base/android/java/src/org/chromium/base/BuildInfo.java",
         "base/android/java/src/org/chromium/base/BundleUtils.java",
         "base/android/java/src/org/chromium/base/CpuFeatures.java",
         "base/android/java/src/org/chromium/base/EventLog.java",
@@ -1475,6 +2002,9 @@
         "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
         "base/android/java/src/org/chromium/base/JavaHandlerThread.java",
         "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
         "base/android/java/src/org/chromium/base/LocaleUtils.java",
         "base/android/java/src/org/chromium/base/PathService.java",
         "base/android/java/src/org/chromium/base/PathUtils.java",
@@ -1486,23 +2016,23 @@
         "base/android/java/src/org/chromium/base/UnguessableToken.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/base_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/base_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/base_jni " +
+         "'$(genDir)/base/base_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/base_jni.srcjar " +
+         "'$(genDir)/base/base_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/base_jni_placeholder.srcjar " +
+         "'$(genDir)/base/base_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ApkAssets_jni.h " +
          "--output-name " +
          "BaseFeatureMap_jni.h " +
          "--output-name " +
-         "BuildInfo_jni.h " +
-         "--output-name " +
          "BundleUtils_jni.h " +
          "--output-name " +
          "CpuFeatures_jni.h " +
@@ -1523,16 +2053,8 @@
          "--output-name " +
          "InputHintChecker_jni.h " +
          "--output-name " +
-         "IntStringCallback_jni.h " +
-         "--output-name " +
-         "JNIUtils_jni.h " +
-         "--output-name " +
-         "JavaExceptionReporter_jni.h " +
-         "--output-name " +
          "JavaHandlerThread_jni.h " +
          "--output-name " +
-         "JniAndroid_jni.h " +
-         "--output-name " +
          "LocaleUtils_jni.h " +
          "--output-name " +
          "PathService_jni.h " +
@@ -1544,66 +2066,44 @@
          "RadioUtils_jni.h " +
          "--output-name " +
          "TimezoneUtils_jni.h " +
-         "--output-name " +
-         "Token_jni.h " +
-         "--output-name " +
-         "TokenBase_jni.h " +
-         "--output-name " +
-         "UnguessableToken_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ApkAssets.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ApkAssets.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/BaseFeatureMap.java) " +
+         "'$(location base/android/java/src/org/chromium/base/BaseFeatureMap.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/BuildInfo.java) " +
+         "'$(location base/android/java/src/org/chromium/base/BundleUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/BundleUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/CpuFeatures.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/CpuFeatures.java) " +
+         "'$(location base/android/java/src/org/chromium/base/EventLog.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/EventLog.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FeatureList.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FeatureList.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FeatureMap.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FeatureMap.java) " +
+         "'$(location base/android/java/src/org/chromium/base/Features.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/Features.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FieldTrialList.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FieldTrialList.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FileUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FileUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ImportantFileWriterAndroid.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ImportantFileWriterAndroid.java) " +
+         "'$(location base/android/java/src/org/chromium/base/InputHintChecker.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/InputHintChecker.java) " +
+         "'$(location base/android/java/src/org/chromium/base/JavaHandlerThread.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/IntStringCallback.java) " +
+         "'$(location base/android/java/src/org/chromium/base/LocaleUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JNIUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/PathService.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JavaExceptionReporter.java) " +
+         "'$(location base/android/java/src/org/chromium/base/PathUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JavaHandlerThread.java) " +
+         "'$(location base/android/java/src/org/chromium/base/PowerMonitor.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JniAndroid.java) " +
+         "'$(location base/android/java/src/org/chromium/base/RadioUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/LocaleUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/PathService.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/PathUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/PowerMonitor.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/RadioUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/TimezoneUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/Token.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/TokenBase.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/UnguessableToken.java) " +
+         "'$(location base/android/java/src/org/chromium/base/TimezoneUtils.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
@@ -1611,7 +2111,6 @@
         "base/base_jni.srcjar",
         "base/base_jni/ApkAssets_jni.h",
         "base/base_jni/BaseFeatureMap_jni.h",
-        "base/base_jni/BuildInfo_jni.h",
         "base/base_jni/BundleUtils_jni.h",
         "base/base_jni/CpuFeatures_jni.h",
         "base/base_jni/EventLog_jni.h",
@@ -1622,20 +2121,14 @@
         "base/base_jni/FileUtils_jni.h",
         "base/base_jni/ImportantFileWriterAndroid_jni.h",
         "base/base_jni/InputHintChecker_jni.h",
-        "base/base_jni/IntStringCallback_jni.h",
-        "base/base_jni/JNIUtils_jni.h",
-        "base/base_jni/JavaExceptionReporter_jni.h",
         "base/base_jni/JavaHandlerThread_jni.h",
-        "base/base_jni/JniAndroid_jni.h",
         "base/base_jni/LocaleUtils_jni.h",
         "base/base_jni/PathService_jni.h",
         "base/base_jni/PathUtils_jni.h",
         "base/base_jni/PowerMonitor_jni.h",
         "base/base_jni/RadioUtils_jni.h",
         "base/base_jni/TimezoneUtils_jni.h",
-        "base/base_jni/TokenBase_jni.h",
-        "base/base_jni/Token_jni.h",
-        "base/base_jni/UnguessableToken_jni.h",
+        "base/base_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -1670,7 +2163,6 @@
     srcs: [
         "base/android/java/src/org/chromium/base/ApkAssets.java",
         "base/android/java/src/org/chromium/base/BaseFeatureMap.java",
-        "base/android/java/src/org/chromium/base/BuildInfo.java",
         "base/android/java/src/org/chromium/base/BundleUtils.java",
         "base/android/java/src/org/chromium/base/CpuFeatures.java",
         "base/android/java/src/org/chromium/base/EventLog.java",
@@ -1686,6 +2178,9 @@
         "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
         "base/android/java/src/org/chromium/base/JavaHandlerThread.java",
         "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
         "base/android/java/src/org/chromium/base/LocaleUtils.java",
         "base/android/java/src/org/chromium/base/PathService.java",
         "base/android/java/src/org/chromium/base/PathUtils.java",
@@ -1697,23 +2192,23 @@
         "base/android/java/src/org/chromium/base/UnguessableToken.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/base_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/base_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/base_jni " +
+         "'$(genDir)/base/base_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/base_jni.srcjar " +
+         "'$(genDir)/base/base_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/base_jni_placeholder.srcjar " +
+         "'$(genDir)/base/base_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ApkAssets_jni.h " +
          "--output-name " +
          "BaseFeatureMap_jni.h " +
          "--output-name " +
-         "BuildInfo_jni.h " +
-         "--output-name " +
          "BundleUtils_jni.h " +
          "--output-name " +
          "CpuFeatures_jni.h " +
@@ -1734,16 +2229,8 @@
          "--output-name " +
          "InputHintChecker_jni.h " +
          "--output-name " +
-         "IntStringCallback_jni.h " +
-         "--output-name " +
-         "JNIUtils_jni.h " +
-         "--output-name " +
-         "JavaExceptionReporter_jni.h " +
-         "--output-name " +
          "JavaHandlerThread_jni.h " +
          "--output-name " +
-         "JniAndroid_jni.h " +
-         "--output-name " +
          "LocaleUtils_jni.h " +
          "--output-name " +
          "PathService_jni.h " +
@@ -1755,73 +2242,50 @@
          "RadioUtils_jni.h " +
          "--output-name " +
          "TimezoneUtils_jni.h " +
-         "--output-name " +
-         "Token_jni.h " +
-         "--output-name " +
-         "TokenBase_jni.h " +
-         "--output-name " +
-         "UnguessableToken_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ApkAssets.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ApkAssets.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/BaseFeatureMap.java) " +
+         "'$(location base/android/java/src/org/chromium/base/BaseFeatureMap.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/BuildInfo.java) " +
+         "'$(location base/android/java/src/org/chromium/base/BundleUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/BundleUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/CpuFeatures.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/CpuFeatures.java) " +
+         "'$(location base/android/java/src/org/chromium/base/EventLog.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/EventLog.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FeatureList.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FeatureList.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FeatureMap.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FeatureMap.java) " +
+         "'$(location base/android/java/src/org/chromium/base/Features.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/Features.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FieldTrialList.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FieldTrialList.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FileUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FileUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ImportantFileWriterAndroid.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ImportantFileWriterAndroid.java) " +
+         "'$(location base/android/java/src/org/chromium/base/InputHintChecker.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/InputHintChecker.java) " +
+         "'$(location base/android/java/src/org/chromium/base/JavaHandlerThread.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/IntStringCallback.java) " +
+         "'$(location base/android/java/src/org/chromium/base/LocaleUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JNIUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/PathService.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JavaExceptionReporter.java) " +
+         "'$(location base/android/java/src/org/chromium/base/PathUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JavaHandlerThread.java) " +
+         "'$(location base/android/java/src/org/chromium/base/PowerMonitor.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JniAndroid.java) " +
+         "'$(location base/android/java/src/org/chromium/base/RadioUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/LocaleUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/PathService.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/PathUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/PowerMonitor.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/RadioUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/TimezoneUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/Token.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/TokenBase.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/UnguessableToken.java) " +
+         "'$(location base/android/java/src/org/chromium/base/TimezoneUtils.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     out: [
         "base/base_jni.srcjar",
         "base/base_jni/ApkAssets_jni.h",
         "base/base_jni/BaseFeatureMap_jni.h",
-        "base/base_jni/BuildInfo_jni.h",
         "base/base_jni/BundleUtils_jni.h",
         "base/base_jni/CpuFeatures_jni.h",
         "base/base_jni/EventLog_jni.h",
@@ -1832,20 +2296,14 @@
         "base/base_jni/FileUtils_jni.h",
         "base/base_jni/ImportantFileWriterAndroid_jni.h",
         "base/base_jni/InputHintChecker_jni.h",
-        "base/base_jni/IntStringCallback_jni.h",
-        "base/base_jni/JNIUtils_jni.h",
-        "base/base_jni/JavaExceptionReporter_jni.h",
         "base/base_jni/JavaHandlerThread_jni.h",
-        "base/base_jni/JniAndroid_jni.h",
         "base/base_jni/LocaleUtils_jni.h",
         "base/base_jni/PathService_jni.h",
         "base/base_jni/PathUtils_jni.h",
         "base/base_jni/PowerMonitor_jni.h",
         "base/base_jni/RadioUtils_jni.h",
         "base/base_jni/TimezoneUtils_jni.h",
-        "base/base_jni/TokenBase_jni.h",
-        "base/base_jni/Token_jni.h",
-        "base/base_jni/UnguessableToken_jni.h",
+        "base/base_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -1877,7 +2335,6 @@
     srcs: [
         "base/android/java/src/org/chromium/base/ApkAssets.java",
         "base/android/java/src/org/chromium/base/BaseFeatureMap.java",
-        "base/android/java/src/org/chromium/base/BuildInfo.java",
         "base/android/java/src/org/chromium/base/BundleUtils.java",
         "base/android/java/src/org/chromium/base/CpuFeatures.java",
         "base/android/java/src/org/chromium/base/EventLog.java",
@@ -1893,6 +2350,9 @@
         "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
         "base/android/java/src/org/chromium/base/JavaHandlerThread.java",
         "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
         "base/android/java/src/org/chromium/base/LocaleUtils.java",
         "base/android/java/src/org/chromium/base/PathService.java",
         "base/android/java/src/org/chromium/base/PathUtils.java",
@@ -1904,23 +2364,23 @@
         "base/android/java/src/org/chromium/base/UnguessableToken.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/base_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/base_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/base_jni " +
+         "'$(genDir)/base/base_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/base_jni.srcjar " +
+         "'$(genDir)/base/base_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/base_jni_placeholder.srcjar " +
+         "'$(genDir)/base/base_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ApkAssets_jni.h " +
          "--output-name " +
          "BaseFeatureMap_jni.h " +
          "--output-name " +
-         "BuildInfo_jni.h " +
-         "--output-name " +
          "BundleUtils_jni.h " +
          "--output-name " +
          "CpuFeatures_jni.h " +
@@ -1941,16 +2401,8 @@
          "--output-name " +
          "InputHintChecker_jni.h " +
          "--output-name " +
-         "IntStringCallback_jni.h " +
-         "--output-name " +
-         "JNIUtils_jni.h " +
-         "--output-name " +
-         "JavaExceptionReporter_jni.h " +
-         "--output-name " +
          "JavaHandlerThread_jni.h " +
          "--output-name " +
-         "JniAndroid_jni.h " +
-         "--output-name " +
          "LocaleUtils_jni.h " +
          "--output-name " +
          "PathService_jni.h " +
@@ -1962,72 +2414,49 @@
          "RadioUtils_jni.h " +
          "--output-name " +
          "TimezoneUtils_jni.h " +
-         "--output-name " +
-         "Token_jni.h " +
-         "--output-name " +
-         "TokenBase_jni.h " +
-         "--output-name " +
-         "UnguessableToken_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ApkAssets.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ApkAssets.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/BaseFeatureMap.java) " +
+         "'$(location base/android/java/src/org/chromium/base/BaseFeatureMap.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/BuildInfo.java) " +
+         "'$(location base/android/java/src/org/chromium/base/BundleUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/BundleUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/CpuFeatures.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/CpuFeatures.java) " +
+         "'$(location base/android/java/src/org/chromium/base/EventLog.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/EventLog.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FeatureList.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FeatureList.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FeatureMap.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FeatureMap.java) " +
+         "'$(location base/android/java/src/org/chromium/base/Features.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/Features.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FieldTrialList.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FieldTrialList.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FileUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FileUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ImportantFileWriterAndroid.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ImportantFileWriterAndroid.java) " +
+         "'$(location base/android/java/src/org/chromium/base/InputHintChecker.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/InputHintChecker.java) " +
+         "'$(location base/android/java/src/org/chromium/base/JavaHandlerThread.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/IntStringCallback.java) " +
+         "'$(location base/android/java/src/org/chromium/base/LocaleUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JNIUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/PathService.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JavaExceptionReporter.java) " +
+         "'$(location base/android/java/src/org/chromium/base/PathUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JavaHandlerThread.java) " +
+         "'$(location base/android/java/src/org/chromium/base/PowerMonitor.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JniAndroid.java) " +
+         "'$(location base/android/java/src/org/chromium/base/RadioUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/LocaleUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/PathService.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/PathUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/PowerMonitor.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/RadioUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/TimezoneUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/Token.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/TokenBase.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/UnguessableToken.java)",
+         "'$(location base/android/java/src/org/chromium/base/TimezoneUtils.java)'",
     host_cross_supported: false,
     out: [
         "base/base_jni.srcjar",
         "base/base_jni/ApkAssets_jni.h",
         "base/base_jni/BaseFeatureMap_jni.h",
-        "base/base_jni/BuildInfo_jni.h",
         "base/base_jni/BundleUtils_jni.h",
         "base/base_jni/CpuFeatures_jni.h",
         "base/base_jni/EventLog_jni.h",
@@ -2038,20 +2467,14 @@
         "base/base_jni/FileUtils_jni.h",
         "base/base_jni/ImportantFileWriterAndroid_jni.h",
         "base/base_jni/InputHintChecker_jni.h",
-        "base/base_jni/IntStringCallback_jni.h",
-        "base/base_jni/JNIUtils_jni.h",
-        "base/base_jni/JavaExceptionReporter_jni.h",
         "base/base_jni/JavaHandlerThread_jni.h",
-        "base/base_jni/JniAndroid_jni.h",
         "base/base_jni/LocaleUtils_jni.h",
         "base/base_jni/PathService_jni.h",
         "base/base_jni/PathUtils_jni.h",
         "base/base_jni/PowerMonitor_jni.h",
         "base/base_jni/RadioUtils_jni.h",
         "base/base_jni/TimezoneUtils_jni.h",
-        "base/base_jni/TokenBase_jni.h",
-        "base/base_jni/Token_jni.h",
-        "base/base_jni/UnguessableToken_jni.h",
+        "base/base_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -2086,7 +2509,6 @@
     srcs: [
         "base/android/java/src/org/chromium/base/ApkAssets.java",
         "base/android/java/src/org/chromium/base/BaseFeatureMap.java",
-        "base/android/java/src/org/chromium/base/BuildInfo.java",
         "base/android/java/src/org/chromium/base/BundleUtils.java",
         "base/android/java/src/org/chromium/base/CpuFeatures.java",
         "base/android/java/src/org/chromium/base/EventLog.java",
@@ -2102,6 +2524,9 @@
         "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
         "base/android/java/src/org/chromium/base/JavaHandlerThread.java",
         "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
         "base/android/java/src/org/chromium/base/LocaleUtils.java",
         "base/android/java/src/org/chromium/base/PathService.java",
         "base/android/java/src/org/chromium/base/PathUtils.java",
@@ -2113,23 +2538,23 @@
         "base/android/java/src/org/chromium/base/UnguessableToken.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/base_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/base_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/base_jni " +
+         "'$(genDir)/base/base_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/base_jni.srcjar " +
+         "'$(genDir)/base/base_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/base_jni_placeholder.srcjar " +
+         "'$(genDir)/base/base_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ApkAssets_jni.h " +
          "--output-name " +
          "BaseFeatureMap_jni.h " +
          "--output-name " +
-         "BuildInfo_jni.h " +
-         "--output-name " +
          "BundleUtils_jni.h " +
          "--output-name " +
          "CpuFeatures_jni.h " +
@@ -2150,16 +2575,8 @@
          "--output-name " +
          "InputHintChecker_jni.h " +
          "--output-name " +
-         "IntStringCallback_jni.h " +
-         "--output-name " +
-         "JNIUtils_jni.h " +
-         "--output-name " +
-         "JavaExceptionReporter_jni.h " +
-         "--output-name " +
          "JavaHandlerThread_jni.h " +
          "--output-name " +
-         "JniAndroid_jni.h " +
-         "--output-name " +
          "LocaleUtils_jni.h " +
          "--output-name " +
          "PathService_jni.h " +
@@ -2171,71 +2588,48 @@
          "RadioUtils_jni.h " +
          "--output-name " +
          "TimezoneUtils_jni.h " +
-         "--output-name " +
-         "Token_jni.h " +
-         "--output-name " +
-         "TokenBase_jni.h " +
-         "--output-name " +
-         "UnguessableToken_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ApkAssets.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ApkAssets.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/BaseFeatureMap.java) " +
+         "'$(location base/android/java/src/org/chromium/base/BaseFeatureMap.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/BuildInfo.java) " +
+         "'$(location base/android/java/src/org/chromium/base/BundleUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/BundleUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/CpuFeatures.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/CpuFeatures.java) " +
+         "'$(location base/android/java/src/org/chromium/base/EventLog.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/EventLog.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FeatureList.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FeatureList.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FeatureMap.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FeatureMap.java) " +
+         "'$(location base/android/java/src/org/chromium/base/Features.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/Features.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FieldTrialList.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FieldTrialList.java) " +
+         "'$(location base/android/java/src/org/chromium/base/FileUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/FileUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ImportantFileWriterAndroid.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ImportantFileWriterAndroid.java) " +
+         "'$(location base/android/java/src/org/chromium/base/InputHintChecker.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/InputHintChecker.java) " +
+         "'$(location base/android/java/src/org/chromium/base/JavaHandlerThread.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/IntStringCallback.java) " +
+         "'$(location base/android/java/src/org/chromium/base/LocaleUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JNIUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/PathService.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JavaExceptionReporter.java) " +
+         "'$(location base/android/java/src/org/chromium/base/PathUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JavaHandlerThread.java) " +
+         "'$(location base/android/java/src/org/chromium/base/PowerMonitor.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/JniAndroid.java) " +
+         "'$(location base/android/java/src/org/chromium/base/RadioUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/LocaleUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/PathService.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/PathUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/PowerMonitor.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/RadioUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/TimezoneUtils.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/Token.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/TokenBase.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/UnguessableToken.java)",
+         "'$(location base/android/java/src/org/chromium/base/TimezoneUtils.java)'",
     out: [
         "base/base_jni.srcjar",
         "base/base_jni/ApkAssets_jni.h",
         "base/base_jni/BaseFeatureMap_jni.h",
-        "base/base_jni/BuildInfo_jni.h",
         "base/base_jni/BundleUtils_jni.h",
         "base/base_jni/CpuFeatures_jni.h",
         "base/base_jni/EventLog_jni.h",
@@ -2246,20 +2640,14 @@
         "base/base_jni/FileUtils_jni.h",
         "base/base_jni/ImportantFileWriterAndroid_jni.h",
         "base/base_jni/InputHintChecker_jni.h",
-        "base/base_jni/IntStringCallback_jni.h",
-        "base/base_jni/JNIUtils_jni.h",
-        "base/base_jni/JavaExceptionReporter_jni.h",
         "base/base_jni/JavaHandlerThread_jni.h",
-        "base/base_jni/JniAndroid_jni.h",
         "base/base_jni/LocaleUtils_jni.h",
         "base/base_jni/PathService_jni.h",
         "base/base_jni/PathUtils_jni.h",
         "base/base_jni/PowerMonitor_jni.h",
         "base/base_jni/RadioUtils_jni.h",
         "base/base_jni/TimezoneUtils_jni.h",
-        "base/base_jni/TokenBase_jni.h",
-        "base/base_jni/Token_jni.h",
-        "base/base_jni/UnguessableToken_jni.h",
+        "base/base_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -2285,6 +2673,606 @@
     ],
 }
 
+// GN: //base:base_jni_java__process_device
+java_genrule {
+    name: "tot_cronet_base_base_jni_java__process_device",
+    srcs: [
+        ":tot_cronet_base_base_jni_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/base_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_jni_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_base_jni_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_base_jni_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/base_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_minimal_jni__action
+cc_genrule {
+    name: "tot_cronet_base_base_minimal_jni__action",
+    srcs: [
+        "base/android/java/src/org/chromium/base/IntStringCallback.java",
+        "base/android/java/src/org/chromium/base/JNIUtils.java",
+        "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
+        "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
+        "base/android/java/src/org/chromium/base/Token.java",
+        "base/android/java/src/org/chromium/base/TokenBase.java",
+        "base/android/java/src/org/chromium/base/UnguessableToken.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/base_minimal_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/base_minimal_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/base_minimal_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/base_minimal_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--enable-definition-macros " +
+         "--output-name " +
+         "IntStringCallback_jni.h " +
+         "--output-name " +
+         "JNIUtils_jni.h " +
+         "--output-name " +
+         "JavaExceptionReporter_jni.h " +
+         "--output-name " +
+         "JniAndroid_jni.h " +
+         "--output-name " +
+         "JniCallbackUtils_jni.h " +
+         "--output-name " +
+         "JniOnceCallback_jni.h " +
+         "--output-name " +
+         "JniRepeatingCallback_jni.h " +
+         "--output-name " +
+         "Token_jni.h " +
+         "--output-name " +
+         "TokenBase_jni.h " +
+         "--output-name " +
+         "UnguessableToken_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/IntStringCallback.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JNIUtils.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JavaExceptionReporter.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniAndroid.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniCallbackUtils.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniOnceCallback.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniRepeatingCallback.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/Token.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/TokenBase.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/UnguessableToken.java)' " +
+         "--package-prefix " +
+         "android.net.connectivity",
+    host_cross_supported: false,
+    out: [
+        "base/base_minimal_jni.srcjar",
+        "base/base_minimal_jni/IntStringCallback_jni.h",
+        "base/base_minimal_jni/JNIUtils_jni.h",
+        "base/base_minimal_jni/JavaExceptionReporter_jni.h",
+        "base/base_minimal_jni/JniAndroid_jni.h",
+        "base/base_minimal_jni/JniCallbackUtils_jni.h",
+        "base/base_minimal_jni/JniOnceCallback_jni.h",
+        "base/base_minimal_jni/JniRepeatingCallback_jni.h",
+        "base/base_minimal_jni/TokenBase_jni.h",
+        "base/base_minimal_jni/Token_jni.h",
+        "base/base_minimal_jni/UnguessableToken_jni.h",
+        "base/base_minimal_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_minimal_jni__action
+java_genrule {
+    name: "tot_cronet_base_base_minimal_jni__action__java",
+    srcs: [
+        "base/android/java/src/org/chromium/base/IntStringCallback.java",
+        "base/android/java/src/org/chromium/base/JNIUtils.java",
+        "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
+        "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
+        "base/android/java/src/org/chromium/base/Token.java",
+        "base/android/java/src/org/chromium/base/TokenBase.java",
+        "base/android/java/src/org/chromium/base/UnguessableToken.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/base_minimal_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/base_minimal_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/base_minimal_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/base_minimal_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--enable-definition-macros " +
+         "--output-name " +
+         "IntStringCallback_jni.h " +
+         "--output-name " +
+         "JNIUtils_jni.h " +
+         "--output-name " +
+         "JavaExceptionReporter_jni.h " +
+         "--output-name " +
+         "JniAndroid_jni.h " +
+         "--output-name " +
+         "JniCallbackUtils_jni.h " +
+         "--output-name " +
+         "JniOnceCallback_jni.h " +
+         "--output-name " +
+         "JniRepeatingCallback_jni.h " +
+         "--output-name " +
+         "Token_jni.h " +
+         "--output-name " +
+         "TokenBase_jni.h " +
+         "--output-name " +
+         "UnguessableToken_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/IntStringCallback.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JNIUtils.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JavaExceptionReporter.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniAndroid.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniCallbackUtils.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniOnceCallback.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniRepeatingCallback.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/Token.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/TokenBase.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/UnguessableToken.java)' " +
+         "--package-prefix " +
+         "android.net.connectivity",
+    out: [
+        "base/base_minimal_jni.srcjar",
+        "base/base_minimal_jni/IntStringCallback_jni.h",
+        "base/base_minimal_jni/JNIUtils_jni.h",
+        "base/base_minimal_jni/JavaExceptionReporter_jni.h",
+        "base/base_minimal_jni/JniAndroid_jni.h",
+        "base/base_minimal_jni/JniCallbackUtils_jni.h",
+        "base/base_minimal_jni/JniOnceCallback_jni.h",
+        "base/base_minimal_jni/JniRepeatingCallback_jni.h",
+        "base/base_minimal_jni/TokenBase_jni.h",
+        "base/base_minimal_jni/Token_jni.h",
+        "base/base_minimal_jni/UnguessableToken_jni.h",
+        "base/base_minimal_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_minimal_jni__action__testing
+cc_genrule {
+    name: "tot_cronet_base_base_minimal_jni__action__testing",
+    srcs: [
+        "base/android/java/src/org/chromium/base/IntStringCallback.java",
+        "base/android/java/src/org/chromium/base/JNIUtils.java",
+        "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
+        "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
+        "base/android/java/src/org/chromium/base/Token.java",
+        "base/android/java/src/org/chromium/base/TokenBase.java",
+        "base/android/java/src/org/chromium/base/UnguessableToken.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/base_minimal_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/base_minimal_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/base_minimal_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/base_minimal_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--enable-definition-macros " +
+         "--output-name " +
+         "IntStringCallback_jni.h " +
+         "--output-name " +
+         "JNIUtils_jni.h " +
+         "--output-name " +
+         "JavaExceptionReporter_jni.h " +
+         "--output-name " +
+         "JniAndroid_jni.h " +
+         "--output-name " +
+         "JniCallbackUtils_jni.h " +
+         "--output-name " +
+         "JniOnceCallback_jni.h " +
+         "--output-name " +
+         "JniRepeatingCallback_jni.h " +
+         "--output-name " +
+         "Token_jni.h " +
+         "--output-name " +
+         "TokenBase_jni.h " +
+         "--output-name " +
+         "UnguessableToken_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/IntStringCallback.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JNIUtils.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JavaExceptionReporter.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniAndroid.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniCallbackUtils.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniOnceCallback.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniRepeatingCallback.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/Token.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/TokenBase.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/UnguessableToken.java)'",
+    host_cross_supported: false,
+    out: [
+        "base/base_minimal_jni.srcjar",
+        "base/base_minimal_jni/IntStringCallback_jni.h",
+        "base/base_minimal_jni/JNIUtils_jni.h",
+        "base/base_minimal_jni/JavaExceptionReporter_jni.h",
+        "base/base_minimal_jni/JniAndroid_jni.h",
+        "base/base_minimal_jni/JniCallbackUtils_jni.h",
+        "base/base_minimal_jni/JniOnceCallback_jni.h",
+        "base/base_minimal_jni/JniRepeatingCallback_jni.h",
+        "base/base_minimal_jni/TokenBase_jni.h",
+        "base/base_minimal_jni/Token_jni.h",
+        "base/base_minimal_jni/UnguessableToken_jni.h",
+        "base/base_minimal_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_minimal_jni__action__testing
+java_genrule {
+    name: "tot_cronet_base_base_minimal_jni__action__testing__java",
+    srcs: [
+        "base/android/java/src/org/chromium/base/IntStringCallback.java",
+        "base/android/java/src/org/chromium/base/JNIUtils.java",
+        "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
+        "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
+        "base/android/java/src/org/chromium/base/Token.java",
+        "base/android/java/src/org/chromium/base/TokenBase.java",
+        "base/android/java/src/org/chromium/base/UnguessableToken.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/base_minimal_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/base_minimal_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/base_minimal_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/base_minimal_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--enable-definition-macros " +
+         "--output-name " +
+         "IntStringCallback_jni.h " +
+         "--output-name " +
+         "JNIUtils_jni.h " +
+         "--output-name " +
+         "JavaExceptionReporter_jni.h " +
+         "--output-name " +
+         "JniAndroid_jni.h " +
+         "--output-name " +
+         "JniCallbackUtils_jni.h " +
+         "--output-name " +
+         "JniOnceCallback_jni.h " +
+         "--output-name " +
+         "JniRepeatingCallback_jni.h " +
+         "--output-name " +
+         "Token_jni.h " +
+         "--output-name " +
+         "TokenBase_jni.h " +
+         "--output-name " +
+         "UnguessableToken_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/IntStringCallback.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JNIUtils.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JavaExceptionReporter.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniAndroid.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniCallbackUtils.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniOnceCallback.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/JniRepeatingCallback.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/Token.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/TokenBase.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/UnguessableToken.java)'",
+    out: [
+        "base/base_minimal_jni.srcjar",
+        "base/base_minimal_jni/IntStringCallback_jni.h",
+        "base/base_minimal_jni/JNIUtils_jni.h",
+        "base/base_minimal_jni/JavaExceptionReporter_jni.h",
+        "base/base_minimal_jni/JniAndroid_jni.h",
+        "base/base_minimal_jni/JniCallbackUtils_jni.h",
+        "base/base_minimal_jni/JniOnceCallback_jni.h",
+        "base/base_minimal_jni/JniRepeatingCallback_jni.h",
+        "base/base_minimal_jni/TokenBase_jni.h",
+        "base/base_minimal_jni/Token_jni.h",
+        "base/base_minimal_jni/UnguessableToken_jni.h",
+        "base/base_minimal_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_minimal_jni_java__process_device
+java_genrule {
+    name: "tot_cronet_base_base_minimal_jni_java__process_device",
+    srcs: [
+        ":tot_cronet_base_base_minimal_jni_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/base_minimal_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_minimal_jni_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_base_minimal_jni_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_base_minimal_jni_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/base_minimal_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_shared_preferences_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_base_shared_preferences_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_base_shared_preferences_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/base_shared_preferences_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:base_shared_preferences_jni__action
 cc_genrule {
     name: "tot_cronet_base_base_shared_preferences_jni__action",
@@ -2292,26 +3280,29 @@
         "base/android/java/src/org/chromium/base/shared_preferences/SharedPreferencesManager.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/base_shared_preferences_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/base_shared_preferences_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/base_shared_preferences_jni " +
+         "'$(genDir)/base/base_shared_preferences_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/base_shared_preferences_jni.srcjar " +
+         "'$(genDir)/base/base_shared_preferences_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/base_shared_preferences_jni_placeholder.srcjar " +
+         "'$(genDir)/base/base_shared_preferences_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "SharedPreferencesManager_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/shared_preferences/SharedPreferencesManager.java) " +
+         "'$(location base/android/java/src/org/chromium/base/shared_preferences/SharedPreferencesManager.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
     out: [
         "base/base_shared_preferences_jni.srcjar",
         "base/base_shared_preferences_jni/SharedPreferencesManager_jni.h",
+        "base/base_shared_preferences_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -2347,24 +3338,27 @@
         "base/android/java/src/org/chromium/base/shared_preferences/SharedPreferencesManager.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/base_shared_preferences_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/base_shared_preferences_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/base_shared_preferences_jni " +
+         "'$(genDir)/base/base_shared_preferences_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/base_shared_preferences_jni.srcjar " +
+         "'$(genDir)/base/base_shared_preferences_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/base_shared_preferences_jni_placeholder.srcjar " +
+         "'$(genDir)/base/base_shared_preferences_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "SharedPreferencesManager_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/shared_preferences/SharedPreferencesManager.java)",
+         "'$(location base/android/java/src/org/chromium/base/shared_preferences/SharedPreferencesManager.java)'",
     host_cross_supported: false,
     out: [
         "base/base_shared_preferences_jni.srcjar",
         "base/base_shared_preferences_jni/SharedPreferencesManager_jni.h",
+        "base/base_shared_preferences_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -2393,11 +3387,161 @@
     ],
 }
 
+// GN: //base:base_shared_preferences_jni__action__testing
+java_genrule {
+    name: "tot_cronet_base_base_shared_preferences_jni__action__testing__java",
+    srcs: [
+        "base/android/java/src/org/chromium/base/shared_preferences/SharedPreferencesManager.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/base_shared_preferences_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/base_shared_preferences_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/base_shared_preferences_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/base_shared_preferences_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "SharedPreferencesManager_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/shared_preferences/SharedPreferencesManager.java)'",
+    out: [
+        "base/base_shared_preferences_jni.srcjar",
+        "base/base_shared_preferences_jni/SharedPreferencesManager_jni.h",
+        "base/base_shared_preferences_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_shared_preferences_jni_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_base_shared_preferences_jni_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_base_shared_preferences_jni_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/base_shared_preferences_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_switches_java__process_device
+java_genrule {
+    name: "tot_cronet_base_base_switches_java__process_device",
+    srcs: [
+        ":tot_cronet_base_base_switches_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/base_switches_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_switches_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_base_switches_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_base_switches_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/base_switches_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:build_date
 cc_genrule {
     name: "tot_cronet_base_build_date",
-    cmd: "mkdir -p $(genDir)/base && $(location base/write_build_date_header.py) $(out) " +
-         "1740501589",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location base/write_build_date_header.py) " +
+         "'$(out)' " +
+         "1742822436",
     host_cross_supported: false,
     out: [
         "base/generated_build_date.h",
@@ -2416,8 +3560,10 @@
 // GN: //base:build_date__testing
 cc_genrule {
     name: "tot_cronet_base_build_date__testing",
-    cmd: "mkdir -p $(genDir)/base && $(location base/write_build_date_header.py) $(out) " +
-         "1740501589",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location base/write_build_date_header.py) " +
+         "'$(out)' " +
+         "1742822436",
     host_supported: true,
     host_cross_supported: false,
     out: [
@@ -2434,6 +3580,426 @@
     ],
 }
 
+// GN: //base:build_info_java__process_device
+java_genrule {
+    name: "tot_cronet_base_build_info_java__process_device",
+    srcs: [
+        ":tot_cronet_base_build_info_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/build_info_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:build_info_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_build_info_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_build_info_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/build_info_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:build_info_jni__action
+cc_genrule {
+    name: "tot_cronet_base_build_info_jni__action",
+    srcs: [
+        "base/android/java/src/org/chromium/base/ApkInfo.java",
+        "base/android/java/src/org/chromium/base/BuildInfo.java",
+        "base/android/java/src/org/chromium/base/DeviceInfo.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/build_info_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/build_info_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/build_info_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/build_info_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "ApkInfo_jni.h " +
+         "--output-name " +
+         "BuildInfo_jni.h " +
+         "--output-name " +
+         "DeviceInfo_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/ApkInfo.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/BuildInfo.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/DeviceInfo.java)' " +
+         "--package-prefix " +
+         "android.net.connectivity",
+    host_cross_supported: false,
+    out: [
+        "base/build_info_jni.srcjar",
+        "base/build_info_jni/ApkInfo_jni.h",
+        "base/build_info_jni/BuildInfo_jni.h",
+        "base/build_info_jni/DeviceInfo_jni.h",
+        "base/build_info_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:build_info_jni__action
+java_genrule {
+    name: "tot_cronet_base_build_info_jni__action__java",
+    srcs: [
+        "base/android/java/src/org/chromium/base/ApkInfo.java",
+        "base/android/java/src/org/chromium/base/BuildInfo.java",
+        "base/android/java/src/org/chromium/base/DeviceInfo.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/build_info_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/build_info_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/build_info_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/build_info_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "ApkInfo_jni.h " +
+         "--output-name " +
+         "BuildInfo_jni.h " +
+         "--output-name " +
+         "DeviceInfo_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/ApkInfo.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/BuildInfo.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/DeviceInfo.java)' " +
+         "--package-prefix " +
+         "android.net.connectivity",
+    out: [
+        "base/build_info_jni.srcjar",
+        "base/build_info_jni/ApkInfo_jni.h",
+        "base/build_info_jni/BuildInfo_jni.h",
+        "base/build_info_jni/DeviceInfo_jni.h",
+        "base/build_info_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:build_info_jni__action
+java_genrule {
+    name: "tot_cronet_base_build_info_jni__action__java_proxy_only",
+    srcs: [
+        ":tot_cronet_base_build_info_jni__action__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "build_info_jni.srcjar",
+    ],
+}
+
+// GN: //base:build_info_jni__action__testing
+cc_genrule {
+    name: "tot_cronet_base_build_info_jni__action__testing",
+    srcs: [
+        "base/android/java/src/org/chromium/base/ApkInfo.java",
+        "base/android/java/src/org/chromium/base/BuildInfo.java",
+        "base/android/java/src/org/chromium/base/DeviceInfo.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/build_info_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/build_info_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/build_info_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/build_info_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "ApkInfo_jni.h " +
+         "--output-name " +
+         "BuildInfo_jni.h " +
+         "--output-name " +
+         "DeviceInfo_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/ApkInfo.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/BuildInfo.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/DeviceInfo.java)'",
+    host_cross_supported: false,
+    out: [
+        "base/build_info_jni.srcjar",
+        "base/build_info_jni/ApkInfo_jni.h",
+        "base/build_info_jni/BuildInfo_jni.h",
+        "base/build_info_jni/DeviceInfo_jni.h",
+        "base/build_info_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:build_info_jni__action__testing
+java_genrule {
+    name: "tot_cronet_base_build_info_jni__action__testing__java",
+    srcs: [
+        "base/android/java/src/org/chromium/base/ApkInfo.java",
+        "base/android/java/src/org/chromium/base/BuildInfo.java",
+        "base/android/java/src/org/chromium/base/DeviceInfo.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/build_info_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/build_info_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/build_info_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/build_info_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "ApkInfo_jni.h " +
+         "--output-name " +
+         "BuildInfo_jni.h " +
+         "--output-name " +
+         "DeviceInfo_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/ApkInfo.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/BuildInfo.java)' " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/DeviceInfo.java)'",
+    out: [
+        "base/build_info_jni.srcjar",
+        "base/build_info_jni/ApkInfo_jni.h",
+        "base/build_info_jni/BuildInfo_jni.h",
+        "base/build_info_jni/DeviceInfo_jni.h",
+        "base/build_info_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:build_info_jni__action__testing
+java_genrule {
+    name: "tot_cronet_base_build_info_jni__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_base_build_info_jni__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "build_info_jni.srcjar",
+    ],
+}
+
+// GN: //base:callback_java__process_device
+java_genrule {
+    name: "tot_cronet_base_callback_java__process_device",
+    srcs: [
+        ":tot_cronet_base_callback_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/callback_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:callback_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_callback_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_callback_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/callback_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:callback_jni__action
 cc_genrule {
     name: "tot_cronet_base_callback_jni__action",
@@ -2441,26 +4007,139 @@
         "base/android/java/src/org/chromium/base/Callback.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/callback_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/callback_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/callback_jni " +
+         "'$(genDir)/base/callback_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/callback_jni.srcjar " +
+         "'$(genDir)/base/callback_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/callback_jni_placeholder.srcjar " +
+         "'$(genDir)/base/callback_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "Callback_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/Callback.java) " +
+         "'$(location base/android/java/src/org/chromium/base/Callback.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
     out: [
         "base/callback_jni.srcjar",
         "base/callback_jni/Callback_jni.h",
+        "base/callback_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:callback_jni__action
+java_genrule {
+    name: "tot_cronet_base_callback_jni__action__java",
+    srcs: [
+        "base/android/java/src/org/chromium/base/Callback.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/callback_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/callback_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/callback_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/callback_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "Callback_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/Callback.java)' " +
+         "--package-prefix " +
+         "android.net.connectivity",
+    out: [
+        "base/callback_jni.srcjar",
+        "base/callback_jni/Callback_jni.h",
+        "base/callback_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:callback_jni__action__testing
+cc_genrule {
+    name: "tot_cronet_base_callback_jni__action__testing",
+    srcs: [
+        "base/android/java/src/org/chromium/base/Callback.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/callback_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/callback_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/callback_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/callback_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "Callback_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/Callback.java)'",
+    host_cross_supported: false,
+    out: [
+        "base/callback_jni.srcjar",
+        "base/callback_jni/Callback_jni.h",
+        "base/callback_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -2490,30 +4169,32 @@
 }
 
 // GN: //base:callback_jni__action__testing
-cc_genrule {
-    name: "tot_cronet_base_callback_jni__action__testing",
+java_genrule {
+    name: "tot_cronet_base_callback_jni__action__testing__java",
     srcs: [
         "base/android/java/src/org/chromium/base/Callback.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/callback_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/callback_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/callback_jni " +
+         "'$(genDir)/base/callback_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/callback_jni.srcjar " +
+         "'$(genDir)/base/callback_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/callback_jni_placeholder.srcjar " +
+         "'$(genDir)/base/callback_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "Callback_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/Callback.java)",
-    host_cross_supported: false,
+         "'$(location base/android/java/src/org/chromium/base/Callback.java)'",
     out: [
         "base/callback_jni.srcjar",
         "base/callback_jni/Callback_jni.h",
+        "base/callback_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -2534,8 +4215,69 @@
         "third_party/jni_zero/parse.py",
         "third_party/jni_zero/proxy.py",
     ],
-    apex_available: [
-        "com.android.tethering",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:callback_jni_java__process_device
+java_genrule {
+    name: "tot_cronet_base_callback_jni_java__process_device",
+    srcs: [
+        ":tot_cronet_base_callback_jni_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/callback_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:callback_jni_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_callback_jni_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_callback_jni_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/callback_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
     ],
     visibility: [
         "//external/cronet:__subpackages__",
@@ -2545,9 +4287,11 @@
 // GN: //base:cfi_buildflags
 cc_genrule {
     name: "tot_cronet_base_cfi_buildflags",
-    cmd: "mkdir -p $(genDir)/base && echo '--flags CFI_CAST_CHECK=\"false && false\" CFI_DIAG=\"false && false\" CFI_ICALL_CHECK=\"false && false\" CFI_ENFORCEMENT_TRAP=\"false && !false\" CFI_ENFORCEMENT_DIAGNOSTIC=\"false && false && !false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags '\"'\"'CFI_CAST_CHECK=false && false'\"'\"' '\"'\"'CFI_DIAG=false && false'\"'\"' '\"'\"'CFI_ICALL_CHECK=false && false'\"'\"' '\"'\"'CFI_ENFORCEMENT_TRAP=false && !false'\"'\"' '\"'\"'CFI_ENFORCEMENT_DIAGNOSTIC=false && false && !false'\"'\"'' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:cfi_buildflags " +
          "--gen-dir " +
@@ -2572,9 +4316,11 @@
 // GN: //base:cfi_buildflags__testing
 cc_genrule {
     name: "tot_cronet_base_cfi_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/base && echo '--flags CFI_CAST_CHECK=\"false && false\" CFI_DIAG=\"false && false\" CFI_ICALL_CHECK=\"false && false\" CFI_ENFORCEMENT_TRAP=\"false && !false\" CFI_ENFORCEMENT_DIAGNOSTIC=\"false && false && !false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags '\"'\"'CFI_CAST_CHECK=false && false'\"'\"' '\"'\"'CFI_DIAG=false && false'\"'\"' '\"'\"'CFI_ICALL_CHECK=false && false'\"'\"' '\"'\"'CFI_ENFORCEMENT_TRAP=false && !false'\"'\"' '\"'\"'CFI_ENFORCEMENT_DIAGNOSTIC=false && false && !false'\"'\"'' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:cfi_buildflags " +
          "--gen-dir " +
@@ -2600,16 +4346,18 @@
 // GN: //base:check_version_internal_action
 cc_genrule {
     name: "tot_cronet_base_check_version_internal_action",
-    cmd: "mkdir -p $(genDir)/base && $(location build/util/version.py) --official " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/util/version.py) " +
+         "--official " +
          "-f " +
-         "$(location chrome/VERSION) " +
+         "'$(location chrome/VERSION)' " +
          "-e " +
          "'VERSION_MAJOR=\"%s\" % (MAJOR)' " +
          "-e " +
          "'NEXT_VERSION_MAJOR=\"%d\" % (int(MAJOR) + 1)' " +
          "-o " +
-         "$(out) " +
-         "$(location base/check_version_internal.h.in)",
+         "'$(out)' " +
+         "'$(location base/check_version_internal.h.in)'",
     host_cross_supported: false,
     out: [
         "base/check_version_internal.h",
@@ -2632,16 +4380,18 @@
 // GN: //base:check_version_internal_action__testing
 cc_genrule {
     name: "tot_cronet_base_check_version_internal_action__testing",
-    cmd: "mkdir -p $(genDir)/base && $(location build/util/version.py) --official " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/util/version.py) " +
+         "--official " +
          "-f " +
-         "$(location chrome/VERSION) " +
+         "'$(location chrome/VERSION)' " +
          "-e " +
          "'VERSION_MAJOR=\"%s\" % (MAJOR)' " +
          "-e " +
          "'NEXT_VERSION_MAJOR=\"%d\" % (int(MAJOR) + 1)' " +
          "-o " +
-         "$(out) " +
-         "$(location base/check_version_internal.h.in)",
+         "'$(out)' " +
+         "'$(location base/check_version_internal.h.in)'",
     host_supported: true,
     host_cross_supported: false,
     out: [
@@ -2665,9 +4415,11 @@
 // GN: //base:clang_profiling_buildflags
 cc_genrule {
     name: "tot_cronet_base_clang_profiling_buildflags",
-    cmd: "mkdir -p $(genDir)/base && echo '--flags CLANG_PROFILING=\"false\" CLANG_PROFILING_INSIDE_SANDBOX=\"false\" USE_CLANG_COVERAGE=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags CLANG_PROFILING=false CLANG_PROFILING_INSIDE_SANDBOX=false USE_CLANG_COVERAGE=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:clang_profiling_buildflags " +
          "--gen-dir " +
@@ -2692,9 +4444,11 @@
 // GN: //base:clang_profiling_buildflags__testing
 cc_genrule {
     name: "tot_cronet_base_clang_profiling_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/base && echo '--flags CLANG_PROFILING=\"false\" CLANG_PROFILING_INSIDE_SANDBOX=\"false\" USE_CLANG_COVERAGE=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags CLANG_PROFILING=false CLANG_PROFILING_INSIDE_SANDBOX=false USE_CLANG_COVERAGE=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:clang_profiling_buildflags " +
          "--gen-dir " +
@@ -2717,6 +4471,70 @@
     ],
 }
 
+// GN: //base:command_line_java__process_device
+java_genrule {
+    name: "tot_cronet_base_command_line_java__process_device",
+    srcs: [
+        ":tot_cronet_base_command_line_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/command_line_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:command_line_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_command_line_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_command_line_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/command_line_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:command_line_jni__action
 cc_genrule {
     name: "tot_cronet_base_command_line_jni__action",
@@ -2724,26 +4542,29 @@
         "base/android/java/src/org/chromium/base/CommandLine.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/command_line_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/command_line_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/command_line_jni " +
+         "'$(genDir)/base/command_line_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/command_line_jni.srcjar " +
+         "'$(genDir)/base/command_line_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/command_line_jni_placeholder.srcjar " +
+         "'$(genDir)/base/command_line_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "CommandLine_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/CommandLine.java) " +
+         "'$(location base/android/java/src/org/chromium/base/CommandLine.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
     out: [
         "base/command_line_jni.srcjar",
         "base/command_line_jni/CommandLine_jni.h",
+        "base/command_line_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -2779,25 +4600,28 @@
         "base/android/java/src/org/chromium/base/CommandLine.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/command_line_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/command_line_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/command_line_jni " +
+         "'$(genDir)/base/command_line_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/command_line_jni.srcjar " +
+         "'$(genDir)/base/command_line_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/command_line_jni_placeholder.srcjar " +
+         "'$(genDir)/base/command_line_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "CommandLine_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/CommandLine.java) " +
+         "'$(location base/android/java/src/org/chromium/base/CommandLine.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     out: [
         "base/command_line_jni.srcjar",
         "base/command_line_jni/CommandLine_jni.h",
+        "base/command_line_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -2830,24 +4654,27 @@
         "base/android/java/src/org/chromium/base/CommandLine.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/command_line_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/command_line_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/command_line_jni " +
+         "'$(genDir)/base/command_line_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/command_line_jni.srcjar " +
+         "'$(genDir)/base/command_line_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/command_line_jni_placeholder.srcjar " +
+         "'$(genDir)/base/command_line_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "CommandLine_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/CommandLine.java)",
+         "'$(location base/android/java/src/org/chromium/base/CommandLine.java)'",
     host_cross_supported: false,
     out: [
         "base/command_line_jni.srcjar",
         "base/command_line_jni/CommandLine_jni.h",
+        "base/command_line_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -2883,23 +4710,26 @@
         "base/android/java/src/org/chromium/base/CommandLine.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/command_line_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/command_line_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/command_line_jni " +
+         "'$(genDir)/base/command_line_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/command_line_jni.srcjar " +
+         "'$(genDir)/base/command_line_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/command_line_jni_placeholder.srcjar " +
+         "'$(genDir)/base/command_line_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "CommandLine_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/CommandLine.java)",
+         "'$(location base/android/java/src/org/chromium/base/CommandLine.java)'",
     out: [
         "base/command_line_jni.srcjar",
         "base/command_line_jni/CommandLine_jni.h",
+        "base/command_line_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -2925,6 +4755,70 @@
     ],
 }
 
+// GN: //base:command_line_jni_java__process_device
+java_genrule {
+    name: "tot_cronet_base_command_line_jni_java__process_device",
+    srcs: [
+        ":tot_cronet_base_command_line_jni_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/command_line_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:command_line_jni_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_command_line_jni_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_command_line_jni_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/command_line_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:content_uri_utils_jni__action
 cc_genrule {
     name: "tot_cronet_base_content_uri_utils_jni__action",
@@ -2932,26 +4826,29 @@
         "base/android/java/src/org/chromium/base/ContentUriUtils.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/content_uri_utils_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/content_uri_utils_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/content_uri_utils_jni " +
+         "'$(genDir)/base/content_uri_utils_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/content_uri_utils_jni.srcjar " +
+         "'$(genDir)/base/content_uri_utils_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/content_uri_utils_jni_placeholder.srcjar " +
+         "'$(genDir)/base/content_uri_utils_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ContentUriUtils_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ContentUriUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ContentUriUtils.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
     out: [
         "base/content_uri_utils_jni.srcjar",
         "base/content_uri_utils_jni/ContentUriUtils_jni.h",
+        "base/content_uri_utils_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -2987,24 +4884,27 @@
         "base/android/java/src/org/chromium/base/ContentUriUtils.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/content_uri_utils_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/content_uri_utils_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/content_uri_utils_jni " +
+         "'$(genDir)/base/content_uri_utils_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/content_uri_utils_jni.srcjar " +
+         "'$(genDir)/base/content_uri_utils_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/content_uri_utils_jni_placeholder.srcjar " +
+         "'$(genDir)/base/content_uri_utils_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ContentUriUtils_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ContentUriUtils.java)",
+         "'$(location base/android/java/src/org/chromium/base/ContentUriUtils.java)'",
     host_cross_supported: false,
     out: [
         "base/content_uri_utils_jni.srcjar",
         "base/content_uri_utils_jni/ContentUriUtils_jni.h",
+        "base/content_uri_utils_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -3038,64 +4938,74 @@
     name: "tot_cronet_base_debugging_buildflags",
     cmd: "if [[ ( $$CC_ARCH == 'arm' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/debug && echo '--flags DCHECK_IS_CONFIGURABLE=\"false\" ENABLE_PROFILING=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"false\" UNSAFE_DEVELOPER_BUILD=\"false\" CAN_UNWIND_WITH_CFI_TABLE=\"true\" EXCLUDE_UNWIND_TABLES=\"false\" ENABLE_GDBINIT_WARNING=\"false\" ENABLE_LLDBINIT_WARNING=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" ENABLE_STACK_TRACE_LINE_NUMBERS=\"true\" ENABLE_COMMANDLINE_SEQUENCE_CHECKS=\"false\" ENABLE_ALLOCATION_STACK_TRACE_RECORDER=\"false\" ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=\"false\" PRINT_UNSYMBOLIZED_STACK_TRACES=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/debug &&  " +
+         "echo '--flags DCHECK_IS_CONFIGURABLE=false ENABLE_PROFILING=false CAN_UNWIND_WITH_FRAME_POINTERS=false UNSAFE_DEVELOPER_BUILD=false CAN_UNWIND_WITH_CFI_TABLE=true EXCLUDE_UNWIND_TABLES=false ENABLE_GDBINIT_WARNING=false ENABLE_LLDBINIT_WARNING=false EXPENSIVE_DCHECKS_ARE_ON=false ENABLE_STACK_TRACE_LINE_NUMBERS=true ENABLE_COMMANDLINE_SEQUENCE_CHECKS=false ENABLE_ALLOCATION_STACK_TRACE_RECORDER=false ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=false PRINT_UNSYMBOLIZED_STACK_TRACES=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:debugging_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'arm64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/debug && echo '--flags DCHECK_IS_CONFIGURABLE=\"false\" ENABLE_PROFILING=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"true\" UNSAFE_DEVELOPER_BUILD=\"false\" CAN_UNWIND_WITH_CFI_TABLE=\"false\" EXCLUDE_UNWIND_TABLES=\"false\" ENABLE_GDBINIT_WARNING=\"false\" ENABLE_LLDBINIT_WARNING=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" ENABLE_STACK_TRACE_LINE_NUMBERS=\"true\" ENABLE_COMMANDLINE_SEQUENCE_CHECKS=\"false\" ENABLE_ALLOCATION_STACK_TRACE_RECORDER=\"true\" ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=\"false\" PRINT_UNSYMBOLIZED_STACK_TRACES=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/debug &&  " +
+         "echo '--flags DCHECK_IS_CONFIGURABLE=false ENABLE_PROFILING=false CAN_UNWIND_WITH_FRAME_POINTERS=true UNSAFE_DEVELOPER_BUILD=false CAN_UNWIND_WITH_CFI_TABLE=false EXCLUDE_UNWIND_TABLES=false ENABLE_GDBINIT_WARNING=false ENABLE_LLDBINIT_WARNING=false EXPENSIVE_DCHECKS_ARE_ON=false ENABLE_STACK_TRACE_LINE_NUMBERS=true ENABLE_COMMANDLINE_SEQUENCE_CHECKS=false ENABLE_ALLOCATION_STACK_TRACE_RECORDER=true ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=false PRINT_UNSYMBOLIZED_STACK_TRACES=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:debugging_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'riscv64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/debug && echo '--flags DCHECK_IS_CONFIGURABLE=\"false\" ENABLE_PROFILING=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"false\" UNSAFE_DEVELOPER_BUILD=\"false\" CAN_UNWIND_WITH_CFI_TABLE=\"false\" EXCLUDE_UNWIND_TABLES=\"false\" ENABLE_GDBINIT_WARNING=\"false\" ENABLE_LLDBINIT_WARNING=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" ENABLE_STACK_TRACE_LINE_NUMBERS=\"true\" ENABLE_COMMANDLINE_SEQUENCE_CHECKS=\"false\" ENABLE_ALLOCATION_STACK_TRACE_RECORDER=\"false\" ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=\"false\" PRINT_UNSYMBOLIZED_STACK_TRACES=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/debug &&  " +
+         "echo '--flags DCHECK_IS_CONFIGURABLE=false ENABLE_PROFILING=false CAN_UNWIND_WITH_FRAME_POINTERS=false UNSAFE_DEVELOPER_BUILD=false CAN_UNWIND_WITH_CFI_TABLE=false EXCLUDE_UNWIND_TABLES=false ENABLE_GDBINIT_WARNING=false ENABLE_LLDBINIT_WARNING=false EXPENSIVE_DCHECKS_ARE_ON=false ENABLE_STACK_TRACE_LINE_NUMBERS=true ENABLE_COMMANDLINE_SEQUENCE_CHECKS=false ENABLE_ALLOCATION_STACK_TRACE_RECORDER=false ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=false PRINT_UNSYMBOLIZED_STACK_TRACES=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:debugging_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/debug && echo '--flags DCHECK_IS_CONFIGURABLE=\"false\" ENABLE_PROFILING=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"true\" UNSAFE_DEVELOPER_BUILD=\"false\" CAN_UNWIND_WITH_CFI_TABLE=\"false\" EXCLUDE_UNWIND_TABLES=\"false\" ENABLE_GDBINIT_WARNING=\"false\" ENABLE_LLDBINIT_WARNING=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" ENABLE_STACK_TRACE_LINE_NUMBERS=\"true\" ENABLE_COMMANDLINE_SEQUENCE_CHECKS=\"false\" ENABLE_ALLOCATION_STACK_TRACE_RECORDER=\"false\" ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=\"false\" PRINT_UNSYMBOLIZED_STACK_TRACES=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/debug &&  " +
+         "echo '--flags DCHECK_IS_CONFIGURABLE=false ENABLE_PROFILING=false CAN_UNWIND_WITH_FRAME_POINTERS=true UNSAFE_DEVELOPER_BUILD=false CAN_UNWIND_WITH_CFI_TABLE=false EXCLUDE_UNWIND_TABLES=false ENABLE_GDBINIT_WARNING=false ENABLE_LLDBINIT_WARNING=false EXPENSIVE_DCHECKS_ARE_ON=false ENABLE_STACK_TRACE_LINE_NUMBERS=true ENABLE_COMMANDLINE_SEQUENCE_CHECKS=false ENABLE_ALLOCATION_STACK_TRACE_RECORDER=false ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=false PRINT_UNSYMBOLIZED_STACK_TRACES=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:debugging_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86_64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/debug && echo '--flags DCHECK_IS_CONFIGURABLE=\"false\" ENABLE_PROFILING=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"false\" UNSAFE_DEVELOPER_BUILD=\"false\" CAN_UNWIND_WITH_CFI_TABLE=\"false\" EXCLUDE_UNWIND_TABLES=\"false\" ENABLE_GDBINIT_WARNING=\"false\" ENABLE_LLDBINIT_WARNING=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" ENABLE_STACK_TRACE_LINE_NUMBERS=\"true\" ENABLE_COMMANDLINE_SEQUENCE_CHECKS=\"false\" ENABLE_ALLOCATION_STACK_TRACE_RECORDER=\"false\" ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=\"false\" PRINT_UNSYMBOLIZED_STACK_TRACES=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/debug &&  " +
+         "echo '--flags DCHECK_IS_CONFIGURABLE=false ENABLE_PROFILING=false CAN_UNWIND_WITH_FRAME_POINTERS=false UNSAFE_DEVELOPER_BUILD=false CAN_UNWIND_WITH_CFI_TABLE=false EXCLUDE_UNWIND_TABLES=false ENABLE_GDBINIT_WARNING=false ENABLE_LLDBINIT_WARNING=false EXPENSIVE_DCHECKS_ARE_ON=false ENABLE_STACK_TRACE_LINE_NUMBERS=true ENABLE_COMMANDLINE_SEQUENCE_CHECKS=false ENABLE_ALLOCATION_STACK_TRACE_RECORDER=false ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=false PRINT_UNSYMBOLIZED_STACK_TRACES=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:debugging_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi;",
+         "/dev/stdin " +
+         ";fi;",
     host_cross_supported: false,
     out: [
         "base/debug/debugging_buildflags.h",
@@ -3116,76 +5026,88 @@
     name: "tot_cronet_base_debugging_buildflags__testing",
     cmd: "if [[ ( $$CC_ARCH == 'arm' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/debug && echo '--flags DCHECK_IS_CONFIGURABLE=\"false\" ENABLE_PROFILING=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"false\" UNSAFE_DEVELOPER_BUILD=\"false\" CAN_UNWIND_WITH_CFI_TABLE=\"true\" EXCLUDE_UNWIND_TABLES=\"false\" ENABLE_GDBINIT_WARNING=\"false\" ENABLE_LLDBINIT_WARNING=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" ENABLE_STACK_TRACE_LINE_NUMBERS=\"true\" ENABLE_COMMANDLINE_SEQUENCE_CHECKS=\"false\" ENABLE_ALLOCATION_STACK_TRACE_RECORDER=\"false\" ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=\"false\" PRINT_UNSYMBOLIZED_STACK_TRACES=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/debug &&  " +
+         "echo '--flags DCHECK_IS_CONFIGURABLE=false ENABLE_PROFILING=false CAN_UNWIND_WITH_FRAME_POINTERS=false UNSAFE_DEVELOPER_BUILD=false CAN_UNWIND_WITH_CFI_TABLE=true EXCLUDE_UNWIND_TABLES=false ENABLE_GDBINIT_WARNING=false ENABLE_LLDBINIT_WARNING=false EXPENSIVE_DCHECKS_ARE_ON=false ENABLE_STACK_TRACE_LINE_NUMBERS=true ENABLE_COMMANDLINE_SEQUENCE_CHECKS=false ENABLE_ALLOCATION_STACK_TRACE_RECORDER=false ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=false PRINT_UNSYMBOLIZED_STACK_TRACES=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:debugging_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'arm64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/debug && echo '--flags DCHECK_IS_CONFIGURABLE=\"false\" ENABLE_PROFILING=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"true\" UNSAFE_DEVELOPER_BUILD=\"false\" CAN_UNWIND_WITH_CFI_TABLE=\"false\" EXCLUDE_UNWIND_TABLES=\"false\" ENABLE_GDBINIT_WARNING=\"false\" ENABLE_LLDBINIT_WARNING=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" ENABLE_STACK_TRACE_LINE_NUMBERS=\"true\" ENABLE_COMMANDLINE_SEQUENCE_CHECKS=\"false\" ENABLE_ALLOCATION_STACK_TRACE_RECORDER=\"true\" ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=\"false\" PRINT_UNSYMBOLIZED_STACK_TRACES=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/debug &&  " +
+         "echo '--flags DCHECK_IS_CONFIGURABLE=false ENABLE_PROFILING=false CAN_UNWIND_WITH_FRAME_POINTERS=true UNSAFE_DEVELOPER_BUILD=false CAN_UNWIND_WITH_CFI_TABLE=false EXCLUDE_UNWIND_TABLES=false ENABLE_GDBINIT_WARNING=false ENABLE_LLDBINIT_WARNING=false EXPENSIVE_DCHECKS_ARE_ON=false ENABLE_STACK_TRACE_LINE_NUMBERS=true ENABLE_COMMANDLINE_SEQUENCE_CHECKS=false ENABLE_ALLOCATION_STACK_TRACE_RECORDER=true ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=false PRINT_UNSYMBOLIZED_STACK_TRACES=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:debugging_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'riscv64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/debug && echo '--flags DCHECK_IS_CONFIGURABLE=\"false\" ENABLE_PROFILING=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"false\" UNSAFE_DEVELOPER_BUILD=\"false\" CAN_UNWIND_WITH_CFI_TABLE=\"false\" EXCLUDE_UNWIND_TABLES=\"false\" ENABLE_GDBINIT_WARNING=\"false\" ENABLE_LLDBINIT_WARNING=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" ENABLE_STACK_TRACE_LINE_NUMBERS=\"true\" ENABLE_COMMANDLINE_SEQUENCE_CHECKS=\"false\" ENABLE_ALLOCATION_STACK_TRACE_RECORDER=\"false\" ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=\"false\" PRINT_UNSYMBOLIZED_STACK_TRACES=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/debug &&  " +
+         "echo '--flags DCHECK_IS_CONFIGURABLE=false ENABLE_PROFILING=false CAN_UNWIND_WITH_FRAME_POINTERS=false UNSAFE_DEVELOPER_BUILD=false CAN_UNWIND_WITH_CFI_TABLE=false EXCLUDE_UNWIND_TABLES=false ENABLE_GDBINIT_WARNING=false ENABLE_LLDBINIT_WARNING=false EXPENSIVE_DCHECKS_ARE_ON=false ENABLE_STACK_TRACE_LINE_NUMBERS=true ENABLE_COMMANDLINE_SEQUENCE_CHECKS=false ENABLE_ALLOCATION_STACK_TRACE_RECORDER=false ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=false PRINT_UNSYMBOLIZED_STACK_TRACES=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:debugging_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/debug && echo '--flags DCHECK_IS_CONFIGURABLE=\"false\" ENABLE_PROFILING=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"true\" UNSAFE_DEVELOPER_BUILD=\"false\" CAN_UNWIND_WITH_CFI_TABLE=\"false\" EXCLUDE_UNWIND_TABLES=\"false\" ENABLE_GDBINIT_WARNING=\"false\" ENABLE_LLDBINIT_WARNING=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" ENABLE_STACK_TRACE_LINE_NUMBERS=\"true\" ENABLE_COMMANDLINE_SEQUENCE_CHECKS=\"false\" ENABLE_ALLOCATION_STACK_TRACE_RECORDER=\"false\" ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=\"false\" PRINT_UNSYMBOLIZED_STACK_TRACES=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/debug &&  " +
+         "echo '--flags DCHECK_IS_CONFIGURABLE=false ENABLE_PROFILING=false CAN_UNWIND_WITH_FRAME_POINTERS=true UNSAFE_DEVELOPER_BUILD=false CAN_UNWIND_WITH_CFI_TABLE=false EXCLUDE_UNWIND_TABLES=false ENABLE_GDBINIT_WARNING=false ENABLE_LLDBINIT_WARNING=false EXPENSIVE_DCHECKS_ARE_ON=false ENABLE_STACK_TRACE_LINE_NUMBERS=true ENABLE_COMMANDLINE_SEQUENCE_CHECKS=false ENABLE_ALLOCATION_STACK_TRACE_RECORDER=false ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=false PRINT_UNSYMBOLIZED_STACK_TRACES=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:debugging_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86_64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/debug && echo '--flags DCHECK_IS_CONFIGURABLE=\"false\" ENABLE_PROFILING=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"false\" UNSAFE_DEVELOPER_BUILD=\"false\" CAN_UNWIND_WITH_CFI_TABLE=\"false\" EXCLUDE_UNWIND_TABLES=\"false\" ENABLE_GDBINIT_WARNING=\"false\" ENABLE_LLDBINIT_WARNING=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" ENABLE_STACK_TRACE_LINE_NUMBERS=\"true\" ENABLE_COMMANDLINE_SEQUENCE_CHECKS=\"false\" ENABLE_ALLOCATION_STACK_TRACE_RECORDER=\"false\" ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=\"false\" PRINT_UNSYMBOLIZED_STACK_TRACES=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/debug &&  " +
+         "echo '--flags DCHECK_IS_CONFIGURABLE=false ENABLE_PROFILING=false CAN_UNWIND_WITH_FRAME_POINTERS=false UNSAFE_DEVELOPER_BUILD=false CAN_UNWIND_WITH_CFI_TABLE=false EXCLUDE_UNWIND_TABLES=false ENABLE_GDBINIT_WARNING=false ENABLE_LLDBINIT_WARNING=false EXPENSIVE_DCHECKS_ARE_ON=false ENABLE_STACK_TRACE_LINE_NUMBERS=true ENABLE_COMMANDLINE_SEQUENCE_CHECKS=false ENABLE_ALLOCATION_STACK_TRACE_RECORDER=false ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=false PRINT_UNSYMBOLIZED_STACK_TRACES=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:debugging_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ $$CC_OS != 'android' ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/debug && echo '--flags DCHECK_IS_CONFIGURABLE=\"false\" ENABLE_PROFILING=\"false\" CAN_UNWIND_WITH_FRAME_POINTERS=\"true\" UNSAFE_DEVELOPER_BUILD=\"false\" CAN_UNWIND_WITH_CFI_TABLE=\"false\" EXCLUDE_UNWIND_TABLES=\"true\" ENABLE_GDBINIT_WARNING=\"false\" ENABLE_LLDBINIT_WARNING=\"false\" EXPENSIVE_DCHECKS_ARE_ON=\"false\" ENABLE_STACK_TRACE_LINE_NUMBERS=\"true\" ENABLE_COMMANDLINE_SEQUENCE_CHECKS=\"false\" ENABLE_ALLOCATION_STACK_TRACE_RECORDER=\"false\" ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=\"false\" PRINT_UNSYMBOLIZED_STACK_TRACES=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/debug &&  " +
+         "echo '--flags DCHECK_IS_CONFIGURABLE=false ENABLE_PROFILING=false CAN_UNWIND_WITH_FRAME_POINTERS=true UNSAFE_DEVELOPER_BUILD=false CAN_UNWIND_WITH_CFI_TABLE=false EXCLUDE_UNWIND_TABLES=true ENABLE_GDBINIT_WARNING=false ENABLE_LLDBINIT_WARNING=false EXPENSIVE_DCHECKS_ARE_ON=false ENABLE_STACK_TRACE_LINE_NUMBERS=true ENABLE_COMMANDLINE_SEQUENCE_CHECKS=false ENABLE_ALLOCATION_STACK_TRACE_RECORDER=false ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING=false PRINT_UNSYMBOLIZED_STACK_TRACES=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:debugging_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi;",
+         "/dev/stdin " +
+         ";fi;",
     host_supported: true,
     host_cross_supported: false,
     out: [
@@ -3205,9 +5127,11 @@
 // GN: //base:feature_list_buildflags
 cc_genrule {
     name: "tot_cronet_base_feature_list_buildflags",
-    cmd: "mkdir -p $(genDir)/base && echo '--flags ENABLE_BANNED_BASE_FEATURE_PREFIX=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags ENABLE_BANNED_BASE_FEATURE_PREFIX=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:feature_list_buildflags " +
          "--gen-dir " +
@@ -3232,9 +5156,11 @@
 // GN: //base:feature_list_buildflags__testing
 cc_genrule {
     name: "tot_cronet_base_feature_list_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/base && echo '--flags ENABLE_BANNED_BASE_FEATURE_PREFIX=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags ENABLE_BANNED_BASE_FEATURE_PREFIX=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:feature_list_buildflags " +
          "--gen-dir " +
@@ -3257,12 +5183,78 @@
     ],
 }
 
+// GN: //base:flagged_apis_java__process_device
+java_genrule {
+    name: "tot_cronet_base_flagged_apis_java__process_device",
+    srcs: [
+        ":tot_cronet_base_flagged_apis_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/flagged_apis_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:flagged_apis_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_flagged_apis_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_flagged_apis_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/flagged_apis_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:fuzzing_buildflags
 cc_genrule {
     name: "tot_cronet_base_fuzzing_buildflags",
-    cmd: "mkdir -p $(genDir)/base && echo '--flags USE_FUZZING_ENGINE=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags USE_FUZZING_ENGINE=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:fuzzing_buildflags " +
          "--gen-dir " +
@@ -3287,9 +5279,11 @@
 // GN: //base:fuzzing_buildflags__testing
 cc_genrule {
     name: "tot_cronet_base_fuzzing_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/base && echo '--flags USE_FUZZING_ENGINE=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags USE_FUZZING_ENGINE=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:fuzzing_buildflags " +
          "--gen-dir " +
@@ -3315,9 +5309,11 @@
 // GN: //base:ios_cronet_buildflags
 cc_genrule {
     name: "tot_cronet_base_ios_cronet_buildflags",
-    cmd: "mkdir -p $(genDir)/base/message_loop && echo '--flags CRONET_BUILD=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base/message_loop &&  " +
+         "echo '--flags CRONET_BUILD=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:ios_cronet_buildflags " +
          "--gen-dir " +
@@ -3342,9 +5338,11 @@
 // GN: //base:ios_cronet_buildflags__testing
 cc_genrule {
     name: "tot_cronet_base_ios_cronet_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/base/message_loop && echo '--flags CRONET_BUILD=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base/message_loop &&  " +
+         "echo '--flags CRONET_BUILD=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:ios_cronet_buildflags " +
          "--gen-dir " +
@@ -3367,6 +5365,70 @@
     ],
 }
 
+// GN: //base:jank_tracker_java__process_device
+java_genrule {
+    name: "tot_cronet_base_jank_tracker_java__process_device",
+    srcs: [
+        ":tot_cronet_base_jank_tracker_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/jank_tracker_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:jank_tracker_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_jank_tracker_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_jank_tracker_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/jank_tracker_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:jank_tracker_jni__action
 cc_genrule {
     name: "tot_cronet_base_jank_tracker_jni__action",
@@ -3374,26 +5436,29 @@
         "base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/jank_tracker_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/jank_tracker_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/jank_tracker_jni " +
+         "'$(genDir)/base/jank_tracker_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/jank_tracker_jni.srcjar " +
+         "'$(genDir)/base/jank_tracker_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/jank_tracker_jni_placeholder.srcjar " +
+         "'$(genDir)/base/jank_tracker_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "JankMetricUMARecorder_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java) " +
+         "'$(location base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
     out: [
         "base/jank_tracker_jni.srcjar",
         "base/jank_tracker_jni/JankMetricUMARecorder_jni.h",
+        "base/jank_tracker_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -3429,25 +5494,28 @@
         "base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/jank_tracker_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/jank_tracker_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/jank_tracker_jni " +
+         "'$(genDir)/base/jank_tracker_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/jank_tracker_jni.srcjar " +
+         "'$(genDir)/base/jank_tracker_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/jank_tracker_jni_placeholder.srcjar " +
+         "'$(genDir)/base/jank_tracker_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "JankMetricUMARecorder_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java) " +
+         "'$(location base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     out: [
         "base/jank_tracker_jni.srcjar",
         "base/jank_tracker_jni/JankMetricUMARecorder_jni.h",
+        "base/jank_tracker_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -3473,6 +5541,18 @@
     ],
 }
 
+// GN: //base:jank_tracker_jni__action
+java_genrule {
+    name: "tot_cronet_base_jank_tracker_jni__action__java_proxy_only",
+    srcs: [
+        ":tot_cronet_base_jank_tracker_jni__action__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "jank_tracker_jni.srcjar",
+    ],
+}
+
 // GN: //base:jank_tracker_jni__action__testing
 cc_genrule {
     name: "tot_cronet_base_jank_tracker_jni__action__testing",
@@ -3480,24 +5560,27 @@
         "base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/jank_tracker_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/jank_tracker_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/jank_tracker_jni " +
+         "'$(genDir)/base/jank_tracker_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/jank_tracker_jni.srcjar " +
+         "'$(genDir)/base/jank_tracker_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/jank_tracker_jni_placeholder.srcjar " +
+         "'$(genDir)/base/jank_tracker_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "JankMetricUMARecorder_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java)",
+         "'$(location base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java)'",
     host_cross_supported: false,
     out: [
         "base/jank_tracker_jni.srcjar",
         "base/jank_tracker_jni/JankMetricUMARecorder_jni.h",
+        "base/jank_tracker_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -3533,23 +5616,26 @@
         "base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/jank_tracker_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/jank_tracker_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/jank_tracker_jni " +
+         "'$(genDir)/base/jank_tracker_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/jank_tracker_jni.srcjar " +
+         "'$(genDir)/base/jank_tracker_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/jank_tracker_jni_placeholder.srcjar " +
+         "'$(genDir)/base/jank_tracker_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "JankMetricUMARecorder_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java)",
+         "'$(location base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java)'",
     out: [
         "base/jank_tracker_jni.srcjar",
         "base/jank_tracker_jni/JankMetricUMARecorder_jni.h",
+        "base/jank_tracker_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -3575,6 +5661,18 @@
     ],
 }
 
+// GN: //base:jank_tracker_jni__action__testing
+java_genrule {
+    name: "tot_cronet_base_jank_tracker_jni__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_base_jank_tracker_jni__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "jank_tracker_jni.srcjar",
+    ],
+}
+
 // GN: //base:java_features_srcjar
 java_genrule {
     name: "tot_cronet_base_java_features_srcjar",
@@ -3583,13 +5681,15 @@
         "base/features.cc",
         "base/task/task_features.cc",
     ],
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_features.py) --srcjar " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_features.py) " +
+         "--srcjar " +
+         "'$(out)' " +
          "--template " +
-         "$(location base/android/java/src/org/chromium/base/BaseFeatures.java.tmpl) " +
-         "$(location base/allocator/partition_alloc_features.cc) " +
-         "$(location base/features.cc) " +
-         "$(location base/task/task_features.cc)",
+         "'$(location base/android/java/src/org/chromium/base/BaseFeatures.java.tmpl)' " +
+         "'$(location base/allocator/partition_alloc_features.cc)' " +
+         "'$(location base/features.cc)' " +
+         "'$(location base/task/task_features.cc)'",
     out: [
         "base/java_features_srcjar.srcjar",
     ],
@@ -3616,13 +5716,15 @@
         "base/features.cc",
         "base/task/task_features.cc",
     ],
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_features.py) --srcjar " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_features.py) " +
+         "--srcjar " +
+         "'$(out)' " +
          "--template " +
-         "$(location base/android/java/src/org/chromium/base/BaseFeatures.java.tmpl) " +
-         "$(location base/allocator/partition_alloc_features.cc) " +
-         "$(location base/features.cc) " +
-         "$(location base/task/task_features.cc)",
+         "'$(location base/android/java/src/org/chromium/base/BaseFeatures.java.tmpl)' " +
+         "'$(location base/allocator/partition_alloc_features.cc)' " +
+         "'$(location base/features.cc)' " +
+         "'$(location base/task/task_features.cc)'",
     out: [
         "base/java_features_srcjar.srcjar",
     ],
@@ -3647,11 +5749,13 @@
     srcs: [
         "base/base_switches.cc",
     ],
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_strings.py) --srcjar " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_strings.py) " +
+         "--srcjar " +
+         "'$(out)' " +
          "--template " +
-         "$(location base/android/java/src/org/chromium/base/BaseSwitches.java.tmpl) " +
-         "$(location base/base_switches.cc)",
+         "'$(location base/android/java/src/org/chromium/base/BaseSwitches.java.tmpl)' " +
+         "'$(location base/base_switches.cc)'",
     out: [
         "base/java_switches_srcjar.srcjar",
     ],
@@ -3676,11 +5780,13 @@
     srcs: [
         "base/base_switches.cc",
     ],
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_strings.py) --srcjar " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_strings.py) " +
+         "--srcjar " +
+         "'$(out)' " +
          "--template " +
-         "$(location base/android/java/src/org/chromium/base/BaseSwitches.java.tmpl) " +
-         "$(location base/base_switches.cc)",
+         "'$(location base/android/java/src/org/chromium/base/BaseSwitches.java.tmpl)' " +
+         "'$(location base/base_switches.cc)'",
     out: [
         "base/java_switches_srcjar.srcjar",
     ],
@@ -3699,12 +5805,78 @@
     ],
 }
 
+// GN: //base:library_loader_java__process_device
+java_genrule {
+    name: "tot_cronet_base_library_loader_java__process_device",
+    srcs: [
+        ":tot_cronet_base_library_loader_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/library_loader_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:library_loader_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_library_loader_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_library_loader_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/library_loader_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:library_loader_java_enums_srcjar
 java_genrule {
     name: "tot_cronet_base_library_loader_java_enums_srcjar",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/android/library_loader/library_loader_hooks.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/android/library_loader/library_loader_hooks.h)'",
     out: [
         "base/library_loader_java_enums_srcjar.srcjar",
     ],
@@ -3726,9 +5898,11 @@
 // GN: //base:library_loader_java_enums_srcjar__testing
 java_genrule {
     name: "tot_cronet_base_library_loader_java_enums_srcjar__testing",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/android/library_loader/library_loader_hooks.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/android/library_loader/library_loader_hooks.h)'",
     out: [
         "base/library_loader_java_enums_srcjar.srcjar",
     ],
@@ -3755,24 +5929,26 @@
         "base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/library_loader_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/library_loader_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/library_loader_jni " +
+         "'$(genDir)/base/library_loader_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/library_loader_jni.srcjar " +
+         "'$(genDir)/base/library_loader_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/library_loader_jni_placeholder.srcjar " +
+         "'$(genDir)/base/library_loader_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "LibraryLoader_jni.h " +
          "--output-name " +
          "LibraryPrefetcher_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java) " +
+         "'$(location base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java) " +
+         "'$(location base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
@@ -3780,6 +5956,7 @@
         "base/library_loader_jni.srcjar",
         "base/library_loader_jni/LibraryLoader_jni.h",
         "base/library_loader_jni/LibraryPrefetcher_jni.h",
+        "base/library_loader_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -3816,30 +5993,33 @@
         "base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/library_loader_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/library_loader_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/library_loader_jni " +
+         "'$(genDir)/base/library_loader_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/library_loader_jni.srcjar " +
+         "'$(genDir)/base/library_loader_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/library_loader_jni_placeholder.srcjar " +
+         "'$(genDir)/base/library_loader_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "LibraryLoader_jni.h " +
          "--output-name " +
          "LibraryPrefetcher_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java) " +
+         "'$(location base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java) " +
+         "'$(location base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     out: [
         "base/library_loader_jni.srcjar",
         "base/library_loader_jni/LibraryLoader_jni.h",
         "base/library_loader_jni/LibraryPrefetcher_jni.h",
+        "base/library_loader_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -3873,29 +6053,32 @@
         "base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/library_loader_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/library_loader_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/library_loader_jni " +
+         "'$(genDir)/base/library_loader_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/library_loader_jni.srcjar " +
+         "'$(genDir)/base/library_loader_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/library_loader_jni_placeholder.srcjar " +
+         "'$(genDir)/base/library_loader_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "LibraryLoader_jni.h " +
          "--output-name " +
          "LibraryPrefetcher_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java) " +
+         "'$(location base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java)",
+         "'$(location base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java)'",
     host_cross_supported: false,
     out: [
         "base/library_loader_jni.srcjar",
         "base/library_loader_jni/LibraryLoader_jni.h",
         "base/library_loader_jni/LibraryPrefetcher_jni.h",
+        "base/library_loader_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -3932,28 +6115,31 @@
         "base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/library_loader_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/library_loader_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/library_loader_jni " +
+         "'$(genDir)/base/library_loader_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/library_loader_jni.srcjar " +
+         "'$(genDir)/base/library_loader_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/library_loader_jni_placeholder.srcjar " +
+         "'$(genDir)/base/library_loader_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "LibraryLoader_jni.h " +
          "--output-name " +
          "LibraryPrefetcher_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java) " +
+         "'$(location base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java)",
+         "'$(location base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java)'",
     out: [
         "base/library_loader_jni.srcjar",
         "base/library_loader_jni/LibraryLoader_jni.h",
         "base/library_loader_jni/LibraryPrefetcher_jni.h",
+        "base/library_loader_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -3979,6 +6165,262 @@
     ],
 }
 
+// GN: //base:library_loader_jni_java__process_device
+java_genrule {
+    name: "tot_cronet_base_library_loader_jni_java__process_device",
+    srcs: [
+        ":tot_cronet_base_library_loader_jni_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/library_loader_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:library_loader_jni_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_library_loader_jni_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_library_loader_jni_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/library_loader_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:lifetime_java__process_device
+java_genrule {
+    name: "tot_cronet_base_lifetime_java__process_device",
+    srcs: [
+        ":tot_cronet_base_lifetime_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/lifetime_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:lifetime_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_lifetime_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_lifetime_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/lifetime_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:log_java__process_device
+java_genrule {
+    name: "tot_cronet_base_log_java__process_device",
+    srcs: [
+        ":tot_cronet_base_log_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/log_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:log_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_log_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_log_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/log_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:memory_java__process_device
+java_genrule {
+    name: "tot_cronet_base_memory_java__process_device",
+    srcs: [
+        ":tot_cronet_base_memory_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/memory_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:memory_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_memory_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_memory_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/memory_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:memory_jni__action
 cc_genrule {
     name: "tot_cronet_base_memory_jni__action",
@@ -3989,15 +6431,17 @@
         "base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/memory_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/memory_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/memory_jni " +
+         "'$(genDir)/base/memory_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/memory_jni.srcjar " +
+         "'$(genDir)/base/memory_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/memory_jni_placeholder.srcjar " +
+         "'$(genDir)/base/memory_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "MemoryPressureListener_jni.h " +
@@ -4008,13 +6452,13 @@
          "--output-name " +
          "MemoryPurgeManager_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/MemoryPressureListener.java) " +
+         "'$(location base/android/java/src/org/chromium/base/MemoryPressureListener.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java) " +
+         "'$(location base/android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/memory/MemoryInfoBridge.java) " +
+         "'$(location base/android/java/src/org/chromium/base/memory/MemoryInfoBridge.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java) " +
+         "'$(location base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
@@ -4024,6 +6468,7 @@
         "base/memory_jni/MemoryInfoBridge_jni.h",
         "base/memory_jni/MemoryPressureListener_jni.h",
         "base/memory_jni/MemoryPurgeManager_jni.h",
+        "base/memory_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -4062,15 +6507,17 @@
         "base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/memory_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/memory_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/memory_jni " +
+         "'$(genDir)/base/memory_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/memory_jni.srcjar " +
+         "'$(genDir)/base/memory_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/memory_jni_placeholder.srcjar " +
+         "'$(genDir)/base/memory_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "MemoryPressureListener_jni.h " +
@@ -4081,13 +6528,13 @@
          "--output-name " +
          "MemoryPurgeManager_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/MemoryPressureListener.java) " +
+         "'$(location base/android/java/src/org/chromium/base/MemoryPressureListener.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java) " +
+         "'$(location base/android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/memory/MemoryInfoBridge.java) " +
+         "'$(location base/android/java/src/org/chromium/base/memory/MemoryInfoBridge.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java) " +
+         "'$(location base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     out: [
@@ -4096,6 +6543,7 @@
         "base/memory_jni/MemoryInfoBridge_jni.h",
         "base/memory_jni/MemoryPressureListener_jni.h",
         "base/memory_jni/MemoryPurgeManager_jni.h",
+        "base/memory_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -4121,6 +6569,18 @@
     ],
 }
 
+// GN: //base:memory_jni__action
+java_genrule {
+    name: "tot_cronet_base_memory_jni__action__java_proxy_only",
+    srcs: [
+        ":tot_cronet_base_memory_jni__action__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "memory_jni.srcjar",
+    ],
+}
+
 // GN: //base:memory_jni__action__testing
 cc_genrule {
     name: "tot_cronet_base_memory_jni__action__testing",
@@ -4131,15 +6591,17 @@
         "base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/memory_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/memory_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/memory_jni " +
+         "'$(genDir)/base/memory_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/memory_jni.srcjar " +
+         "'$(genDir)/base/memory_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/memory_jni_placeholder.srcjar " +
+         "'$(genDir)/base/memory_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "MemoryPressureListener_jni.h " +
@@ -4150,13 +6612,13 @@
          "--output-name " +
          "MemoryPurgeManager_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/MemoryPressureListener.java) " +
+         "'$(location base/android/java/src/org/chromium/base/MemoryPressureListener.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java) " +
+         "'$(location base/android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/memory/MemoryInfoBridge.java) " +
+         "'$(location base/android/java/src/org/chromium/base/memory/MemoryInfoBridge.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java)",
+         "'$(location base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java)'",
     host_cross_supported: false,
     out: [
         "base/memory_jni.srcjar",
@@ -4164,6 +6626,7 @@
         "base/memory_jni/MemoryInfoBridge_jni.h",
         "base/memory_jni/MemoryPressureListener_jni.h",
         "base/memory_jni/MemoryPurgeManager_jni.h",
+        "base/memory_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -4202,15 +6665,17 @@
         "base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/memory_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/memory_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/memory_jni " +
+         "'$(genDir)/base/memory_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/memory_jni.srcjar " +
+         "'$(genDir)/base/memory_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/memory_jni_placeholder.srcjar " +
+         "'$(genDir)/base/memory_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "MemoryPressureListener_jni.h " +
@@ -4221,19 +6686,20 @@
          "--output-name " +
          "MemoryPurgeManager_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/MemoryPressureListener.java) " +
+         "'$(location base/android/java/src/org/chromium/base/MemoryPressureListener.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java) " +
+         "'$(location base/android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/memory/MemoryInfoBridge.java) " +
+         "'$(location base/android/java/src/org/chromium/base/memory/MemoryInfoBridge.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java)",
+         "'$(location base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java)'",
     out: [
         "base/memory_jni.srcjar",
         "base/memory_jni/JavaHeapDumpGenerator_jni.h",
         "base/memory_jni/MemoryInfoBridge_jni.h",
         "base/memory_jni/MemoryPressureListener_jni.h",
         "base/memory_jni/MemoryPurgeManager_jni.h",
+        "base/memory_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -4259,12 +6725,26 @@
     ],
 }
 
+// GN: //base:memory_jni__action__testing
+java_genrule {
+    name: "tot_cronet_base_memory_jni__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_base_memory_jni__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "memory_jni.srcjar",
+    ],
+}
+
 // GN: //base:memory_pressure_level_enum_srcjar
 java_genrule {
     name: "tot_cronet_base_memory_pressure_level_enum_srcjar",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/memory/memory_pressure_listener.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/memory/memory_pressure_listener.h)'",
     out: [
         "base/memory_pressure_level_enum_srcjar.srcjar",
     ],
@@ -4286,9 +6766,11 @@
 // GN: //base:memory_pressure_level_enum_srcjar__testing
 java_genrule {
     name: "tot_cronet_base_memory_pressure_level_enum_srcjar__testing",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/memory/memory_pressure_listener.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/memory/memory_pressure_listener.h)'",
     out: [
         "base/memory_pressure_level_enum_srcjar.srcjar",
     ],
@@ -4307,12 +6789,78 @@
     ],
 }
 
+// GN: //base:metrics_ScopedSysTraceEvent_java__process_device
+java_genrule {
+    name: "tot_cronet_base_metrics_ScopedSysTraceEvent_java__process_device",
+    srcs: [
+        ":tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/metrics_ScopedSysTraceEvent_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:metrics_ScopedSysTraceEvent_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_metrics_ScopedSysTraceEvent_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/metrics_ScopedSysTraceEvent_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:metrics_enum_srcjar
 java_genrule {
     name: "tot_cronet_base_metrics_enum_srcjar",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/metrics/histogram_base.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/metrics/histogram_base.h)'",
     out: [
         "base/metrics_enum_srcjar.srcjar",
     ],
@@ -4334,9 +6882,11 @@
 // GN: //base:metrics_enum_srcjar__testing
 java_genrule {
     name: "tot_cronet_base_metrics_enum_srcjar__testing",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/metrics/histogram_base.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/metrics/histogram_base.h)'",
     out: [
         "base/metrics_enum_srcjar.srcjar",
     ],
@@ -4355,6 +6905,70 @@
     ],
 }
 
+// GN: //base:metrics_java__process_device
+java_genrule {
+    name: "tot_cronet_base_metrics_java__process_device",
+    srcs: [
+        ":tot_cronet_base_metrics_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/metrics_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:metrics_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_metrics_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_metrics_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/metrics_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:metrics_jni__action
 cc_genrule {
     name: "tot_cronet_base_metrics_jni__action",
@@ -4363,24 +6977,26 @@
         "base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/metrics_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/metrics_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/metrics_jni " +
+         "'$(genDir)/base/metrics_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/metrics_jni.srcjar " +
+         "'$(genDir)/base/metrics_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/metrics_jni_placeholder.srcjar " +
+         "'$(genDir)/base/metrics_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "NativeUmaRecorder_jni.h " +
          "--output-name " +
          "StatisticsRecorderAndroid_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java) " +
+         "'$(location base/android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java) " +
+         "'$(location base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
@@ -4388,6 +7004,7 @@
         "base/metrics_jni.srcjar",
         "base/metrics_jni/NativeUmaRecorder_jni.h",
         "base/metrics_jni/StatisticsRecorderAndroid_jni.h",
+        "base/metrics_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -4424,30 +7041,33 @@
         "base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/metrics_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/metrics_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/metrics_jni " +
+         "'$(genDir)/base/metrics_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/metrics_jni.srcjar " +
+         "'$(genDir)/base/metrics_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/metrics_jni_placeholder.srcjar " +
+         "'$(genDir)/base/metrics_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "NativeUmaRecorder_jni.h " +
          "--output-name " +
          "StatisticsRecorderAndroid_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java) " +
+         "'$(location base/android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java) " +
+         "'$(location base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     out: [
         "base/metrics_jni.srcjar",
         "base/metrics_jni/NativeUmaRecorder_jni.h",
         "base/metrics_jni/StatisticsRecorderAndroid_jni.h",
+        "base/metrics_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -4481,29 +7101,32 @@
         "base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/metrics_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/metrics_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/metrics_jni " +
+         "'$(genDir)/base/metrics_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/metrics_jni.srcjar " +
+         "'$(genDir)/base/metrics_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/metrics_jni_placeholder.srcjar " +
+         "'$(genDir)/base/metrics_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "NativeUmaRecorder_jni.h " +
          "--output-name " +
          "StatisticsRecorderAndroid_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java) " +
+         "'$(location base/android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java)",
+         "'$(location base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java)'",
     host_cross_supported: false,
     out: [
         "base/metrics_jni.srcjar",
         "base/metrics_jni/NativeUmaRecorder_jni.h",
         "base/metrics_jni/StatisticsRecorderAndroid_jni.h",
+        "base/metrics_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -4540,28 +7163,31 @@
         "base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/metrics_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/metrics_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/metrics_jni " +
+         "'$(genDir)/base/metrics_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/metrics_jni.srcjar " +
+         "'$(genDir)/base/metrics_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/metrics_jni_placeholder.srcjar " +
+         "'$(genDir)/base/metrics_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "NativeUmaRecorder_jni.h " +
          "--output-name " +
          "StatisticsRecorderAndroid_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java) " +
+         "'$(location base/android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java)",
+         "'$(location base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java)'",
     out: [
         "base/metrics_jni.srcjar",
         "base/metrics_jni/NativeUmaRecorder_jni.h",
         "base/metrics_jni/StatisticsRecorderAndroid_jni.h",
+        "base/metrics_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -4587,12 +7213,78 @@
     ],
 }
 
+// GN: //base:metrics_jni_java__process_device
+java_genrule {
+    name: "tot_cronet_base_metrics_jni_java__process_device",
+    srcs: [
+        ":tot_cronet_base_metrics_jni_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/metrics_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:metrics_jni_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_metrics_jni_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_metrics_jni_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/metrics_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:orderfile_buildflags
 cc_genrule {
     name: "tot_cronet_base_orderfile_buildflags",
-    cmd: "mkdir -p $(genDir)/base/android/orderfile && echo '--flags DEVTOOLS_INSTRUMENTATION_DUMPING=\"false\" ORDERFILE_INSTRUMENTATION=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base/android/orderfile &&  " +
+         "echo '--flags DEVTOOLS_INSTRUMENTATION_DUMPING=false ORDERFILE_INSTRUMENTATION=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:orderfile_buildflags " +
          "--gen-dir " +
@@ -4617,9 +7309,11 @@
 // GN: //base:orderfile_buildflags__testing
 cc_genrule {
     name: "tot_cronet_base_orderfile_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/base/android/orderfile && echo '--flags DEVTOOLS_INSTRUMENTATION_DUMPING=\"false\" ORDERFILE_INSTRUMENTATION=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base/android/orderfile &&  " +
+         "echo '--flags DEVTOOLS_INSTRUMENTATION_DUMPING=false ORDERFILE_INSTRUMENTATION=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:orderfile_buildflags " +
          "--gen-dir " +
@@ -4645,9 +7339,11 @@
 // GN: //base:power_monitor_buildflags
 cc_genrule {
     name: "tot_cronet_base_power_monitor_buildflags",
-    cmd: "mkdir -p $(genDir)/base/power_monitor && echo '--flags HAS_BATTERY_LEVEL_PROVIDER_IMPL=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base/power_monitor &&  " +
+         "echo '--flags HAS_BATTERY_LEVEL_PROVIDER_IMPL=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:power_monitor_buildflags " +
          "--gen-dir " +
@@ -4672,9 +7368,11 @@
 // GN: //base:power_monitor_buildflags__testing
 cc_genrule {
     name: "tot_cronet_base_power_monitor_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/base/power_monitor && echo '--flags HAS_BATTERY_LEVEL_PROVIDER_IMPL=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base/power_monitor &&  " +
+         "echo '--flags HAS_BATTERY_LEVEL_PROVIDER_IMPL=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:power_monitor_buildflags " +
          "--gen-dir " +
@@ -4704,26 +7402,29 @@
         "base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/process_launcher_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/process_launcher_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/process_launcher_jni " +
+         "'$(genDir)/base/process_launcher_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/process_launcher_jni.srcjar " +
+         "'$(genDir)/base/process_launcher_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/process_launcher_jni_placeholder.srcjar " +
+         "'$(genDir)/base/process_launcher_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ChildProcessService_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java) " +
+         "'$(location base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
     out: [
         "base/process_launcher_jni.srcjar",
         "base/process_launcher_jni/ChildProcessService_jni.h",
+        "base/process_launcher_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -4759,24 +7460,27 @@
         "base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/process_launcher_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/process_launcher_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/process_launcher_jni " +
+         "'$(genDir)/base/process_launcher_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/process_launcher_jni.srcjar " +
+         "'$(genDir)/base/process_launcher_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/process_launcher_jni_placeholder.srcjar " +
+         "'$(genDir)/base/process_launcher_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ChildProcessService_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java)",
+         "'$(location base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java)'",
     host_cross_supported: false,
     out: [
         "base/process_launcher_jni.srcjar",
         "base/process_launcher_jni/ChildProcessService_jni.h",
+        "base/process_launcher_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -4810,64 +7514,74 @@
     name: "tot_cronet_base_profiler_buildflags",
     cmd: "if [[ ( $$CC_ARCH == 'arm' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/profiler && echo '--flags ENABLE_ARM_CFI_TABLE=\"true\" IOS_STACK_PROFILER_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/profiler &&  " +
+         "echo '--flags ENABLE_ARM_CFI_TABLE=true IOS_STACK_PROFILER_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:profiler_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'arm64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/profiler && echo '--flags ENABLE_ARM_CFI_TABLE=\"false\" IOS_STACK_PROFILER_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/profiler &&  " +
+         "echo '--flags ENABLE_ARM_CFI_TABLE=false IOS_STACK_PROFILER_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:profiler_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'riscv64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/profiler && echo '--flags ENABLE_ARM_CFI_TABLE=\"false\" IOS_STACK_PROFILER_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/profiler &&  " +
+         "echo '--flags ENABLE_ARM_CFI_TABLE=false IOS_STACK_PROFILER_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:profiler_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/profiler && echo '--flags ENABLE_ARM_CFI_TABLE=\"false\" IOS_STACK_PROFILER_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/profiler &&  " +
+         "echo '--flags ENABLE_ARM_CFI_TABLE=false IOS_STACK_PROFILER_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:profiler_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86_64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/profiler && echo '--flags ENABLE_ARM_CFI_TABLE=\"false\" IOS_STACK_PROFILER_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/profiler &&  " +
+         "echo '--flags ENABLE_ARM_CFI_TABLE=false IOS_STACK_PROFILER_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:profiler_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi;",
+         "/dev/stdin " +
+         ";fi;",
     host_cross_supported: false,
     out: [
         "base/profiler/profiler_buildflags.h",
@@ -4888,76 +7602,88 @@
     name: "tot_cronet_base_profiler_buildflags__testing",
     cmd: "if [[ ( $$CC_ARCH == 'arm' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/profiler && echo '--flags ENABLE_ARM_CFI_TABLE=\"true\" IOS_STACK_PROFILER_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/profiler &&  " +
+         "echo '--flags ENABLE_ARM_CFI_TABLE=true IOS_STACK_PROFILER_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:profiler_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'arm64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/profiler && echo '--flags ENABLE_ARM_CFI_TABLE=\"false\" IOS_STACK_PROFILER_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/profiler &&  " +
+         "echo '--flags ENABLE_ARM_CFI_TABLE=false IOS_STACK_PROFILER_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:profiler_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'riscv64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/profiler && echo '--flags ENABLE_ARM_CFI_TABLE=\"false\" IOS_STACK_PROFILER_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/profiler &&  " +
+         "echo '--flags ENABLE_ARM_CFI_TABLE=false IOS_STACK_PROFILER_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:profiler_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/profiler && echo '--flags ENABLE_ARM_CFI_TABLE=\"false\" IOS_STACK_PROFILER_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/profiler &&  " +
+         "echo '--flags ENABLE_ARM_CFI_TABLE=false IOS_STACK_PROFILER_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:profiler_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86_64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/profiler && echo '--flags ENABLE_ARM_CFI_TABLE=\"false\" IOS_STACK_PROFILER_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/profiler &&  " +
+         "echo '--flags ENABLE_ARM_CFI_TABLE=false IOS_STACK_PROFILER_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:profiler_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ $$CC_OS != 'android' ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base/profiler && echo '--flags ENABLE_ARM_CFI_TABLE=\"false\" IOS_STACK_PROFILER_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base/profiler &&  " +
+         "echo '--flags ENABLE_ARM_CFI_TABLE=false IOS_STACK_PROFILER_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:profiler_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi;",
+         "/dev/stdin " +
+         ";fi;",
     host_supported: true,
     host_cross_supported: false,
     out: [
@@ -4974,12 +7700,78 @@
     ],
 }
 
+// GN: //base:promise_java__process_device
+java_genrule {
+    name: "tot_cronet_base_promise_java__process_device",
+    srcs: [
+        ":tot_cronet_base_promise_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/promise_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:promise_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_promise_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_promise_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/promise_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:protected_memory_buildflags
 cc_genrule {
     name: "tot_cronet_base_protected_memory_buildflags",
-    cmd: "mkdir -p $(genDir)/base/memory && echo '--flags PROTECTED_MEMORY_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base/memory &&  " +
+         "echo '--flags PROTECTED_MEMORY_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:protected_memory_buildflags " +
          "--gen-dir " +
@@ -5004,9 +7796,11 @@
 // GN: //base:protected_memory_buildflags__testing
 cc_genrule {
     name: "tot_cronet_base_protected_memory_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/base/memory && echo '--flags PROTECTED_MEMORY_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base/memory &&  " +
+         "echo '--flags PROTECTED_MEMORY_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:protected_memory_buildflags " +
          "--gen-dir " +
@@ -5029,6 +7823,70 @@
     ],
 }
 
+// GN: //base:resetters_java__process_device
+java_genrule {
+    name: "tot_cronet_base_resetters_java__process_device",
+    srcs: [
+        ":tot_cronet_base_resetters_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/resetters_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:resetters_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_resetters_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_resetters_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/resetters_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:rust_logger_cxx_generated_gen
 cc_genrule {
     name: "tot_cronet_base_rust_logger_cxx_generated_gen",
@@ -5122,9 +7980,11 @@
 // GN: //base:sanitizer_buildflags
 cc_genrule {
     name: "tot_cronet_base_sanitizer_buildflags",
-    cmd: "mkdir -p $(genDir)/base && echo '--flags IS_HWASAN=\"false\" IS_UBSAN=\"false\" IS_UBSAN_SECURITY=\"false\" USING_SANITIZER=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags IS_HWASAN=false IS_UBSAN=false IS_UBSAN_SECURITY=false USING_SANITIZER=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:sanitizer_buildflags " +
          "--gen-dir " +
@@ -5149,9 +8009,11 @@
 // GN: //base:sanitizer_buildflags__testing
 cc_genrule {
     name: "tot_cronet_base_sanitizer_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/base && echo '--flags IS_HWASAN=\"false\" IS_UBSAN=\"false\" IS_UBSAN_SECURITY=\"false\" USING_SANITIZER=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags IS_HWASAN=false IS_UBSAN=false IS_UBSAN_SECURITY=false USING_SANITIZER=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:sanitizer_buildflags " +
          "--gen-dir " +
@@ -5174,12 +8036,206 @@
     ],
 }
 
+// GN: //base:service_loader_java__process_device
+java_genrule {
+    name: "tot_cronet_base_service_loader_java__process_device",
+    srcs: [
+        ":tot_cronet_base_service_loader_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/service_loader_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:service_loader_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_service_loader_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_service_loader_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/service_loader_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:stream_util_java__process_device
+java_genrule {
+    name: "tot_cronet_base_stream_util_java__process_device",
+    srcs: [
+        ":tot_cronet_base_stream_util_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/stream_util_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:stream_util_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_stream_util_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_stream_util_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/stream_util_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:supplier_java__process_device
+java_genrule {
+    name: "tot_cronet_base_supplier_java__process_device",
+    srcs: [
+        ":tot_cronet_base_supplier_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/supplier_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:supplier_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_supplier_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_supplier_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/supplier_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:synchronization_buildflags
 cc_genrule {
     name: "tot_cronet_base_synchronization_buildflags",
-    cmd: "mkdir -p $(genDir)/base/synchronization && echo '--flags ENABLE_MUTEX_PRIORITY_INHERITANCE=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base/synchronization &&  " +
+         "echo '--flags ENABLE_MUTEX_PRIORITY_INHERITANCE=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:synchronization_buildflags " +
          "--gen-dir " +
@@ -5204,9 +8260,11 @@
 // GN: //base:synchronization_buildflags__testing
 cc_genrule {
     name: "tot_cronet_base_synchronization_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/base/synchronization && echo '--flags ENABLE_MUTEX_PRIORITY_INHERITANCE=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base/synchronization &&  " +
+         "echo '--flags ENABLE_MUTEX_PRIORITY_INHERITANCE=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:synchronization_buildflags " +
          "--gen-dir " +
@@ -5232,9 +8290,11 @@
 // GN: //base:sys_utils_enum_srcjar
 java_genrule {
     name: "tot_cronet_base_sys_utils_enum_srcjar",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/android/linker/linker_jni.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/android/linker/linker_jni.h)'",
     out: [
         "base/sys_utils_enum_srcjar.srcjar",
     ],
@@ -5256,9 +8316,11 @@
 // GN: //base:sys_utils_enum_srcjar__testing
 java_genrule {
     name: "tot_cronet_base_sys_utils_enum_srcjar__testing",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/android/linker/linker_jni.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/android/linker/linker_jni.h)'",
     out: [
         "base/sys_utils_enum_srcjar.srcjar",
     ],
@@ -5277,6 +8339,70 @@
     ],
 }
 
+// GN: //base:sys_utils_java__process_device
+java_genrule {
+    name: "tot_cronet_base_sys_utils_java__process_device",
+    srcs: [
+        ":tot_cronet_base_sys_utils_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/sys_utils_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:sys_utils_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_sys_utils_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_sys_utils_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/sys_utils_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:sys_utils_jni__action
 cc_genrule {
     name: "tot_cronet_base_sys_utils_jni__action",
@@ -5284,26 +8410,29 @@
         "base/android/java/src/org/chromium/base/SysUtils.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/sys_utils_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/sys_utils_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/sys_utils_jni " +
+         "'$(genDir)/base/sys_utils_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/sys_utils_jni.srcjar " +
+         "'$(genDir)/base/sys_utils_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/sys_utils_jni_placeholder.srcjar " +
+         "'$(genDir)/base/sys_utils_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "SysUtils_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/SysUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/SysUtils.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
     out: [
         "base/sys_utils_jni.srcjar",
         "base/sys_utils_jni/SysUtils_jni.h",
+        "base/sys_utils_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -5339,25 +8468,28 @@
         "base/android/java/src/org/chromium/base/SysUtils.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/sys_utils_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/sys_utils_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/sys_utils_jni " +
+         "'$(genDir)/base/sys_utils_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/sys_utils_jni.srcjar " +
+         "'$(genDir)/base/sys_utils_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/sys_utils_jni_placeholder.srcjar " +
+         "'$(genDir)/base/sys_utils_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "SysUtils_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/SysUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/SysUtils.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     out: [
         "base/sys_utils_jni.srcjar",
         "base/sys_utils_jni/SysUtils_jni.h",
+        "base/sys_utils_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -5383,6 +8515,18 @@
     ],
 }
 
+// GN: //base:sys_utils_jni__action
+java_genrule {
+    name: "tot_cronet_base_sys_utils_jni__action__java_proxy_only",
+    srcs: [
+        ":tot_cronet_base_sys_utils_jni__action__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "sys_utils_jni.srcjar",
+    ],
+}
+
 // GN: //base:sys_utils_jni__action__testing
 cc_genrule {
     name: "tot_cronet_base_sys_utils_jni__action__testing",
@@ -5390,24 +8534,27 @@
         "base/android/java/src/org/chromium/base/SysUtils.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/sys_utils_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/sys_utils_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/sys_utils_jni " +
+         "'$(genDir)/base/sys_utils_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/sys_utils_jni.srcjar " +
+         "'$(genDir)/base/sys_utils_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/sys_utils_jni_placeholder.srcjar " +
+         "'$(genDir)/base/sys_utils_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "SysUtils_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/SysUtils.java)",
+         "'$(location base/android/java/src/org/chromium/base/SysUtils.java)'",
     host_cross_supported: false,
     out: [
         "base/sys_utils_jni.srcjar",
         "base/sys_utils_jni/SysUtils_jni.h",
+        "base/sys_utils_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -5443,23 +8590,26 @@
         "base/android/java/src/org/chromium/base/SysUtils.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/sys_utils_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/sys_utils_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/sys_utils_jni " +
+         "'$(genDir)/base/sys_utils_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/sys_utils_jni.srcjar " +
+         "'$(genDir)/base/sys_utils_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/sys_utils_jni_placeholder.srcjar " +
+         "'$(genDir)/base/sys_utils_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "SysUtils_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/SysUtils.java)",
+         "'$(location base/android/java/src/org/chromium/base/SysUtils.java)'",
     out: [
         "base/sys_utils_jni.srcjar",
         "base/sys_utils_jni/SysUtils_jni.h",
+        "base/sys_utils_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -5485,13 +8635,27 @@
     ],
 }
 
+// GN: //base:sys_utils_jni__action__testing
+java_genrule {
+    name: "tot_cronet_base_sys_utils_jni__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_base_sys_utils_jni__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "sys_utils_jni.srcjar",
+    ],
+}
+
 // GN: //base:task_trait_enum_srcjar
 java_genrule {
     name: "tot_cronet_base_task_trait_enum_srcjar",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/android/task_scheduler/task_runner_android.h) " +
-         "$(location base/android/task_scheduler/task_traits_android.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/android/task_scheduler/task_runner_android.h)' " +
+         "'$(location base/android/task_scheduler/task_traits_android.h)'",
     out: [
         "base/task_trait_enum_srcjar.srcjar",
     ],
@@ -5514,10 +8678,12 @@
 // GN: //base:task_trait_enum_srcjar__testing
 java_genrule {
     name: "tot_cronet_base_task_trait_enum_srcjar__testing",
-    cmd: "mkdir -p $(genDir)/base && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location base/android/task_scheduler/task_runner_android.h) " +
-         "$(location base/android/task_scheduler/task_traits_android.h)",
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/android/task_scheduler/task_runner_android.h)' " +
+         "'$(location base/android/task_scheduler/task_traits_android.h)'",
     out: [
         "base/task_trait_enum_srcjar.srcjar",
     ],
@@ -5537,6 +8703,70 @@
     ],
 }
 
+// GN: //base:tasks_java__process_device
+java_genrule {
+    name: "tot_cronet_base_tasks_java__process_device",
+    srcs: [
+        ":tot_cronet_base_tasks_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/tasks_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_tasks_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_tasks_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/tasks_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:tasks_jni__action
 cc_genrule {
     name: "tot_cronet_base_tasks_jni__action",
@@ -5544,20 +8774,21 @@
         "base/android/java/src/org/chromium/base/ApplicationStatus.java",
         "base/android/java/src/org/chromium/base/EarlyTraceEvent.java",
         "base/android/java/src/org/chromium/base/ThreadUtils.java",
-        "base/android/java/src/org/chromium/base/TraceEvent.java",
         "base/android/java/src/org/chromium/base/task/PostTask.java",
         "base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/tasks_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/tasks_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/tasks_jni " +
+         "'$(genDir)/base/tasks_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/tasks_jni.srcjar " +
+         "'$(genDir)/base/tasks_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/tasks_jni_placeholder.srcjar " +
+         "'$(genDir)/base/tasks_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ApplicationStatus_jni.h " +
@@ -5566,23 +8797,19 @@
          "--output-name " +
          "ThreadUtils_jni.h " +
          "--output-name " +
-         "TraceEvent_jni.h " +
-         "--output-name " +
          "PostTask_jni.h " +
          "--output-name " +
          "TaskRunnerImpl_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ApplicationStatus.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ApplicationStatus.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/EarlyTraceEvent.java) " +
+         "'$(location base/android/java/src/org/chromium/base/EarlyTraceEvent.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ThreadUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ThreadUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/TraceEvent.java) " +
+         "'$(location base/android/java/src/org/chromium/base/task/PostTask.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/task/PostTask.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java) " +
+         "'$(location base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
@@ -5593,7 +8820,7 @@
         "base/tasks_jni/PostTask_jni.h",
         "base/tasks_jni/TaskRunnerImpl_jni.h",
         "base/tasks_jni/ThreadUtils_jni.h",
-        "base/tasks_jni/TraceEvent_jni.h",
+        "base/tasks_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -5629,20 +8856,21 @@
         "base/android/java/src/org/chromium/base/ApplicationStatus.java",
         "base/android/java/src/org/chromium/base/EarlyTraceEvent.java",
         "base/android/java/src/org/chromium/base/ThreadUtils.java",
-        "base/android/java/src/org/chromium/base/TraceEvent.java",
         "base/android/java/src/org/chromium/base/task/PostTask.java",
         "base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/tasks_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/tasks_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/tasks_jni " +
+         "'$(genDir)/base/tasks_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/tasks_jni.srcjar " +
+         "'$(genDir)/base/tasks_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/tasks_jni_placeholder.srcjar " +
+         "'$(genDir)/base/tasks_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ApplicationStatus_jni.h " +
@@ -5651,23 +8879,19 @@
          "--output-name " +
          "ThreadUtils_jni.h " +
          "--output-name " +
-         "TraceEvent_jni.h " +
-         "--output-name " +
          "PostTask_jni.h " +
          "--output-name " +
          "TaskRunnerImpl_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ApplicationStatus.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ApplicationStatus.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/EarlyTraceEvent.java) " +
+         "'$(location base/android/java/src/org/chromium/base/EarlyTraceEvent.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ThreadUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ThreadUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/TraceEvent.java) " +
+         "'$(location base/android/java/src/org/chromium/base/task/PostTask.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/task/PostTask.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java) " +
+         "'$(location base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     out: [
@@ -5677,7 +8901,7 @@
         "base/tasks_jni/PostTask_jni.h",
         "base/tasks_jni/TaskRunnerImpl_jni.h",
         "base/tasks_jni/ThreadUtils_jni.h",
-        "base/tasks_jni/TraceEvent_jni.h",
+        "base/tasks_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -5710,20 +8934,21 @@
         "base/android/java/src/org/chromium/base/ApplicationStatus.java",
         "base/android/java/src/org/chromium/base/EarlyTraceEvent.java",
         "base/android/java/src/org/chromium/base/ThreadUtils.java",
-        "base/android/java/src/org/chromium/base/TraceEvent.java",
         "base/android/java/src/org/chromium/base/task/PostTask.java",
         "base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/tasks_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/tasks_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/tasks_jni " +
+         "'$(genDir)/base/tasks_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/tasks_jni.srcjar " +
+         "'$(genDir)/base/tasks_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/tasks_jni_placeholder.srcjar " +
+         "'$(genDir)/base/tasks_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ApplicationStatus_jni.h " +
@@ -5732,23 +8957,19 @@
          "--output-name " +
          "ThreadUtils_jni.h " +
          "--output-name " +
-         "TraceEvent_jni.h " +
-         "--output-name " +
          "PostTask_jni.h " +
          "--output-name " +
          "TaskRunnerImpl_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ApplicationStatus.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ApplicationStatus.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/EarlyTraceEvent.java) " +
+         "'$(location base/android/java/src/org/chromium/base/EarlyTraceEvent.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ThreadUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ThreadUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/TraceEvent.java) " +
+         "'$(location base/android/java/src/org/chromium/base/task/PostTask.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/task/PostTask.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java)",
+         "'$(location base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java)'",
     host_cross_supported: false,
     out: [
         "base/tasks_jni.srcjar",
@@ -5757,7 +8978,7 @@
         "base/tasks_jni/PostTask_jni.h",
         "base/tasks_jni/TaskRunnerImpl_jni.h",
         "base/tasks_jni/ThreadUtils_jni.h",
-        "base/tasks_jni/TraceEvent_jni.h",
+        "base/tasks_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -5793,20 +9014,21 @@
         "base/android/java/src/org/chromium/base/ApplicationStatus.java",
         "base/android/java/src/org/chromium/base/EarlyTraceEvent.java",
         "base/android/java/src/org/chromium/base/ThreadUtils.java",
-        "base/android/java/src/org/chromium/base/TraceEvent.java",
         "base/android/java/src/org/chromium/base/task/PostTask.java",
         "base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java",
     ],
     cmd: "mkdir -p $(genDir)/base &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/tasks_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/tasks_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/tasks_jni " +
+         "'$(genDir)/base/tasks_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/tasks_jni.srcjar " +
+         "'$(genDir)/base/tasks_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/tasks_jni_placeholder.srcjar " +
+         "'$(genDir)/base/tasks_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ApplicationStatus_jni.h " +
@@ -5815,23 +9037,19 @@
          "--output-name " +
          "ThreadUtils_jni.h " +
          "--output-name " +
-         "TraceEvent_jni.h " +
-         "--output-name " +
          "PostTask_jni.h " +
          "--output-name " +
          "TaskRunnerImpl_jni.h " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ApplicationStatus.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ApplicationStatus.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/EarlyTraceEvent.java) " +
+         "'$(location base/android/java/src/org/chromium/base/EarlyTraceEvent.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/ThreadUtils.java) " +
+         "'$(location base/android/java/src/org/chromium/base/ThreadUtils.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/TraceEvent.java) " +
+         "'$(location base/android/java/src/org/chromium/base/task/PostTask.java)' " +
          "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/task/PostTask.java) " +
-         "--input-file " +
-         "$(location base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java)",
+         "'$(location base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java)'",
     out: [
         "base/tasks_jni.srcjar",
         "base/tasks_jni/ApplicationStatus_jni.h",
@@ -5839,7 +9057,7 @@
         "base/tasks_jni/PostTask_jni.h",
         "base/tasks_jni/TaskRunnerImpl_jni.h",
         "base/tasks_jni/ThreadUtils_jni.h",
-        "base/tasks_jni/TraceEvent_jni.h",
+        "base/tasks_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -5865,6 +9083,354 @@
     ],
 }
 
+// GN: //base:tasks_jni_java__process_device
+java_genrule {
+    name: "tot_cronet_base_tasks_jni_java__process_device",
+    srcs: [
+        ":tot_cronet_base_tasks_jni_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/tasks_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_jni_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_tasks_jni_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_tasks_jni_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/tasks_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_minimal_jni__action
+cc_genrule {
+    name: "tot_cronet_base_tasks_minimal_jni__action",
+    srcs: [
+        "base/android/java/src/org/chromium/base/TraceEvent.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/tasks_minimal_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/tasks_minimal_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/tasks_minimal_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/tasks_minimal_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "TraceEvent_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/TraceEvent.java)' " +
+         "--package-prefix " +
+         "android.net.connectivity",
+    host_cross_supported: false,
+    out: [
+        "base/tasks_minimal_jni.srcjar",
+        "base/tasks_minimal_jni/TraceEvent_jni.h",
+        "base/tasks_minimal_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_minimal_jni__action
+java_genrule {
+    name: "tot_cronet_base_tasks_minimal_jni__action__java",
+    srcs: [
+        "base/android/java/src/org/chromium/base/TraceEvent.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/tasks_minimal_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/tasks_minimal_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/tasks_minimal_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/tasks_minimal_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "TraceEvent_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/TraceEvent.java)' " +
+         "--package-prefix " +
+         "android.net.connectivity",
+    out: [
+        "base/tasks_minimal_jni.srcjar",
+        "base/tasks_minimal_jni/TraceEvent_jni.h",
+        "base/tasks_minimal_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_minimal_jni__action__testing
+cc_genrule {
+    name: "tot_cronet_base_tasks_minimal_jni__action__testing",
+    srcs: [
+        "base/android/java/src/org/chromium/base/TraceEvent.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/tasks_minimal_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/tasks_minimal_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/tasks_minimal_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/tasks_minimal_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "TraceEvent_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/TraceEvent.java)'",
+    host_cross_supported: false,
+    out: [
+        "base/tasks_minimal_jni.srcjar",
+        "base/tasks_minimal_jni/TraceEvent_jni.h",
+        "base/tasks_minimal_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_minimal_jni__action__testing
+java_genrule {
+    name: "tot_cronet_base_tasks_minimal_jni__action__testing__java",
+    srcs: [
+        "base/android/java/src/org/chromium/base/TraceEvent.java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "mkdir -p $(genDir)/jni_headers/base/tasks_minimal_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
+         "--output-dir " +
+         "'$(genDir)/base/tasks_minimal_jni' " +
+         "--extra-include " +
+         "third_party/jni_zero/jni_zero_internal.h " +
+         "--srcjar-path " +
+         "'$(genDir)/base/tasks_minimal_jni.srcjar' " +
+         "--placeholder-srcjar-path " +
+         "'$(genDir)/base/tasks_minimal_jni_placeholder.srcjar' " +
+         "--use-proxy-hash " +
+         "--output-name " +
+         "TraceEvent_jni.h " +
+         "--input-file " +
+         "'$(location base/android/java/src/org/chromium/base/TraceEvent.java)'",
+    out: [
+        "base/tasks_minimal_jni.srcjar",
+        "base/tasks_minimal_jni/TraceEvent_jni.h",
+        "base/tasks_minimal_jni_placeholder.srcjar",
+    ],
+    tool_files: [
+        "third_party/jni_zero/codegen/called_by_native_header.py",
+        "third_party/jni_zero/codegen/convert_type.py",
+        "third_party/jni_zero/codegen/gen_jni_java.py",
+        "third_party/jni_zero/codegen/header_common.py",
+        "third_party/jni_zero/codegen/natives_header.py",
+        "third_party/jni_zero/codegen/placeholder_gen_jni_java.py",
+        "third_party/jni_zero/codegen/placeholder_java_type.py",
+        "third_party/jni_zero/codegen/proxy_impl_java.py",
+        "third_party/jni_zero/codegen/register_natives.py",
+        "third_party/jni_zero/common.py",
+        "third_party/jni_zero/java_lang_classes.py",
+        "third_party/jni_zero/java_types.py",
+        "third_party/jni_zero/jni_generator.py",
+        "third_party/jni_zero/jni_registration_generator.py",
+        "third_party/jni_zero/jni_zero.py",
+        "third_party/jni_zero/parse.py",
+        "third_party/jni_zero/proxy.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_minimal_jni_java__process_device
+java_genrule {
+    name: "tot_cronet_base_tasks_minimal_jni_java__process_device",
+    srcs: [
+        ":tot_cronet_base_tasks_minimal_jni_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/tasks_minimal_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_minimal_jni_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_tasks_minimal_jni_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "base/tasks_minimal_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base/test:base_unittests_jni_headers__action__testing
 cc_genrule {
     name: "tot_cronet_base_test_base_unittests_jni_headers__action__testing",
@@ -5873,29 +9439,32 @@
         "base/test/android/java/src/org/chromium/base/JavaHandlerThreadHelpers.java",
     ],
     cmd: "mkdir -p $(genDir)/base/test &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/test/base_unittests_jni_headers && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/test/base_unittests_jni_headers &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/test/base_unittests_jni_headers " +
+         "'$(genDir)/base/test/base_unittests_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/test/base_unittests_jni_headers.srcjar " +
+         "'$(genDir)/base/test/base_unittests_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/test/base_unittests_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/base/test/base_unittests_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "ContentUriTestUtils_jni.h " +
          "--output-name " +
          "JavaHandlerThreadHelpers_jni.h " +
          "--input-file " +
-         "$(location base/test/android/java/src/org/chromium/base/ContentUriTestUtils.java) " +
+         "'$(location base/test/android/java/src/org/chromium/base/ContentUriTestUtils.java)' " +
          "--input-file " +
-         "$(location base/test/android/java/src/org/chromium/base/JavaHandlerThreadHelpers.java)",
+         "'$(location base/test/android/java/src/org/chromium/base/JavaHandlerThreadHelpers.java)'",
     host_cross_supported: false,
     out: [
         "base/test/base_unittests_jni_headers.srcjar",
         "base/test/base_unittests_jni_headers/ContentUriTestUtils_jni.h",
         "base/test/base_unittests_jni_headers/JavaHandlerThreadHelpers_jni.h",
+        "base/test/base_unittests_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -6126,9 +9695,9 @@
         "-DANDROID",
         "-DANDROID_NDK_VERSION_ROLL=r27_1",
         "-DBENCHMARK_STATIC_DEFINE",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.130/include/cxx.h\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.146/include/cxx.h\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DGTEST_API_=",
         "-DGTEST_HAS_ABSL",
@@ -6233,15 +9802,17 @@
         "base/test/android/javatests/src/org/chromium/base/test/util/UrlUtils.java",
     ],
     cmd: "mkdir -p $(genDir)/base/test &&  " +
-         "mkdir -p $(genDir)/jni_headers/base/test/test_support_jni_headers && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/base/test/test_support_jni_headers &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/base/test/test_support_jni_headers " +
+         "'$(genDir)/base/test/test_support_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/base/test/test_support_jni_headers.srcjar " +
+         "'$(genDir)/base/test/test_support_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/base/test/test_support_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/base/test/test_support_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "MainReturnCodeResult_jni.h " +
@@ -6252,13 +9823,13 @@
          "--output-name " +
          "UrlUtils_jni.h " +
          "--input-file " +
-         "$(location base/test/android/java/src/org/chromium/base/MainReturnCodeResult.java) " +
+         "'$(location base/test/android/java/src/org/chromium/base/MainReturnCodeResult.java)' " +
          "--input-file " +
-         "$(location base/test/android/java/src/org/chromium/base/MultiprocessTestClientLauncher.java) " +
+         "'$(location base/test/android/java/src/org/chromium/base/MultiprocessTestClientLauncher.java)' " +
          "--input-file " +
-         "$(location base/test/android/javatests/src/org/chromium/base/test/task/ThreadPoolTestHelpers.java) " +
+         "'$(location base/test/android/javatests/src/org/chromium/base/test/task/ThreadPoolTestHelpers.java)' " +
          "--input-file " +
-         "$(location base/test/android/javatests/src/org/chromium/base/test/util/UrlUtils.java)",
+         "'$(location base/test/android/javatests/src/org/chromium/base/test/util/UrlUtils.java)'",
     host_cross_supported: false,
     out: [
         "base/test/test_support_jni_headers.srcjar",
@@ -6266,6 +9837,7 @@
         "base/test/test_support_jni_headers/MultiprocessTestClientLauncher_jni.h",
         "base/test/test_support_jni_headers/ThreadPoolTestHelpers_jni.h",
         "base/test/test_support_jni_headers/UrlUtils_jni.h",
+        "base/test/test_support_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -6294,12 +9866,78 @@
     ],
 }
 
+// GN: //base:time_utils_java__process_device
+java_genrule {
+    name: "tot_cronet_base_time_utils_java__process_device",
+    srcs: [
+        ":tot_cronet_base_time_utils_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/time_utils_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:time_utils_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_time_utils_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_time_utils_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/time_utils_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:tracing_buildflags
 cc_genrule {
     name: "tot_cronet_base_tracing_buildflags",
-    cmd: "mkdir -p $(genDir)/base && echo '--flags ENABLE_BASE_TRACING=\"false\" USE_PERFETTO_TRACE_PROCESSOR=\"true\" OPTIONAL_TRACE_EVENTS_ENABLED=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags ENABLE_BASE_TRACING=false USE_PERFETTO_TRACE_PROCESSOR=true OPTIONAL_TRACE_EVENTS_ENABLED=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:tracing_buildflags " +
          "--gen-dir " +
@@ -6326,76 +9964,88 @@
     name: "tot_cronet_base_tracing_buildflags__testing",
     cmd: "if [[ ( $$CC_ARCH == 'arm' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base && echo '--flags ENABLE_BASE_TRACING=\"false\" USE_PERFETTO_TRACE_PROCESSOR=\"true\" OPTIONAL_TRACE_EVENTS_ENABLED=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags ENABLE_BASE_TRACING=false USE_PERFETTO_TRACE_PROCESSOR=true OPTIONAL_TRACE_EVENTS_ENABLED=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:tracing_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'arm64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base && echo '--flags ENABLE_BASE_TRACING=\"false\" USE_PERFETTO_TRACE_PROCESSOR=\"true\" OPTIONAL_TRACE_EVENTS_ENABLED=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags ENABLE_BASE_TRACING=false USE_PERFETTO_TRACE_PROCESSOR=true OPTIONAL_TRACE_EVENTS_ENABLED=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:tracing_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'riscv64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base && echo '--flags ENABLE_BASE_TRACING=\"false\" USE_PERFETTO_TRACE_PROCESSOR=\"true\" OPTIONAL_TRACE_EVENTS_ENABLED=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags ENABLE_BASE_TRACING=false USE_PERFETTO_TRACE_PROCESSOR=true OPTIONAL_TRACE_EVENTS_ENABLED=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:tracing_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base && echo '--flags ENABLE_BASE_TRACING=\"false\" USE_PERFETTO_TRACE_PROCESSOR=\"true\" OPTIONAL_TRACE_EVENTS_ENABLED=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags ENABLE_BASE_TRACING=false USE_PERFETTO_TRACE_PROCESSOR=true OPTIONAL_TRACE_EVENTS_ENABLED=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:tracing_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86_64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base && echo '--flags ENABLE_BASE_TRACING=\"false\" USE_PERFETTO_TRACE_PROCESSOR=\"true\" OPTIONAL_TRACE_EVENTS_ENABLED=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags ENABLE_BASE_TRACING=false USE_PERFETTO_TRACE_PROCESSOR=true OPTIONAL_TRACE_EVENTS_ENABLED=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:tracing_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ $$CC_OS != 'android' ]]; " +
          "then " +
-         "mkdir -p $(genDir)/base && echo '--flags ENABLE_BASE_TRACING=\"false\" USE_PERFETTO_TRACE_PROCESSOR=\"true\" OPTIONAL_TRACE_EVENTS_ENABLED=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/base &&  " +
+         "echo '--flags ENABLE_BASE_TRACING=false USE_PERFETTO_TRACE_PROCESSOR=true OPTIONAL_TRACE_EVENTS_ENABLED=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//base:tracing_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi;",
+         "/dev/stdin " +
+         ";fi;",
     host_supported: true,
     host_cross_supported: false,
     out: [
@@ -6412,11 +10062,409 @@
     ],
 }
 
+// GN: //base:unowned_user_data_java__process_device
+java_genrule {
+    name: "tot_cronet_base_unowned_user_data_java__process_device",
+    srcs: [
+        ":tot_cronet_base_unowned_user_data_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/unowned_user_data_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:unowned_user_data_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_unowned_user_data_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_unowned_user_data_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/unowned_user_data_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base/version_info/android:channel_enum_java__process_device
+java_genrule {
+    name: "tot_cronet_base_version_info_android_channel_enum_java__process_device",
+    srcs: [
+        ":tot_cronet_base_version_info_android_channel_enum_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base/version_info/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/version_info/android/channel_enum_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base/version_info/android:channel_enum_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_version_info_android_channel_enum_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_version_info_android_channel_enum_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base/version_info/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/version_info/android/channel_enum_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base/version_info/android:channel_enum_srcjar
+java_genrule {
+    name: "tot_cronet_base_version_info_android_channel_enum_srcjar",
+    cmd: "mkdir -p $(genDir)/base/version_info/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/version_info/channel.h)'",
+    out: [
+        "base/version_info/android/channel_enum_srcjar.srcjar",
+    ],
+    tool_files: [
+        "base/version_info/channel.h",
+        "build/action_helpers.py",
+        "build/android/gyp/java_cpp_enum.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/android/gyp/util/java_cpp_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base/version_info/android:channel_enum_srcjar__testing
+java_genrule {
+    name: "tot_cronet_base_version_info_android_channel_enum_srcjar__testing",
+    cmd: "mkdir -p $(genDir)/base/version_info/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location base/version_info/channel.h)'",
+    out: [
+        "base/version_info/android/channel_enum_srcjar.srcjar",
+    ],
+    tool_files: [
+        "base/version_info/channel.h",
+        "build/action_helpers.py",
+        "build/android/gyp/java_cpp_enum.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/android/gyp/util/java_cpp_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base/version_info/android:generate_version_constants
+java_genrule {
+    name: "tot_cronet_base_version_info_android_generate_version_constants",
+    cmd: "mkdir -p $(genDir)/base/version_info/android/java/org/chromium/base/version_info &&  " +
+         "$(location build/util/version.py) " +
+         "--official " +
+         "-f " +
+         "'$(location chrome/VERSION)' " +
+         "-e " +
+         "'CHANNEL=str.upper('\"'\"'default'\"'\"')' " +
+         "-o " +
+         "'$(out)' " +
+         "'$(location base/version_info/android/java/VersionConstants.java.version)'",
+    out: [
+        "base/version_info/android/java/org/chromium/base/version_info/VersionConstants.java",
+    ],
+    tool_files: [
+        "base/version_info/android/java/VersionConstants.java.version",
+        "build/util/LASTCHANGE",
+        "build/util/android_chrome_version.py",
+        "build/util/version.py",
+        "chrome/VERSION",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base/version_info/android:generate_version_constants__testing
+java_genrule {
+    name: "tot_cronet_base_version_info_android_generate_version_constants__testing",
+    cmd: "mkdir -p $(genDir)/base/version_info/android/java/org/chromium/base/version_info &&  " +
+         "$(location build/util/version.py) " +
+         "--official " +
+         "-f " +
+         "'$(location chrome/VERSION)' " +
+         "-e " +
+         "'CHANNEL=str.upper('\"'\"'default'\"'\"')' " +
+         "-o " +
+         "'$(out)' " +
+         "'$(location base/version_info/android/java/VersionConstants.java.version)'",
+    out: [
+        "base/version_info/android/java/org/chromium/base/version_info/VersionConstants.java",
+    ],
+    tool_files: [
+        "base/version_info/android/java/VersionConstants.java.version",
+        "build/util/LASTCHANGE",
+        "build/util/android_chrome_version.py",
+        "build/util/version.py",
+        "chrome/VERSION",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base/version_info/android:version_constants_java__process_device
+java_genrule {
+    name: "tot_cronet_base_version_info_android_version_constants_java__process_device",
+    srcs: [
+        ":tot_cronet_base_version_info_android_version_constants_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/base/version_info/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/version_info/android/version_constants_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base/version_info/android:version_constants_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_base_version_info_android_version_constants_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_base_version_info_android_version_constants_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/base/version_info/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "base/version_info/android/version_constants_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //build/android:build_java__process_device
+java_genrule {
+    name: "tot_cronet_build_android_build_java__process_device",
+    srcs: [
+        ":tot_cronet_build_android_build_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/build/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/build/BuildConfig.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "build/android/build_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //build/android:build_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_build_android_build_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_build_android_build_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/build/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/build/BuildConfig.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "build/android/build_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //build/android/gtest_apk:native_test_instrumentation_test_runner_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_build_android_gtest_apk_native_test_instrumentation_test_runner_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_build_android_gtest_apk_native_test_instrumentation_test_runner_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/build/android/gtest_apk &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "build/android/gtest_apk/native_test_instrumentation_test_runner_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //build/android:native_libraries_gen
 java_genrule {
     name: "tot_cronet_build_android_native_libraries_gen",
-    cmd: "mkdir -p $(genDir)/build/android && $(location build/android/gyp/write_native_libraries_java.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build/android &&  " +
+         "$(location build/android/gyp/write_native_libraries_java.py) " +
+         "--output " +
+         "'$(out)' " +
          "--cpu-family " +
          "CPU_FAMILY_ARM",
     out: [
@@ -6438,8 +10486,10 @@
 // GN: //build/android:native_libraries_gen__testing
 java_genrule {
     name: "tot_cronet_build_android_native_libraries_gen__testing",
-    cmd: "mkdir -p $(genDir)/build/android && $(location build/android/gyp/write_native_libraries_java.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build/android &&  " +
+         "$(location build/android/gyp/write_native_libraries_java.py) " +
+         "--output " +
+         "'$(out)' " +
          "--cpu-family " +
          "CPU_FAMILY_ARM",
     out: [
@@ -6565,9 +10615,11 @@
 // GN: //build:blink_buildflags
 cc_genrule {
     name: "tot_cronet_build_blink_buildflags",
-    cmd: "mkdir -p $(genDir)/build && echo '--flags USE_BLINK=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build &&  " +
+         "echo '--flags USE_BLINK=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build:blink_buildflags " +
          "--gen-dir " +
@@ -6592,9 +10644,11 @@
 // GN: //build:blink_buildflags__testing
 cc_genrule {
     name: "tot_cronet_build_blink_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/build && echo '--flags USE_BLINK=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build &&  " +
+         "echo '--flags USE_BLINK=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build:blink_buildflags " +
          "--gen-dir " +
@@ -6620,9 +10674,11 @@
 // GN: //build:branding_buildflags
 cc_genrule {
     name: "tot_cronet_build_branding_buildflags",
-    cmd: "mkdir -p $(genDir)/build && echo '--flags CHROMIUM_BRANDING=\"1\" GOOGLE_CHROME_BRANDING=\"0\" CHROME_FOR_TESTING=\"0\" GOOGLE_CHROME_FOR_TESTING_BRANDING=\"0\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build &&  " +
+         "echo '--flags CHROMIUM_BRANDING=1 GOOGLE_CHROME_BRANDING=0 CHROME_FOR_TESTING=0 GOOGLE_CHROME_FOR_TESTING_BRANDING=0' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build:branding_buildflags " +
          "--gen-dir " +
@@ -6647,9 +10703,11 @@
 // GN: //build:branding_buildflags__testing
 cc_genrule {
     name: "tot_cronet_build_branding_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/build && echo '--flags CHROMIUM_BRANDING=\"1\" GOOGLE_CHROME_BRANDING=\"0\" CHROME_FOR_TESTING=\"0\" GOOGLE_CHROME_FOR_TESTING_BRANDING=\"0\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build &&  " +
+         "echo '--flags CHROMIUM_BRANDING=1 GOOGLE_CHROME_BRANDING=0 CHROME_FOR_TESTING=0 GOOGLE_CHROME_FOR_TESTING_BRANDING=0' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build:branding_buildflags " +
          "--gen-dir " +
@@ -6675,9 +10733,11 @@
 // GN: //build:chromecast_buildflags
 cc_genrule {
     name: "tot_cronet_build_chromecast_buildflags",
-    cmd: "mkdir -p $(genDir)/build && echo '--flags IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" ENABLE_CAST_RECEIVER=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build &&  " +
+         "echo '--flags IS_CASTOS=false IS_CAST_ANDROID=false ENABLE_CAST_RECEIVER=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build:chromecast_buildflags " +
          "--gen-dir " +
@@ -6702,9 +10762,11 @@
 // GN: //build:chromecast_buildflags__testing
 cc_genrule {
     name: "tot_cronet_build_chromecast_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/build && echo '--flags IS_CASTOS=\"false\" IS_CAST_ANDROID=\"false\" ENABLE_CAST_RECEIVER=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build &&  " +
+         "echo '--flags IS_CASTOS=false IS_CAST_ANDROID=false ENABLE_CAST_RECEIVER=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build:chromecast_buildflags " +
          "--gen-dir " +
@@ -6730,15 +10792,18 @@
 // GN: //build:chromeos_buildflags
 cc_genrule {
     name: "tot_cronet_build_chromeos_buildflags",
-    cmd: "mkdir -p $(genDir)/build && echo '--flags IS_CHROMEOS_DEVICE=\"false\" IS_CHROMEOS_LACROS=\"false\" IS_CHROMEOS_ASH=\"false\" IS_CHROMEOS_WITH_HW_DETAILS=\"false\" IS_REVEN=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build &&  " +
+         "echo '--flags IS_CHROMEOS_DEVICE=false IS_CHROMEOS_ASH=false IS_CHROMEOS_WITH_HW_DETAILS=false IS_REVEN=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build:chromeos_buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
          "/dev/stdin",
+    host_supported: true,
     host_cross_supported: false,
     out: [
         "build/chromeos_buildflags.h",
@@ -6757,9 +10822,11 @@
 // GN: //build:chromeos_buildflags__testing
 cc_genrule {
     name: "tot_cronet_build_chromeos_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/build && echo '--flags IS_CHROMEOS_DEVICE=\"false\" IS_CHROMEOS_LACROS=\"false\" IS_CHROMEOS_ASH=\"false\" IS_CHROMEOS_WITH_HW_DETAILS=\"false\" IS_REVEN=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build &&  " +
+         "echo '--flags IS_CHROMEOS_DEVICE=false IS_CHROMEOS_ASH=false IS_CHROMEOS_WITH_HW_DETAILS=false IS_REVEN=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build:chromeos_buildflags " +
          "--gen-dir " +
@@ -6785,9 +10852,11 @@
 // GN: //build/config/compiler:compiler_buildflags
 cc_genrule {
     name: "tot_cronet_build_config_compiler_compiler_buildflags",
-    cmd: "mkdir -p $(genDir)/build/config/compiler && echo '--flags CLANG_PGO=\"0\" SYMBOL_LEVEL=\"1\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build/config/compiler &&  " +
+         "echo '--flags CLANG_PGO=0 SYMBOL_LEVEL=1' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build/config/compiler:compiler_buildflags " +
          "--gen-dir " +
@@ -6812,9 +10881,11 @@
 // GN: //build/config/compiler:compiler_buildflags__testing
 cc_genrule {
     name: "tot_cronet_build_config_compiler_compiler_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/build/config/compiler && echo '--flags CLANG_PGO=\"0\" SYMBOL_LEVEL=\"1\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build/config/compiler &&  " +
+         "echo '--flags CLANG_PGO=0 SYMBOL_LEVEL=1' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build/config/compiler:compiler_buildflags " +
          "--gen-dir " +
@@ -6840,9 +10911,11 @@
 // GN: //build:ios_buildflags
 cc_genrule {
     name: "tot_cronet_build_ios_buildflags",
-    cmd: "mkdir -p $(genDir)/build && echo '--flags IS_IOS_APP_EXTENSION=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build &&  " +
+         "echo '--flags IS_IOS_APP_EXTENSION=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build:ios_buildflags " +
          "--gen-dir " +
@@ -6867,9 +10940,11 @@
 // GN: //build:ios_buildflags__testing
 cc_genrule {
     name: "tot_cronet_build_ios_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/build && echo '--flags IS_IOS_APP_EXTENSION=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build &&  " +
+         "echo '--flags IS_IOS_APP_EXTENSION=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build:ios_buildflags " +
          "--gen-dir " +
@@ -6895,9 +10970,11 @@
 // GN: //build:robolectric_buildflags
 cc_genrule {
     name: "tot_cronet_build_robolectric_buildflags",
-    cmd: "mkdir -p $(genDir)/build && echo '--flags IS_ROBOLECTRIC=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build &&  " +
+         "echo '--flags IS_ROBOLECTRIC=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build:robolectric_buildflags " +
          "--gen-dir " +
@@ -6922,9 +10999,11 @@
 // GN: //build:robolectric_buildflags__testing
 cc_genrule {
     name: "tot_cronet_build_robolectric_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/build && echo '--flags IS_ROBOLECTRIC=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/build &&  " +
+         "echo '--flags IS_ROBOLECTRIC=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//build:robolectric_buildflags " +
          "--gen-dir " +
@@ -6950,7 +11029,7 @@
 cc_library_static {
     name: "tot_cronet_build_rust_cxx_cppdeps",
     srcs: [
-        "third_party/rust/chromium_crates_io/vendor/cxx-1.0.130/src/cxx.cc",
+        "third_party/rust/chromium_crates_io/vendor/cxx-1.0.146/src/cxx.cc",
     ],
     host_cross_supported: false,
     defaults: [
@@ -6959,9 +11038,9 @@
     cflags: [
         "-DANDROID",
         "-DANDROID_NDK_VERSION_ROLL=r27_1",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.130/include/cxx.h\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.146/include/cxx.h\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DCXX_RS_EXPORT=",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DHAVE_SYS_UIO_H",
@@ -7034,7 +11113,7 @@
 cc_library_static {
     name: "tot_cronet_build_rust_cxx_cppdeps__testing",
     srcs: [
-        "third_party/rust/chromium_crates_io/vendor/cxx-1.0.130/src/cxx.cc",
+        "third_party/rust/chromium_crates_io/vendor/cxx-1.0.146/src/cxx.cc",
     ],
     host_supported: true,
     host_cross_supported: false,
@@ -7042,9 +11121,9 @@
         "tot_cronet_cc_defaults",
     ],
     cflags: [
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.130/include/cxx.h\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.146/include/cxx.h\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DCXX_RS_EXPORT=",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DNDEBUG",
@@ -7134,7 +11213,7 @@
         },
         host: {
             cflags: [
-                "-DCR_SYSROOT_KEY=20230611T210420Z-2",
+                "-DCR_SYSROOT_KEY=20250129T203412Z-1",
                 "-DNO_UNWIND_TABLES",
                 "-DUSE_AURA=1",
                 "-DUSE_OZONE=1",
@@ -7267,8 +11346,8 @@
         "tot_cronet_cc_defaults",
     ],
     cflags: [
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DLIBCXXABI_SILENT_TERMINATE",
         "-DNDEBUG",
@@ -7380,7 +11459,7 @@
                 "third_party/libc++abi/src/src/cxa_demangle.cpp",
             ],
             cflags: [
-                "-DCR_SYSROOT_KEY=20230611T210420Z-2",
+                "-DCR_SYSROOT_KEY=20250129T203412Z-1",
                 "-DNO_UNWIND_TABLES",
                 "-DUSE_AURA=1",
                 "-DUSE_OZONE=1",
@@ -7424,8 +11503,8 @@
         "tot_cronet_cc_defaults",
     ],
     cflags: [
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DLIBCXXABI_SILENT_TERMINATE",
         "-DNDEBUG",
@@ -7537,7 +11616,7 @@
                 "third_party/libc++abi/src/src/cxa_demangle.cpp",
             ],
             cflags: [
-                "-DCR_SYSROOT_KEY=20230611T210420Z-2",
+                "-DCR_SYSROOT_KEY=20250129T203412Z-1",
                 "-DNO_UNWIND_TABLES",
                 "-DUSE_AURA=1",
                 "-DUSE_OZONE=1",
@@ -7604,16 +11683,18 @@
 // GN: //components/cronet/android:api_version
 java_genrule {
     name: "tot_cronet_components_cronet_android_api_version",
-    cmd: "mkdir -p $(genDir)/components/cronet/android/templates/org/chromium/net && $(location build/util/version.py) --official " +
+    cmd: "mkdir -p $(genDir)/components/cronet/android/templates/org/chromium/net &&  " +
+         "$(location build/util/version.py) " +
+         "--official " +
          "-f " +
-         "$(location chrome/VERSION) " +
+         "'$(location chrome/VERSION)' " +
          "-f " +
-         "$(location build/util/LASTCHANGE) " +
+         "'$(location build/util/LASTCHANGE)' " +
          "-e " +
-         "'API_LEVEL=34' " +
+         "API_LEVEL=34 " +
          "-o " +
-         "$(out) " +
-         "$(location components/cronet/android/api/src/org/chromium/net/ApiVersion.template)",
+         "'$(out)' " +
+         "'$(location components/cronet/android/api/src/org/chromium/net/ApiVersion.template)'",
     out: [
         "components/cronet/android/templates/org/chromium/net/ApiVersion.java",
     ],
@@ -7632,16 +11713,18 @@
 // GN: //components/cronet/android:api_version__testing
 java_genrule {
     name: "tot_cronet_components_cronet_android_api_version__testing",
-    cmd: "mkdir -p $(genDir)/components/cronet/android/templates/org/chromium/net && $(location build/util/version.py) --official " +
+    cmd: "mkdir -p $(genDir)/components/cronet/android/templates/org/chromium/net &&  " +
+         "$(location build/util/version.py) " +
+         "--official " +
          "-f " +
-         "$(location chrome/VERSION) " +
+         "'$(location chrome/VERSION)' " +
          "-f " +
-         "$(location build/util/LASTCHANGE) " +
+         "'$(location build/util/LASTCHANGE)' " +
          "-e " +
-         "'API_LEVEL=34' " +
+         "API_LEVEL=34 " +
          "-o " +
-         "$(out) " +
-         "$(location components/cronet/android/api/src/org/chromium/net/ApiVersion.template)",
+         "'$(out)' " +
+         "'$(location components/cronet/android/api/src/org/chromium/net/ApiVersion.template)'",
     out: [
         "components/cronet/android/templates/org/chromium/net/ApiVersion.java",
     ],
@@ -7657,6 +11740,70 @@
     ],
 }
 
+// GN: //components/cronet/android:base_feature_overrides_java_proto__process_device
+java_genrule {
+    name: "tot_cronet_components_cronet_android_base_feature_overrides_java_proto__process_device",
+    srcs: [
+        ":tot_cronet_components_cronet_android_base_feature_overrides_java_proto__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/base_feature_overrides_java_proto.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:base_feature_overrides_java_proto__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_base_feature_overrides_java_proto__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_base_feature_overrides_java_proto__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/base_feature_overrides_java_proto.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //components/cronet/android:base_feature_overrides_java_proto__protoc_java
 java_genrule {
     name: "tot_cronet_components_cronet_android_base_feature_overrides_java_proto__protoc_java",
@@ -7666,13 +11813,15 @@
     tools: [
         "tot_cronet_third_party_protobuf_protoc",
     ],
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/protoc_java.py) --protoc " +
-         "$(location tot_cronet_third_party_protobuf_protoc) " +
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/protoc_java.py) " +
+         "--protoc " +
+         "'$(location tot_cronet_third_party_protobuf_protoc)' " +
          "--proto-path " +
          "external/cronet/tot/components/cronet/android " +
          "--srcjar " +
-         "$(out) " +
-         "$(location components/cronet/android/proto/base_feature_overrides.proto)",
+         "'$(out)' " +
+         "'$(location components/cronet/android/proto/base_feature_overrides.proto)'",
     out: [
         "components/cronet/android/base_feature_overrides_java_proto__protoc_java.srcjar",
     ],
@@ -7698,13 +11847,15 @@
     tools: [
         "tot_cronet_third_party_protobuf_protoc",
     ],
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/protoc_java.py) --protoc " +
-         "$(location tot_cronet_third_party_protobuf_protoc) " +
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/protoc_java.py) " +
+         "--protoc " +
+         "'$(location tot_cronet_third_party_protobuf_protoc)' " +
          "--proto-path " +
          "external/cronet/tot/components/cronet/android " +
          "--srcjar " +
-         "$(out) " +
-         "$(location components/cronet/android/proto/base_feature_overrides.proto)",
+         "'$(out)' " +
+         "'$(location components/cronet/android/proto/base_feature_overrides.proto)'",
     out: [
         "components/cronet/android/base_feature_overrides_java_proto__protoc_java.srcjar",
     ],
@@ -7721,6 +11872,568 @@
     ],
 }
 
+// GN: //components/cronet/android:base_feature_overrides_proto_gen
+cc_genrule {
+    name: "tot_cronet_components_cronet_android_base_feature_overrides_proto_gen",
+    srcs: [
+        "components/cronet/android/proto/base_feature_overrides.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/components/cronet/android/proto " +
+         "--cpp_out=lite=true:$(genDir)/components/cronet/android/proto/ " +
+         "external/cronet/tot/components/cronet/android/proto/base_feature_overrides.proto",
+    host_cross_supported: false,
+    out: [
+        "components/cronet/android/proto/base_feature_overrides.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:base_feature_overrides_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_components_cronet_android_base_feature_overrides_proto_gen__testing",
+    srcs: [
+        "components/cronet/android/proto/base_feature_overrides.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/components/cronet/android/proto " +
+         "--cpp_out=lite=true:$(genDir)/components/cronet/android/proto/ " +
+         "external/cronet/tot/components/cronet/android/proto/base_feature_overrides.proto",
+    host_cross_supported: false,
+    out: [
+        "components/cronet/android/proto/base_feature_overrides.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:base_feature_overrides_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_components_cronet_android_base_feature_overrides_proto_gen__testing_headers",
+    srcs: [
+        "components/cronet/android/proto/base_feature_overrides.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/components/cronet/android/proto " +
+         "--cpp_out=lite=true:$(genDir)/components/cronet/android/proto/ " +
+         "external/cronet/tot/components/cronet/android/proto/base_feature_overrides.proto",
+    out: [
+        "components/cronet/android/proto/base_feature_overrides.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "components/cronet/android/proto",
+        "protos",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
+// GN: //components/cronet/android:base_feature_overrides_proto_gen
+cc_genrule {
+    name: "tot_cronet_components_cronet_android_base_feature_overrides_proto_gen_headers",
+    srcs: [
+        "components/cronet/android/proto/base_feature_overrides.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/components/cronet/android/proto " +
+         "--cpp_out=lite=true:$(genDir)/components/cronet/android/proto/ " +
+         "external/cronet/tot/components/cronet/android/proto/base_feature_overrides.proto",
+    out: [
+        "components/cronet/android/proto/base_feature_overrides.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "components/cronet/android/proto",
+        "protos",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_api_helpers_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_api_helpers_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_api_helpers_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_api_helpers_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_api_java__process_device
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_api_java__process_device",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_api_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_api_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_api_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_api_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_api_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_api_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_build_config_srcjar
+genrule {
+    name: "tot_cronet_components_cronet_android_cronet_build_config_srcjar",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_build_config_srcjar_preprocess",
+    ],
+    tools: [
+        "soong_zip",
+    ],
+    cmd: "cp $(in) $(genDir)/BuildConfig.java && " +
+         "$(location soong_zip) -o $(out) -srcjar -C $(genDir) -f $(genDir)/BuildConfig.java",
+    out: [
+        "BuildConfig.srcjar",
+    ],
+    defaults: [
+        "tot_cronet_cc_defaults",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_build_config_srcjar__testing
+genrule {
+    name: "tot_cronet_components_cronet_android_cronet_build_config_srcjar__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_build_config_srcjar__testing_preprocess",
+    ],
+    tools: [
+        "soong_zip",
+    ],
+    cmd: "cp $(in) $(genDir)/BuildConfig.java && " +
+         "$(location soong_zip) -o $(out) -srcjar -C $(genDir) -f $(genDir)/BuildConfig.java",
+    out: [
+        "BuildConfig.srcjar",
+    ],
+    defaults: [
+        "tot_cronet_cc_defaults",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_build_config_srcjar__testing
+cc_preprocess_no_configuration {
+    name: "tot_cronet_components_cronet_android_cronet_build_config_srcjar__testing_preprocess",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_build_config_srcjar__testing_rename",
+    ],
+    cflags: [
+        "-DANDROID",
+        "-D_DISABLE_DEBUG_LOGS",
+        "-D_IS_CRONET_BUILD",
+        "-D_LOGTAG_PREFIX=cn_",
+        "-D_MIN_SDK_VERSION=23",
+        "-D_VERSION_CODE=1",
+        "-E",
+        "-P",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_build_config_srcjar__testing
+genrule {
+    name: "tot_cronet_components_cronet_android_cronet_build_config_srcjar__testing_rename",
+    srcs: [
+        "build/android/java/templates/BuildConfig.template",
+    ],
+    cmd: "cp $(in) $(out)",
+    out: [
+        "BuildConfig.cc",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_build_config_srcjar
+cc_preprocess_no_configuration {
+    name: "tot_cronet_components_cronet_android_cronet_build_config_srcjar_preprocess",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_build_config_srcjar_rename",
+    ],
+    cflags: [
+        "-DANDROID",
+        "-D_DISABLE_DEBUG_LOGS",
+        "-D_IS_CRONET_BUILD",
+        "-D_LOGTAG_PREFIX=cn_",
+        "-D_MIN_SDK_VERSION=23",
+        "-D_VERSION_CODE=1",
+        "-E",
+        "-P",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_build_config_srcjar
+genrule {
+    name: "tot_cronet_components_cronet_android_cronet_build_config_srcjar_rename",
+    srcs: [
+        "build/android/java/templates/BuildConfig.template",
+    ],
+    cmd: "cp $(in) $(out)",
+    out: [
+        "BuildConfig.cc",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_common_javatests__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_common_javatests__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_common_javatests__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_common_javatests.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_impl_common_java__process_device
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_impl_common_java__process_device",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_impl_common_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_impl_common_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_impl_common_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_impl_common_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_impl_common_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_impl_common_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_impl_java_util_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_impl_java_util_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_impl_java_util_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_impl_java_util_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_impl_native_java__process_device
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_impl_native_java__process_device",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_impl_native_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_impl_native_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_impl_native_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_impl_native_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_impl_native_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_impl_native_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_impl_platform_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_impl_platform_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_impl_platform_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_impl_platform_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_javatests__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_javatests__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_javatests__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_javatests.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //components/cronet/android:cronet_jni_headers__action
 cc_genrule {
     name: "tot_cronet_components_cronet_android_cronet_jni_headers__action",
@@ -7732,15 +12445,17 @@
         "components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_jni_headers && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_jni_headers &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/components/cronet/android/cronet_jni_headers " +
+         "'$(genDir)/components/cronet/android/cronet_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_headers.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "CronetBidirectionalStream_jni.h " +
@@ -7753,15 +12468,15 @@
          "--output-name " +
          "CronetUrlRequestContext_jni.h " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetBidirectionalStream.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetBidirectionalStream.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetLibraryLoader.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetLibraryLoader.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUploadDataStream.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUploadDataStream.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
@@ -7772,6 +12487,7 @@
         "components/cronet/android/cronet_jni_headers/CronetUploadDataStream_jni.h",
         "components/cronet/android/cronet_jni_headers/CronetUrlRequestContext_jni.h",
         "components/cronet/android/cronet_jni_headers/CronetUrlRequest_jni.h",
+        "components/cronet/android/cronet_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -7811,15 +12527,17 @@
         "components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_jni_headers && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_jni_headers &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/components/cronet/android/cronet_jni_headers " +
+         "'$(genDir)/components/cronet/android/cronet_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_headers.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "CronetBidirectionalStream_jni.h " +
@@ -7832,15 +12550,15 @@
          "--output-name " +
          "CronetUrlRequestContext_jni.h " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetBidirectionalStream.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetBidirectionalStream.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetLibraryLoader.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetLibraryLoader.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUploadDataStream.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUploadDataStream.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     out: [
@@ -7850,6 +12568,7 @@
         "components/cronet/android/cronet_jni_headers/CronetUploadDataStream_jni.h",
         "components/cronet/android/cronet_jni_headers/CronetUrlRequestContext_jni.h",
         "components/cronet/android/cronet_jni_headers/CronetUrlRequest_jni.h",
+        "components/cronet/android/cronet_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -7875,6 +12594,18 @@
     ],
 }
 
+// GN: //components/cronet/android:cronet_jni_headers__action
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_jni_headers__action__java_proxy_only",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_jni_headers__action__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "cronet_jni_headers.srcjar",
+    ],
+}
+
 // GN: //components/cronet/android:cronet_jni_headers__action__testing
 cc_genrule {
     name: "tot_cronet_components_cronet_android_cronet_jni_headers__action__testing",
@@ -7886,15 +12617,17 @@
         "components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_jni_headers && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_jni_headers &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/components/cronet/android/cronet_jni_headers " +
+         "'$(genDir)/components/cronet/android/cronet_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_headers.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "CronetBidirectionalStream_jni.h " +
@@ -7907,15 +12640,15 @@
          "--output-name " +
          "CronetUrlRequestContext_jni.h " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetBidirectionalStream.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetBidirectionalStream.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetLibraryLoader.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetLibraryLoader.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUploadDataStream.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUploadDataStream.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java)",
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java)'",
     host_cross_supported: false,
     out: [
         "components/cronet/android/cronet_jni_headers.srcjar",
@@ -7924,6 +12657,7 @@
         "components/cronet/android/cronet_jni_headers/CronetUploadDataStream_jni.h",
         "components/cronet/android/cronet_jni_headers/CronetUrlRequestContext_jni.h",
         "components/cronet/android/cronet_jni_headers/CronetUrlRequest_jni.h",
+        "components/cronet/android/cronet_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -7963,15 +12697,17 @@
         "components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_jni_headers && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_jni_headers &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/components/cronet/android/cronet_jni_headers " +
+         "'$(genDir)/components/cronet/android/cronet_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_headers.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "CronetBidirectionalStream_jni.h " +
@@ -7984,15 +12720,15 @@
          "--output-name " +
          "CronetUrlRequestContext_jni.h " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetBidirectionalStream.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetBidirectionalStream.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetLibraryLoader.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetLibraryLoader.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUploadDataStream.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUploadDataStream.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java) " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java)",
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java)'",
     out: [
         "components/cronet/android/cronet_jni_headers.srcjar",
         "components/cronet/android/cronet_jni_headers/CronetBidirectionalStream_jni.h",
@@ -8000,6 +12736,7 @@
         "components/cronet/android/cronet_jni_headers/CronetUploadDataStream_jni.h",
         "components/cronet/android/cronet_jni_headers/CronetUrlRequestContext_jni.h",
         "components/cronet/android/cronet_jni_headers/CronetUrlRequest_jni.h",
+        "components/cronet/android/cronet_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -8025,17 +12762,33 @@
     ],
 }
 
+// GN: //components/cronet/android:cronet_jni_headers__action__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_jni_headers__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_jni_headers__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "cronet_jni_headers.srcjar",
+    ],
+}
+
 // GN: //components/cronet/android:cronet_jni_registration
 cc_genrule {
     name: "tot_cronet_components_cronet_android_cronet_jni_registration",
     srcs: [
+        "base/android/java/src/org/chromium/base/AndroidInfo.java",
         "base/android/java/src/org/chromium/base/ApkAssets.java",
+        "base/android/java/src/org/chromium/base/ApkInfo.java",
         "base/android/java/src/org/chromium/base/ApplicationStatus.java",
         "base/android/java/src/org/chromium/base/BaseFeatureMap.java",
         "base/android/java/src/org/chromium/base/BuildInfo.java",
         "base/android/java/src/org/chromium/base/BundleUtils.java",
+        "base/android/java/src/org/chromium/base/Callback.java",
         "base/android/java/src/org/chromium/base/CommandLine.java",
         "base/android/java/src/org/chromium/base/CpuFeatures.java",
+        "base/android/java/src/org/chromium/base/DeviceInfo.java",
         "base/android/java/src/org/chromium/base/EarlyTraceEvent.java",
         "base/android/java/src/org/chromium/base/EventLog.java",
         "base/android/java/src/org/chromium/base/FeatureList.java",
@@ -8050,6 +12803,9 @@
         "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
         "base/android/java/src/org/chromium/base/JavaHandlerThread.java",
         "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
         "base/android/java/src/org/chromium/base/LocaleUtils.java",
         "base/android/java/src/org/chromium/base/MemoryPressureListener.java",
         "base/android/java/src/org/chromium/base/PathService.java",
@@ -8096,20 +12852,22 @@
         "url/android/java/src/org/chromium/url/IDNStringUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android && current_dir=`basename \\`pwd\\``; " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android &&  " +
+         "current_dir=`basename \\`pwd\\``; " +
          "for f in $(in); " +
          "do " +
          "echo \"../$$current_dir/$$f\" >> $(genDir)/java.sources; " +
          "done; " +
-         "python3 $(location third_party/jni_zero/jni_zero.py) generate-final " +
+         "python3 $(location third_party/jni_zero/jni_zero.py) " +
+         "generate-final " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_registration.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_jni_registration.srcjar' " +
          "--java-sources-file " +
-         "$(genDir)/java.sources " +
+         "'$(genDir)/java.sources' " +
          "--include-test-only " +
          "--use-proxy-hash " +
          "--header-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_registration_generated.h " +
+         "'$(genDir)/components/cronet/android/cronet_jni_registration_generated.h' " +
          "--manual-jni-registration " +
          "--package-prefix " +
          "android.net.connectivity",
@@ -8149,13 +12907,17 @@
 java_genrule {
     name: "tot_cronet_components_cronet_android_cronet_jni_registration__java",
     srcs: [
+        "base/android/java/src/org/chromium/base/AndroidInfo.java",
         "base/android/java/src/org/chromium/base/ApkAssets.java",
+        "base/android/java/src/org/chromium/base/ApkInfo.java",
         "base/android/java/src/org/chromium/base/ApplicationStatus.java",
         "base/android/java/src/org/chromium/base/BaseFeatureMap.java",
         "base/android/java/src/org/chromium/base/BuildInfo.java",
         "base/android/java/src/org/chromium/base/BundleUtils.java",
+        "base/android/java/src/org/chromium/base/Callback.java",
         "base/android/java/src/org/chromium/base/CommandLine.java",
         "base/android/java/src/org/chromium/base/CpuFeatures.java",
+        "base/android/java/src/org/chromium/base/DeviceInfo.java",
         "base/android/java/src/org/chromium/base/EarlyTraceEvent.java",
         "base/android/java/src/org/chromium/base/EventLog.java",
         "base/android/java/src/org/chromium/base/FeatureList.java",
@@ -8170,6 +12932,9 @@
         "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
         "base/android/java/src/org/chromium/base/JavaHandlerThread.java",
         "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
         "base/android/java/src/org/chromium/base/LocaleUtils.java",
         "base/android/java/src/org/chromium/base/MemoryPressureListener.java",
         "base/android/java/src/org/chromium/base/PathService.java",
@@ -8216,20 +12981,22 @@
         "url/android/java/src/org/chromium/url/IDNStringUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android && current_dir=`basename \\`pwd\\``; " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android &&  " +
+         "current_dir=`basename \\`pwd\\``; " +
          "for f in $(in); " +
          "do " +
          "echo \"../$$current_dir/$$f\" >> $(genDir)/java.sources; " +
          "done; " +
-         "python3 $(location third_party/jni_zero/jni_zero.py) generate-final " +
+         "python3 $(location third_party/jni_zero/jni_zero.py) " +
+         "generate-final " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_registration.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_jni_registration.srcjar' " +
          "--java-sources-file " +
-         "$(genDir)/java.sources " +
+         "'$(genDir)/java.sources' " +
          "--include-test-only " +
          "--use-proxy-hash " +
          "--header-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_registration_generated.h " +
+         "'$(genDir)/components/cronet/android/cronet_jni_registration_generated.h' " +
          "--manual-jni-registration " +
          "--package-prefix " +
          "android.net.connectivity",
@@ -8264,13 +13031,17 @@
 cc_genrule {
     name: "tot_cronet_components_cronet_android_cronet_jni_registration__testing",
     srcs: [
+        "base/android/java/src/org/chromium/base/AndroidInfo.java",
         "base/android/java/src/org/chromium/base/ApkAssets.java",
+        "base/android/java/src/org/chromium/base/ApkInfo.java",
         "base/android/java/src/org/chromium/base/ApplicationStatus.java",
         "base/android/java/src/org/chromium/base/BaseFeatureMap.java",
         "base/android/java/src/org/chromium/base/BuildInfo.java",
         "base/android/java/src/org/chromium/base/BundleUtils.java",
+        "base/android/java/src/org/chromium/base/Callback.java",
         "base/android/java/src/org/chromium/base/CommandLine.java",
         "base/android/java/src/org/chromium/base/CpuFeatures.java",
+        "base/android/java/src/org/chromium/base/DeviceInfo.java",
         "base/android/java/src/org/chromium/base/EarlyTraceEvent.java",
         "base/android/java/src/org/chromium/base/EventLog.java",
         "base/android/java/src/org/chromium/base/FeatureList.java",
@@ -8285,6 +13056,9 @@
         "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
         "base/android/java/src/org/chromium/base/JavaHandlerThread.java",
         "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
         "base/android/java/src/org/chromium/base/LocaleUtils.java",
         "base/android/java/src/org/chromium/base/MemoryPressureListener.java",
         "base/android/java/src/org/chromium/base/PathService.java",
@@ -8331,20 +13105,22 @@
         "url/android/java/src/org/chromium/url/IDNStringUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android && current_dir=`basename \\`pwd\\``; " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android &&  " +
+         "current_dir=`basename \\`pwd\\``; " +
          "for f in $(in); " +
          "do " +
          "echo \"../$$current_dir/$$f\" >> $(genDir)/java.sources; " +
          "done; " +
-         "python3 $(location third_party/jni_zero/jni_zero.py) generate-final " +
+         "python3 $(location third_party/jni_zero/jni_zero.py) " +
+         "generate-final " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_registration.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_jni_registration.srcjar' " +
          "--java-sources-file " +
-         "$(genDir)/java.sources " +
+         "'$(genDir)/java.sources' " +
          "--include-test-only " +
          "--use-proxy-hash " +
          "--header-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_registration_generated.h " +
+         "'$(genDir)/components/cronet/android/cronet_jni_registration_generated.h' " +
          "--manual-jni-registration",
     host_cross_supported: false,
     out: [
@@ -8382,7 +13158,9 @@
 java_genrule {
     name: "tot_cronet_components_cronet_android_cronet_jni_registration__testing__java",
     srcs: [
+        "base/android/java/src/org/chromium/base/AndroidInfo.java",
         "base/android/java/src/org/chromium/base/ApkAssets.java",
+        "base/android/java/src/org/chromium/base/ApkInfo.java",
         "base/android/java/src/org/chromium/base/ApplicationStatus.java",
         "base/android/java/src/org/chromium/base/BaseFeatureMap.java",
         "base/android/java/src/org/chromium/base/BuildInfo.java",
@@ -8391,6 +13169,7 @@
         "base/android/java/src/org/chromium/base/CommandLine.java",
         "base/android/java/src/org/chromium/base/ContentUriUtils.java",
         "base/android/java/src/org/chromium/base/CpuFeatures.java",
+        "base/android/java/src/org/chromium/base/DeviceInfo.java",
         "base/android/java/src/org/chromium/base/EarlyTraceEvent.java",
         "base/android/java/src/org/chromium/base/EventLog.java",
         "base/android/java/src/org/chromium/base/FeatureList.java",
@@ -8405,6 +13184,9 @@
         "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
         "base/android/java/src/org/chromium/base/JavaHandlerThread.java",
         "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
         "base/android/java/src/org/chromium/base/LocaleUtils.java",
         "base/android/java/src/org/chromium/base/MemoryPressureListener.java",
         "base/android/java/src/org/chromium/base/PathService.java",
@@ -8477,20 +13259,22 @@
         "url/android/java/src/org/chromium/url/IDNStringUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android && current_dir=`basename \\`pwd\\``; " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android &&  " +
+         "current_dir=`basename \\`pwd\\``; " +
          "for f in $(in); " +
          "do " +
          "echo \"../$$current_dir/$$f\" >> $(genDir)/java.sources; " +
          "done; " +
-         "python3 $(location third_party/jni_zero/jni_zero.py) generate-final " +
+         "python3 $(location third_party/jni_zero/jni_zero.py) " +
+         "generate-final " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_registration.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_jni_registration.srcjar' " +
          "--java-sources-file " +
-         "$(genDir)/java.sources " +
+         "'$(genDir)/java.sources' " +
          "--include-test-only " +
          "--use-proxy-hash " +
          "--header-path " +
-         "$(genDir)/components/cronet/android/cronet_jni_registration_generated.h " +
+         "'$(genDir)/components/cronet/android/cronet_jni_registration_generated.h' " +
          "--manual-jni-registration",
     out: [
         "components/cronet/android/cronet_jni_registration.srcjar",
@@ -8519,6 +13303,166 @@
     ],
 }
 
+// GN: //components/cronet/android:cronet_shared_java__process_device
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_shared_java__process_device",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_shared_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_shared_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_shared_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_shared_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_shared_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_shared_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_stats_log_java__process_device
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_stats_log_java__process_device",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_stats_log_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_stats_log_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_stats_log_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_stats_log_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_stats_log_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_stats_log_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_test_apk_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_test_apk_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_test_apk_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_test_apk_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //components/cronet/android:cronet_test_apk_jni__action__testing
 cc_genrule {
     name: "tot_cronet_components_cronet_android_cronet_test_apk_jni__action__testing",
@@ -8531,15 +13475,17 @@
         "components/cronet/android/test/src/org/chromium/net/TestUploadDataStreamHandler.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_test_apk_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_test_apk_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/components/cronet/android/cronet_test_apk_jni " +
+         "'$(genDir)/components/cronet/android/cronet_test_apk_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_test_apk_jni.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_test_apk_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_test_apk_jni_placeholder.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_test_apk_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "CronetTestUtil_jni.h " +
@@ -8554,17 +13500,17 @@
          "--output-name " +
          "TestUploadDataStreamHandler_jni.h " +
          "--input-file " +
-         "$(location components/cronet/android/test/src/org/chromium/net/CronetTestUtil.java) " +
+         "'$(location components/cronet/android/test/src/org/chromium/net/CronetTestUtil.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/src/org/chromium/net/MockCertVerifier.java) " +
+         "'$(location components/cronet/android/test/src/org/chromium/net/MockCertVerifier.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/src/org/chromium/net/MockUrlRequestJobFactory.java) " +
+         "'$(location components/cronet/android/test/src/org/chromium/net/MockUrlRequestJobFactory.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/src/org/chromium/net/NativeTestServer.java) " +
+         "'$(location components/cronet/android/test/src/org/chromium/net/NativeTestServer.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/src/org/chromium/net/QuicTestServer.java) " +
+         "'$(location components/cronet/android/test/src/org/chromium/net/QuicTestServer.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/src/org/chromium/net/TestUploadDataStreamHandler.java)",
+         "'$(location components/cronet/android/test/src/org/chromium/net/TestUploadDataStreamHandler.java)'",
     host_cross_supported: false,
     out: [
         "components/cronet/android/cronet_test_apk_jni.srcjar",
@@ -8574,6 +13520,7 @@
         "components/cronet/android/cronet_test_apk_jni/NativeTestServer_jni.h",
         "components/cronet/android/cronet_test_apk_jni/QuicTestServer_jni.h",
         "components/cronet/android/cronet_test_apk_jni/TestUploadDataStreamHandler_jni.h",
+        "components/cronet/android/cronet_test_apk_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -8614,15 +13561,17 @@
         "components/cronet/android/test/src/org/chromium/net/TestUploadDataStreamHandler.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_test_apk_jni && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_test_apk_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/components/cronet/android/cronet_test_apk_jni " +
+         "'$(genDir)/components/cronet/android/cronet_test_apk_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_test_apk_jni.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_test_apk_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_test_apk_jni_placeholder.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_test_apk_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "CronetTestUtil_jni.h " +
@@ -8637,17 +13586,17 @@
          "--output-name " +
          "TestUploadDataStreamHandler_jni.h " +
          "--input-file " +
-         "$(location components/cronet/android/test/src/org/chromium/net/CronetTestUtil.java) " +
+         "'$(location components/cronet/android/test/src/org/chromium/net/CronetTestUtil.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/src/org/chromium/net/MockCertVerifier.java) " +
+         "'$(location components/cronet/android/test/src/org/chromium/net/MockCertVerifier.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/src/org/chromium/net/MockUrlRequestJobFactory.java) " +
+         "'$(location components/cronet/android/test/src/org/chromium/net/MockUrlRequestJobFactory.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/src/org/chromium/net/NativeTestServer.java) " +
+         "'$(location components/cronet/android/test/src/org/chromium/net/NativeTestServer.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/src/org/chromium/net/QuicTestServer.java) " +
+         "'$(location components/cronet/android/test/src/org/chromium/net/QuicTestServer.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/src/org/chromium/net/TestUploadDataStreamHandler.java)",
+         "'$(location components/cronet/android/test/src/org/chromium/net/TestUploadDataStreamHandler.java)'",
     out: [
         "components/cronet/android/cronet_test_apk_jni.srcjar",
         "components/cronet/android/cronet_test_apk_jni/CronetTestUtil_jni.h",
@@ -8656,6 +13605,7 @@
         "components/cronet/android/cronet_test_apk_jni/NativeTestServer_jni.h",
         "components/cronet/android/cronet_test_apk_jni/QuicTestServer_jni.h",
         "components/cronet/android/cronet_test_apk_jni/TestUploadDataStreamHandler_jni.h",
+        "components/cronet/android/cronet_test_apk_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -8681,6 +13631,18 @@
     ],
 }
 
+// GN: //components/cronet/android:cronet_test_apk_jni__action__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_test_apk_jni__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_test_apk_jni__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "cronet_test_apk_jni.srcjar",
+    ],
+}
+
 // GN: //components/cronet/android:cronet_tests_jni_headers__action__testing
 cc_genrule {
     name: "tot_cronet_components_cronet_android_cronet_tests_jni_headers__action__testing",
@@ -8690,15 +13652,17 @@
         "components/cronet/android/test/javatests/src/org/chromium/net/ExperimentalOptionsTest.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_tests_jni_headers && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_tests_jni_headers &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/components/cronet/android/cronet_tests_jni_headers " +
+         "'$(genDir)/components/cronet/android/cronet_tests_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_tests_jni_headers.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_tests_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_tests_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_tests_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "CronetUrlRequestContextTest_jni.h " +
@@ -8707,17 +13671,18 @@
          "--output-name " +
          "ExperimentalOptionsTest_jni.h " +
          "--input-file " +
-         "$(location components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestContextTest.java) " +
+         "'$(location components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestContextTest.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestTest.java) " +
+         "'$(location components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestTest.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/javatests/src/org/chromium/net/ExperimentalOptionsTest.java)",
+         "'$(location components/cronet/android/test/javatests/src/org/chromium/net/ExperimentalOptionsTest.java)'",
     host_cross_supported: false,
     out: [
         "components/cronet/android/cronet_tests_jni_headers.srcjar",
         "components/cronet/android/cronet_tests_jni_headers/CronetUrlRequestContextTest_jni.h",
         "components/cronet/android/cronet_tests_jni_headers/CronetUrlRequestTest_jni.h",
         "components/cronet/android/cronet_tests_jni_headers/ExperimentalOptionsTest_jni.h",
+        "components/cronet/android/cronet_tests_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -8755,15 +13720,17 @@
         "components/cronet/android/test/javatests/src/org/chromium/net/ExperimentalOptionsTest.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_tests_jni_headers && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android/cronet_tests_jni_headers &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/components/cronet/android/cronet_tests_jni_headers " +
+         "'$(genDir)/components/cronet/android/cronet_tests_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_tests_jni_headers.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_tests_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_tests_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_tests_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "CronetUrlRequestContextTest_jni.h " +
@@ -8772,16 +13739,17 @@
          "--output-name " +
          "ExperimentalOptionsTest_jni.h " +
          "--input-file " +
-         "$(location components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestContextTest.java) " +
+         "'$(location components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestContextTest.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestTest.java) " +
+         "'$(location components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestTest.java)' " +
          "--input-file " +
-         "$(location components/cronet/android/test/javatests/src/org/chromium/net/ExperimentalOptionsTest.java)",
+         "'$(location components/cronet/android/test/javatests/src/org/chromium/net/ExperimentalOptionsTest.java)'",
     out: [
         "components/cronet/android/cronet_tests_jni_headers.srcjar",
         "components/cronet/android/cronet_tests_jni_headers/CronetUrlRequestContextTest_jni.h",
         "components/cronet/android/cronet_tests_jni_headers/CronetUrlRequestTest_jni.h",
         "components/cronet/android/cronet_tests_jni_headers/ExperimentalOptionsTest_jni.h",
+        "components/cronet/android/cronet_tests_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -8807,11 +13775,25 @@
     ],
 }
 
+// GN: //components/cronet/android:cronet_tests_jni_headers__action__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_tests_jni_headers__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_tests_jni_headers__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "cronet_tests_jni_headers.srcjar",
+    ],
+}
+
 // GN: //components/cronet/android:cronet_tests_jni_registration__testing
 java_genrule {
     name: "tot_cronet_components_cronet_android_cronet_tests_jni_registration__testing__java",
     srcs: [
+        "base/android/java/src/org/chromium/base/AndroidInfo.java",
         "base/android/java/src/org/chromium/base/ApkAssets.java",
+        "base/android/java/src/org/chromium/base/ApkInfo.java",
         "base/android/java/src/org/chromium/base/ApplicationStatus.java",
         "base/android/java/src/org/chromium/base/BaseFeatureMap.java",
         "base/android/java/src/org/chromium/base/BuildInfo.java",
@@ -8820,6 +13802,7 @@
         "base/android/java/src/org/chromium/base/CommandLine.java",
         "base/android/java/src/org/chromium/base/ContentUriUtils.java",
         "base/android/java/src/org/chromium/base/CpuFeatures.java",
+        "base/android/java/src/org/chromium/base/DeviceInfo.java",
         "base/android/java/src/org/chromium/base/EarlyTraceEvent.java",
         "base/android/java/src/org/chromium/base/EventLog.java",
         "base/android/java/src/org/chromium/base/FeatureList.java",
@@ -8834,6 +13817,9 @@
         "base/android/java/src/org/chromium/base/JavaExceptionReporter.java",
         "base/android/java/src/org/chromium/base/JavaHandlerThread.java",
         "base/android/java/src/org/chromium/base/JniAndroid.java",
+        "base/android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "base/android/java/src/org/chromium/base/JniOnceCallback.java",
+        "base/android/java/src/org/chromium/base/JniRepeatingCallback.java",
         "base/android/java/src/org/chromium/base/LocaleUtils.java",
         "base/android/java/src/org/chromium/base/MemoryPressureListener.java",
         "base/android/java/src/org/chromium/base/PathService.java",
@@ -8906,20 +13892,22 @@
         "url/android/java/src/org/chromium/url/IDNStringUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/cronet/android && current_dir=`basename \\`pwd\\``; " +
+         "mkdir -p $(genDir)/jni_headers/components/cronet/android &&  " +
+         "current_dir=`basename \\`pwd\\``; " +
          "for f in $(in); " +
          "do " +
          "echo \"../$$current_dir/$$f\" >> $(genDir)/java.sources; " +
          "done; " +
-         "python3 $(location third_party/jni_zero/jni_zero.py) generate-final " +
+         "python3 $(location third_party/jni_zero/jni_zero.py) " +
+         "generate-final " +
          "--srcjar-path " +
-         "$(genDir)/components/cronet/android/cronet_tests_jni_registration.srcjar " +
+         "'$(genDir)/components/cronet/android/cronet_tests_jni_registration.srcjar' " +
          "--java-sources-file " +
-         "$(genDir)/java.sources " +
+         "'$(genDir)/java.sources' " +
          "--include-test-only " +
          "--use-proxy-hash " +
          "--header-path " +
-         "$(genDir)/components/cronet/android/cronet_tests_jni_registration_generated.h " +
+         "'$(genDir)/components/cronet/android/cronet_tests_jni_registration_generated.h' " +
          "--manual-jni-registration " +
          "--module-name " +
          "cronet_tests",
@@ -8968,6 +13956,7 @@
         "libbase_stest_ctest_urust_ulogger_uconsumer__c71463e67618dfbc",
         "libchromium__c6c34dd5a98579f2",
         "libcxx__2cd805ef869e78fa",
+        "libfoldhash__3d2886e384b4e895",
         "libitoa__5f66f1469987af64",
         "liblog__7d83bd71ca2985fc",
         "libmemchr__def56687591c1a6a",
@@ -9061,6 +14050,7 @@
         "tot_cronet_third_party_abseil_cpp_absl_debugging_demangle_rust__testing",
         "tot_cronet_third_party_abseil_cpp_absl_debugging_examine_stack__testing",
         "tot_cronet_third_party_abseil_cpp_absl_debugging_failure_signal_handler__testing",
+        "tot_cronet_third_party_abseil_cpp_absl_debugging_leak_check__testing",
         "tot_cronet_third_party_abseil_cpp_absl_debugging_stacktrace__testing",
         "tot_cronet_third_party_abseil_cpp_absl_debugging_symbolize__testing",
         "tot_cronet_third_party_abseil_cpp_absl_debugging_utf8_for_code_point__testing",
@@ -9091,16 +14081,16 @@
         "tot_cronet_third_party_abseil_cpp_absl_log_internal_log_sink_set__testing",
         "tot_cronet_third_party_abseil_cpp_absl_log_internal_nullguard__testing",
         "tot_cronet_third_party_abseil_cpp_absl_log_internal_proto__testing",
+        "tot_cronet_third_party_abseil_cpp_absl_log_internal_structured_proto__testing",
         "tot_cronet_third_party_abseil_cpp_absl_log_internal_vlog_config__testing",
-        "tot_cronet_third_party_abseil_cpp_absl_log_log_entry__testing",
         "tot_cronet_third_party_abseil_cpp_absl_log_log_sink__testing",
         "tot_cronet_third_party_abseil_cpp_absl_numeric_int128__testing",
         "tot_cronet_third_party_abseil_cpp_absl_profiling_exponential_biased__testing",
         "tot_cronet_third_party_abseil_cpp_absl_random_bit_gen_ref__testing",
         "tot_cronet_third_party_abseil_cpp_absl_random_distributions__testing",
+        "tot_cronet_third_party_abseil_cpp_absl_random_internal_entropy_pool__testing",
         "tot_cronet_third_party_abseil_cpp_absl_random_internal_nonsecure_base__testing",
         "tot_cronet_third_party_abseil_cpp_absl_random_internal_platform__testing",
-        "tot_cronet_third_party_abseil_cpp_absl_random_internal_pool_urbg__testing",
         "tot_cronet_third_party_abseil_cpp_absl_random_internal_randen__testing",
         "tot_cronet_third_party_abseil_cpp_absl_random_internal_randen_engine__testing",
         "tot_cronet_third_party_abseil_cpp_absl_random_internal_randen_hwaes__testing",
@@ -9127,8 +14117,6 @@
         "tot_cronet_third_party_abseil_cpp_absl_time_internal_cctz_civil_time__testing",
         "tot_cronet_third_party_abseil_cpp_absl_time_internal_cctz_time_zone__testing",
         "tot_cronet_third_party_abseil_cpp_absl_time_time__testing",
-        "tot_cronet_third_party_abseil_cpp_absl_types_bad_optional_access__testing",
-        "tot_cronet_third_party_abseil_cpp_absl_types_bad_variant_access__testing",
         "tot_cronet_third_party_ashmem_ashmem__testing",
         "tot_cronet_third_party_boringssl_boringssl__testing",
         "tot_cronet_third_party_boringssl_boringssl_asm__testing",
@@ -9150,9 +14138,11 @@
         "tot_cronet_third_party_modp_b64_modp_b64__testing",
         "tot_cronet_third_party_protobuf_protobuf_full__testing",
         "tot_cronet_third_party_protobuf_protobuf_lite__testing",
+        "tot_cronet_third_party_protobuf_utf8_range__testing",
         "tot_cronet_third_party_quic_trace_quic_trace_proto__testing",
         "tot_cronet_third_party_re2_re2__testing",
         "tot_cronet_third_party_rust_serde_json_lenient_v0_2_wrapper_wrapper_cxx_generated__testing",
+        "tot_cronet_third_party_simdutf_simdutf__testing",
         "tot_cronet_url_url__testing",
     ],
     defaults: [
@@ -9162,13 +14152,11 @@
         "-DANDROID",
         "-DANDROID_NDK_VERSION_ROLL=r27_1",
         "-DBENCHMARK_STATIC_DEFINE",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.130/include/cxx.h\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.146/include/cxx.h\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
-        "-DGOOGLE_PROTOBUF_INTERNAL_DONATE_STEAL_INLINE=0",
         "-DGOOGLE_PROTOBUF_NO_RTTI",
-        "-DGOOGLE_PROTOBUF_NO_STATIC_INITIALIZER",
         "-DGTEST_API_=",
         "-DGTEST_HAS_ABSL",
         "-DGTEST_HAS_POSIX_RE=0",
@@ -9268,12 +14256,78 @@
     },
 }
 
+// GN: //components/cronet/android:cronet_urlconnection_impl_java__process_device
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_urlconnection_impl_java__process_device",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_urlconnection_impl_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_urlconnection_impl_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:cronet_urlconnection_impl_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_cronet_urlconnection_impl_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_cronet_urlconnection_impl_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/cronet_urlconnection_impl_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //components/cronet/android:effective_connection_type_java
 java_genrule {
     name: "tot_cronet_components_cronet_android_effective_connection_type_java",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/nqe/effective_connection_type.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/nqe/effective_connection_type.h)'",
     out: [
         "components/cronet/android/effective_connection_type_java.srcjar",
     ],
@@ -9295,9 +14349,11 @@
 // GN: //components/cronet/android:effective_connection_type_java__testing
 java_genrule {
     name: "tot_cronet_components_cronet_android_effective_connection_type_java__testing",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/nqe/effective_connection_type.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/nqe/effective_connection_type.h)'",
     out: [
         "components/cronet/android/effective_connection_type_java.srcjar",
     ],
@@ -9316,6 +14372,70 @@
     ],
 }
 
+// GN: //components/cronet/android:flags_java_proto__process_device
+java_genrule {
+    name: "tot_cronet_components_cronet_android_flags_java_proto__process_device",
+    srcs: [
+        ":tot_cronet_components_cronet_android_flags_java_proto__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/flags_java_proto.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:flags_java_proto__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_flags_java_proto__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_flags_java_proto__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/flags_java_proto.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //components/cronet/android:flags_java_proto__protoc_java
 java_genrule {
     name: "tot_cronet_components_cronet_android_flags_java_proto__protoc_java",
@@ -9325,13 +14445,15 @@
     tools: [
         "tot_cronet_third_party_protobuf_protoc",
     ],
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/protoc_java.py) --protoc " +
-         "$(location tot_cronet_third_party_protobuf_protoc) " +
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/protoc_java.py) " +
+         "--protoc " +
+         "'$(location tot_cronet_third_party_protobuf_protoc)' " +
          "--proto-path " +
          "external/cronet/tot/components/cronet/android " +
          "--srcjar " +
-         "$(out) " +
-         "$(location components/cronet/android/proto/flags.proto)",
+         "'$(out)' " +
+         "'$(location components/cronet/android/proto/flags.proto)'",
     out: [
         "components/cronet/android/flags_java_proto__protoc_java.srcjar",
     ],
@@ -9357,13 +14479,15 @@
     tools: [
         "tot_cronet_third_party_protobuf_protoc",
     ],
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/protoc_java.py) --protoc " +
-         "$(location tot_cronet_third_party_protobuf_protoc) " +
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/protoc_java.py) " +
+         "--protoc " +
+         "'$(location tot_cronet_third_party_protobuf_protoc)' " +
          "--proto-path " +
          "external/cronet/tot/components/cronet/android " +
          "--srcjar " +
-         "$(out) " +
-         "$(location components/cronet/android/proto/flags.proto)",
+         "'$(out)' " +
+         "'$(location components/cronet/android/proto/flags.proto)'",
     out: [
         "components/cronet/android/flags_java_proto__protoc_java.srcjar",
     ],
@@ -9383,9 +14507,11 @@
 // GN: //components/cronet/android:http_cache_type_java
 java_genrule {
     name: "tot_cronet_components_cronet_android_http_cache_type_java",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location components/cronet/url_request_context_config.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location components/cronet/url_request_context_config.h)'",
     out: [
         "components/cronet/android/http_cache_type_java.srcjar",
     ],
@@ -9407,9 +14533,11 @@
 // GN: //components/cronet/android:http_cache_type_java__testing
 java_genrule {
     name: "tot_cronet_components_cronet_android_http_cache_type_java__testing",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location components/cronet/url_request_context_config.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location components/cronet/url_request_context_config.h)'",
     out: [
         "components/cronet/android/http_cache_type_java.srcjar",
     ],
@@ -9428,19 +14556,53 @@
     ],
 }
 
+// GN: //components/cronet/android:httpengine_native_provider_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_httpengine_native_provider_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_httpengine_native_provider_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/httpengine_native_provider_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //components/cronet/android:impl_version
 java_genrule {
     name: "tot_cronet_components_cronet_android_impl_version",
-    cmd: "mkdir -p $(genDir)/components/cronet/android/templates/org/chromium/net/impl && $(location build/util/version.py) --official " +
+    cmd: "mkdir -p $(genDir)/components/cronet/android/templates/org/chromium/net/impl &&  " +
+         "$(location build/util/version.py) " +
+         "--official " +
          "-f " +
-         "$(location chrome/VERSION) " +
+         "'$(location chrome/VERSION)' " +
          "-f " +
-         "$(location build/util/LASTCHANGE) " +
+         "'$(location build/util/LASTCHANGE)' " +
          "-e " +
-         "'API_LEVEL=34' " +
+         "API_LEVEL=34 " +
          "-o " +
-         "$(out) " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/ImplVersion.template)",
+         "'$(out)' " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/ImplVersion.template)'",
     out: [
         "components/cronet/android/templates/org/chromium/net/impl/ImplVersion.java",
     ],
@@ -9459,16 +14621,18 @@
 // GN: //components/cronet/android:impl_version__testing
 java_genrule {
     name: "tot_cronet_components_cronet_android_impl_version__testing",
-    cmd: "mkdir -p $(genDir)/components/cronet/android/templates/org/chromium/net/impl && $(location build/util/version.py) --official " +
+    cmd: "mkdir -p $(genDir)/components/cronet/android/templates/org/chromium/net/impl &&  " +
+         "$(location build/util/version.py) " +
+         "--official " +
          "-f " +
-         "$(location chrome/VERSION) " +
+         "'$(location chrome/VERSION)' " +
          "-f " +
-         "$(location build/util/LASTCHANGE) " +
+         "'$(location build/util/LASTCHANGE)' " +
          "-e " +
-         "'API_LEVEL=34' " +
+         "API_LEVEL=34 " +
          "-o " +
-         "$(out) " +
-         "$(location components/cronet/android/java/src/org/chromium/net/impl/ImplVersion.template)",
+         "'$(out)' " +
+         "'$(location components/cronet/android/java/src/org/chromium/net/impl/ImplVersion.template)'",
     out: [
         "components/cronet/android/templates/org/chromium/net/impl/ImplVersion.java",
     ],
@@ -9581,9 +14745,11 @@
 // GN: //components/cronet/android:net_idempotency_java
 java_genrule {
     name: "tot_cronet_components_cronet_android_net_idempotency_java",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/base/idempotency.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/base/idempotency.h)'",
     out: [
         "components/cronet/android/net_idempotency_java.srcjar",
     ],
@@ -9605,9 +14771,11 @@
 // GN: //components/cronet/android:net_idempotency_java__testing
 java_genrule {
     name: "tot_cronet_components_cronet_android_net_idempotency_java__testing",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/base/idempotency.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/base/idempotency.h)'",
     out: [
         "components/cronet/android/net_idempotency_java.srcjar",
     ],
@@ -9629,9 +14797,11 @@
 // GN: //components/cronet/android:net_request_priority_java
 java_genrule {
     name: "tot_cronet_components_cronet_android_net_request_priority_java",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/base/request_priority.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/base/request_priority.h)'",
     out: [
         "components/cronet/android/net_request_priority_java.srcjar",
     ],
@@ -9653,9 +14823,11 @@
 // GN: //components/cronet/android:net_request_priority_java__testing
 java_genrule {
     name: "tot_cronet_components_cronet_android_net_request_priority_java__testing",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/base/request_priority.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/base/request_priority.h)'",
     out: [
         "components/cronet/android/net_request_priority_java.srcjar",
     ],
@@ -9677,9 +14849,11 @@
 // GN: //components/cronet/android:network_quality_observation_source_java
 java_genrule {
     name: "tot_cronet_components_cronet_android_network_quality_observation_source_java",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/nqe/network_quality_observation_source.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/nqe/network_quality_observation_source.h)'",
     out: [
         "components/cronet/android/network_quality_observation_source_java.srcjar",
     ],
@@ -9701,9 +14875,11 @@
 // GN: //components/cronet/android:network_quality_observation_source_java__testing
 java_genrule {
     name: "tot_cronet_components_cronet_android_network_quality_observation_source_java__testing",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/nqe/network_quality_observation_source.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/nqe/network_quality_observation_source.h)'",
     out: [
         "components/cronet/android/network_quality_observation_source_java.srcjar",
     ],
@@ -9722,6 +14898,70 @@
     ],
 }
 
+// GN: //components/cronet/android:request_context_config_java_proto__process_device
+java_genrule {
+    name: "tot_cronet_components_cronet_android_request_context_config_java_proto__process_device",
+    srcs: [
+        ":tot_cronet_components_cronet_android_request_context_config_java_proto__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/request_context_config_java_proto.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:request_context_config_java_proto__process_device__testing
+java_genrule {
+    name: "tot_cronet_components_cronet_android_request_context_config_java_proto__process_device__testing",
+    srcs: [
+        ":tot_cronet_components_cronet_android_request_context_config_java_proto__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "components/cronet/android/request_context_config_java_proto.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //components/cronet/android:request_context_config_java_proto__protoc_java
 java_genrule {
     name: "tot_cronet_components_cronet_android_request_context_config_java_proto__protoc_java",
@@ -9731,13 +14971,15 @@
     tools: [
         "tot_cronet_third_party_protobuf_protoc",
     ],
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/protoc_java.py) --protoc " +
-         "$(location tot_cronet_third_party_protobuf_protoc) " +
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/protoc_java.py) " +
+         "--protoc " +
+         "'$(location tot_cronet_third_party_protobuf_protoc)' " +
          "--proto-path " +
          "external/cronet/tot/components/cronet/android " +
          "--srcjar " +
-         "$(out) " +
-         "$(location components/cronet/android/proto/request_context_config.proto)",
+         "'$(out)' " +
+         "'$(location components/cronet/android/proto/request_context_config.proto)'",
     out: [
         "components/cronet/android/request_context_config_java_proto__protoc_java.srcjar",
     ],
@@ -9763,13 +15005,15 @@
     tools: [
         "tot_cronet_third_party_protobuf_protoc",
     ],
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/protoc_java.py) --protoc " +
-         "$(location tot_cronet_third_party_protobuf_protoc) " +
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/protoc_java.py) " +
+         "--protoc " +
+         "'$(location tot_cronet_third_party_protobuf_protoc)' " +
          "--proto-path " +
          "external/cronet/tot/components/cronet/android " +
          "--srcjar " +
-         "$(out) " +
-         "$(location components/cronet/android/proto/request_context_config.proto)",
+         "'$(out)' " +
+         "'$(location components/cronet/android/proto/request_context_config.proto)'",
     out: [
         "components/cronet/android/request_context_config_java_proto__protoc_java.srcjar",
     ],
@@ -9786,12 +15030,120 @@
     ],
 }
 
+// GN: //components/cronet/android:request_context_config_proto_gen
+cc_genrule {
+    name: "tot_cronet_components_cronet_android_request_context_config_proto_gen",
+    srcs: [
+        "components/cronet/android/proto/request_context_config.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/components/cronet/android/proto " +
+         "--cpp_out=lite=true:$(genDir)/components/cronet/android/proto/ " +
+         "external/cronet/tot/components/cronet/android/proto/request_context_config.proto",
+    host_cross_supported: false,
+    out: [
+        "components/cronet/android/proto/request_context_config.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:request_context_config_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_components_cronet_android_request_context_config_proto_gen__testing",
+    srcs: [
+        "components/cronet/android/proto/request_context_config.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/components/cronet/android/proto " +
+         "--cpp_out=lite=true:$(genDir)/components/cronet/android/proto/ " +
+         "external/cronet/tot/components/cronet/android/proto/request_context_config.proto",
+    host_cross_supported: false,
+    out: [
+        "components/cronet/android/proto/request_context_config.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //components/cronet/android:request_context_config_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_components_cronet_android_request_context_config_proto_gen__testing_headers",
+    srcs: [
+        "components/cronet/android/proto/request_context_config.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/components/cronet/android/proto " +
+         "--cpp_out=lite=true:$(genDir)/components/cronet/android/proto/ " +
+         "external/cronet/tot/components/cronet/android/proto/request_context_config.proto",
+    out: [
+        "components/cronet/android/proto/request_context_config.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "components/cronet/android/proto",
+        "protos",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
+// GN: //components/cronet/android:request_context_config_proto_gen
+cc_genrule {
+    name: "tot_cronet_components_cronet_android_request_context_config_proto_gen_headers",
+    srcs: [
+        "components/cronet/android/proto/request_context_config.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/components/cronet/android/proto " +
+         "--cpp_out=lite=true:$(genDir)/components/cronet/android/proto/ " +
+         "external/cronet/tot/components/cronet/android/proto/request_context_config.proto",
+    out: [
+        "components/cronet/android/proto/request_context_config.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "components/cronet/android/proto",
+        "protos",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
 // GN: //components/cronet/android:rtt_throughput_values_java
 java_genrule {
     name: "tot_cronet_components_cronet_android_rtt_throughput_values_java",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/nqe/network_quality.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/nqe/network_quality.h)'",
     out: [
         "components/cronet/android/rtt_throughput_values_java.srcjar",
     ],
@@ -9813,9 +15165,11 @@
 // GN: //components/cronet/android:rtt_throughput_values_java__testing
 java_genrule {
     name: "tot_cronet_components_cronet_android_rtt_throughput_values_java__testing",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/nqe/network_quality.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/nqe/network_quality.h)'",
     out: [
         "components/cronet/android/rtt_throughput_values_java.srcjar",
     ],
@@ -9837,9 +15191,11 @@
 // GN: //components/cronet/android:url_request_close_source_java
 java_genrule {
     name: "tot_cronet_components_cronet_android_url_request_close_source_java",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location components/cronet/android/url_request_close_source.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location components/cronet/android/url_request_close_source.h)'",
     out: [
         "components/cronet/android/url_request_close_source_java.srcjar",
     ],
@@ -9861,9 +15217,11 @@
 // GN: //components/cronet/android:url_request_close_source_java__testing
 java_genrule {
     name: "tot_cronet_components_cronet_android_url_request_close_source_java__testing",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location components/cronet/android/url_request_close_source.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location components/cronet/android/url_request_close_source.h)'",
     out: [
         "components/cronet/android/url_request_close_source_java.srcjar",
     ],
@@ -9885,9 +15243,11 @@
 // GN: //components/cronet/android:url_request_error_java
 java_genrule {
     name: "tot_cronet_components_cronet_android_url_request_error_java",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location components/cronet/android/url_request_error.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location components/cronet/android/url_request_error.h)'",
     out: [
         "components/cronet/android/url_request_error_java.srcjar",
     ],
@@ -9909,9 +15269,11 @@
 // GN: //components/cronet/android:url_request_error_java__testing
 java_genrule {
     name: "tot_cronet_components_cronet_android_url_request_error_java__testing",
-    cmd: "mkdir -p $(genDir)/components/cronet/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location components/cronet/android/url_request_error.h)",
+    cmd: "mkdir -p $(genDir)/components/cronet/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location components/cronet/android/url_request_error.h)'",
     out: [
         "components/cronet/android/url_request_error_java.srcjar",
     ],
@@ -9933,9 +15295,11 @@
 // GN: //components/cronet:cronet_buildflags
 cc_genrule {
     name: "tot_cronet_components_cronet_cronet_buildflags",
-    cmd: "mkdir -p $(genDir)/components/cronet && echo '--flags DISABLE_HISTOGRAM_SUPPORT=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/components/cronet &&  " +
+         "echo '--flags DISABLE_HISTOGRAM_SUPPORT=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//components/cronet:cronet_buildflags " +
          "--gen-dir " +
@@ -9960,9 +15324,11 @@
 // GN: //components/cronet:cronet_buildflags__testing
 cc_genrule {
     name: "tot_cronet_components_cronet_cronet_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/components/cronet && echo '--flags DISABLE_HISTOGRAM_SUPPORT=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/components/cronet &&  " +
+         "echo '--flags DISABLE_HISTOGRAM_SUPPORT=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//components/cronet:cronet_buildflags " +
          "--gen-dir " +
@@ -9987,14 +15353,16 @@
 // GN: //components/cronet:cronet_version_header_action
 cc_genrule {
     name: "tot_cronet_components_cronet_cronet_version_header_action",
-    cmd: "mkdir -p $(genDir)/components/cronet && $(location build/util/version.py) --official " +
+    cmd: "mkdir -p $(genDir)/components/cronet &&  " +
+         "$(location build/util/version.py) " +
+         "--official " +
          "-f " +
-         "$(location chrome/VERSION) " +
+         "'$(location chrome/VERSION)' " +
          "-e " +
          "'VERSION_FULL=\"%s.%s.%s.%s\" % (MAJOR,MINOR,BUILD,PATCH)' " +
          "-o " +
-         "$(out) " +
-         "$(location components/cronet/version.h.in)",
+         "'$(out)' " +
+         "'$(location components/cronet/version.h.in)'",
     host_cross_supported: false,
     out: [
         "components/cronet/version.h",
@@ -10017,14 +15385,16 @@
 // GN: //components/cronet:cronet_version_header_action__testing
 cc_genrule {
     name: "tot_cronet_components_cronet_cronet_version_header_action__testing",
-    cmd: "mkdir -p $(genDir)/components/cronet && $(location build/util/version.py) --official " +
+    cmd: "mkdir -p $(genDir)/components/cronet &&  " +
+         "$(location build/util/version.py) " +
+         "--official " +
          "-f " +
-         "$(location chrome/VERSION) " +
+         "'$(location chrome/VERSION)' " +
          "-e " +
          "'VERSION_FULL=\"%s.%s.%s.%s\" % (MAJOR,MINOR,BUILD,PATCH)' " +
          "-o " +
-         "$(out) " +
-         "$(location components/cronet/version.h.in)",
+         "'$(out)' " +
+         "'$(location components/cronet/version.h.in)'",
     host_cross_supported: false,
     out: [
         "components/cronet/version.h",
@@ -10052,24 +15422,26 @@
         "components/prefs/android/java/src/org/chromium/components/prefs/PrefService.java",
     ],
     cmd: "mkdir -p $(genDir)/components/prefs/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/prefs/android/jni_headers && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/components/prefs/android/jni_headers &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/components/prefs/android/jni_headers " +
+         "'$(genDir)/components/prefs/android/jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/components/prefs/android/jni_headers.srcjar " +
+         "'$(genDir)/components/prefs/android/jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/components/prefs/android/jni_headers_placeholder.srcjar " +
+         "'$(genDir)/components/prefs/android/jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "PrefChangeRegistrar_jni.h " +
          "--output-name " +
          "PrefService_jni.h " +
          "--input-file " +
-         "$(location components/prefs/android/java/src/org/chromium/components/prefs/PrefChangeRegistrar.java) " +
+         "'$(location components/prefs/android/java/src/org/chromium/components/prefs/PrefChangeRegistrar.java)' " +
          "--input-file " +
-         "$(location components/prefs/android/java/src/org/chromium/components/prefs/PrefService.java) " +
+         "'$(location components/prefs/android/java/src/org/chromium/components/prefs/PrefService.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
@@ -10077,6 +15449,7 @@
         "components/prefs/android/jni_headers.srcjar",
         "components/prefs/android/jni_headers/PrefChangeRegistrar_jni.h",
         "components/prefs/android/jni_headers/PrefService_jni.h",
+        "components/prefs/android/jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -10113,29 +15486,32 @@
         "components/prefs/android/java/src/org/chromium/components/prefs/PrefService.java",
     ],
     cmd: "mkdir -p $(genDir)/components/prefs/android &&  " +
-         "mkdir -p $(genDir)/jni_headers/components/prefs/android/jni_headers && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/jni_headers/components/prefs/android/jni_headers &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/components/prefs/android/jni_headers " +
+         "'$(genDir)/components/prefs/android/jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/components/prefs/android/jni_headers.srcjar " +
+         "'$(genDir)/components/prefs/android/jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/components/prefs/android/jni_headers_placeholder.srcjar " +
+         "'$(genDir)/components/prefs/android/jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "PrefChangeRegistrar_jni.h " +
          "--output-name " +
          "PrefService_jni.h " +
          "--input-file " +
-         "$(location components/prefs/android/java/src/org/chromium/components/prefs/PrefChangeRegistrar.java) " +
+         "'$(location components/prefs/android/java/src/org/chromium/components/prefs/PrefChangeRegistrar.java)' " +
          "--input-file " +
-         "$(location components/prefs/android/java/src/org/chromium/components/prefs/PrefService.java)",
+         "'$(location components/prefs/android/java/src/org/chromium/components/prefs/PrefService.java)'",
     host_cross_supported: false,
     out: [
         "components/prefs/android/jni_headers.srcjar",
         "components/prefs/android/jni_headers/PrefChangeRegistrar_jni.h",
         "components/prefs/android/jni_headers/PrefService_jni.h",
+        "components/prefs/android/jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -10167,9 +15543,11 @@
 // GN: //crypto:buildflags
 cc_genrule {
     name: "tot_cronet_crypto_buildflags",
-    cmd: "mkdir -p $(genDir)/crypto && echo '--flags USE_NSS_CERTS=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/crypto &&  " +
+         "echo '--flags USE_NSS_CERTS=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//crypto:buildflags " +
          "--gen-dir " +
@@ -10194,9 +15572,11 @@
 // GN: //crypto:buildflags__testing
 cc_genrule {
     name: "tot_cronet_crypto_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/crypto && echo '--flags USE_NSS_CERTS=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/crypto &&  " +
+         "echo '--flags USE_NSS_CERTS=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//crypto:buildflags " +
          "--gen-dir " +
@@ -10219,30 +15599,101 @@
     ],
 }
 
-// GN: //net/android:dummy_spnego_authenticator_java__testing
+// GN: //net/android:dummy_spnego_authenticator_java__compile_java__testing
 java_library {
-    name: "tot_cronet_net_android_dummy_spnego_authenticator_java__testing",
+    name: "tot_cronet_net_android_dummy_spnego_authenticator_java__compile_java__testing",
     srcs: [
-        ":tot_cronet_net_android_dummy_spnego_authenticator_jni__action__testing__java",
+        ":tot_cronet_net_android_dummy_spnego_authenticator_jni__action__testing__java_proxy_only",
         "net/test/android/javatests/src/org/chromium/net/test/DummySpnegoAuthenticator.java",
         "net/test/android/javatests/src/org/chromium/net/test/DummySpnegoAuthenticatorService.java",
     ],
-    static_libs: [
-        "tot_cronet_base_base_java__testing",
-        "tot_cronet_base_base_java_url_utils_for_test__testing",
-        "tot_cronet_net_android_net_java__testing",
-        "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
-    ],
     apex_available: [
         "com.android.tethering",
     ],
     min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_android_info_java__compile_java__testing",
+        "tot_cronet_base_android_runtime_jni_headers_java__testing",
+        "tot_cronet_base_base_java__compile_java__testing",
+        "tot_cronet_base_base_java_url_utils_for_test__compile_java__testing",
+        "tot_cronet_base_base_jni_java__compile_java__testing",
+        "tot_cronet_base_base_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_build_info_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_flagged_apis_java__compile_java__testing",
+        "tot_cronet_base_jank_tracker_java__compile_java__testing",
+        "tot_cronet_base_library_loader_java__compile_java__testing",
+        "tot_cronet_base_library_loader_jni_java__compile_java__testing",
+        "tot_cronet_base_lifetime_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_memory_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_promise_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_service_loader_java__compile_java__testing",
+        "tot_cronet_base_stream_util_java__compile_java__testing",
+        "tot_cronet_base_supplier_java__compile_java__testing",
+        "tot_cronet_base_sys_utils_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_base_unowned_user_data_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_channel_enum_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_version_constants_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_net_android_net_java__compile_java__testing",
+        "tot_cronet_net_android_net_thread_stats_uid_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
     sdk_version: "current",
     visibility: [
         "//external/cronet:__subpackages__",
-        "//packages/modules/Connectivity:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //net/android:dummy_spnego_authenticator_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_net_android_dummy_spnego_authenticator_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_net_android_dummy_spnego_authenticator_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/net/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "net/android/dummy_spnego_authenticator_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //net/android:dummy_spnego_authenticator_jni__action__testing
@@ -10252,24 +15703,27 @@
         "net/test/android/javatests/src/org/chromium/net/test/DummySpnegoAuthenticator.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/net/android/dummy_spnego_authenticator_jni &&  " +
-         "mkdir -p $(genDir)/net/android && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/net/android &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/net/android/dummy_spnego_authenticator_jni " +
+         "'$(genDir)/net/android/dummy_spnego_authenticator_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/net/android/dummy_spnego_authenticator_jni.srcjar " +
+         "'$(genDir)/net/android/dummy_spnego_authenticator_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/net/android/dummy_spnego_authenticator_jni_placeholder.srcjar " +
+         "'$(genDir)/net/android/dummy_spnego_authenticator_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "DummySpnegoAuthenticator_jni.h " +
          "--input-file " +
-         "$(location net/test/android/javatests/src/org/chromium/net/test/DummySpnegoAuthenticator.java)",
+         "'$(location net/test/android/javatests/src/org/chromium/net/test/DummySpnegoAuthenticator.java)'",
     host_cross_supported: false,
     out: [
         "net/android/dummy_spnego_authenticator_jni.srcjar",
         "net/android/dummy_spnego_authenticator_jni/DummySpnegoAuthenticator_jni.h",
+        "net/android/dummy_spnego_authenticator_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -10305,23 +15759,26 @@
         "net/test/android/javatests/src/org/chromium/net/test/DummySpnegoAuthenticator.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/net/android/dummy_spnego_authenticator_jni &&  " +
-         "mkdir -p $(genDir)/net/android && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/net/android &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/net/android/dummy_spnego_authenticator_jni " +
+         "'$(genDir)/net/android/dummy_spnego_authenticator_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/net/android/dummy_spnego_authenticator_jni.srcjar " +
+         "'$(genDir)/net/android/dummy_spnego_authenticator_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/net/android/dummy_spnego_authenticator_jni_placeholder.srcjar " +
+         "'$(genDir)/net/android/dummy_spnego_authenticator_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "DummySpnegoAuthenticator_jni.h " +
          "--input-file " +
-         "$(location net/test/android/javatests/src/org/chromium/net/test/DummySpnegoAuthenticator.java)",
+         "'$(location net/test/android/javatests/src/org/chromium/net/test/DummySpnegoAuthenticator.java)'",
     out: [
         "net/android/dummy_spnego_authenticator_jni.srcjar",
         "net/android/dummy_spnego_authenticator_jni/DummySpnegoAuthenticator_jni.h",
+        "net/android/dummy_spnego_authenticator_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -10347,6 +15804,18 @@
     ],
 }
 
+// GN: //net/android:dummy_spnego_authenticator_jni__action__testing
+java_genrule {
+    name: "tot_cronet_net_android_dummy_spnego_authenticator_jni__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_net_android_dummy_spnego_authenticator_jni__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "dummy_spnego_authenticator_jni.srcjar",
+    ],
+}
+
 // GN: //net/android:embedded_test_server_aidl__testing
 java_library {
     name: "tot_cronet_net_android_embedded_test_server_aidl__testing",
@@ -10370,7 +15839,38 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //net/android:embedded_test_server_aidl_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_net_android_embedded_test_server_aidl_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_net_android_embedded_test_server_aidl_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/net/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "net/android/embedded_test_server_aidl_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //net/android:net_android_java_enums_srcjar
@@ -10381,14 +15881,16 @@
         "net/android/traffic_stats.cc",
         "net/socket/socket_tag.cc",
     ],
-    cmd: "mkdir -p $(genDir)/net/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/base/network_change_notifier.h) " +
-         "$(location net/socket/socket_tag.cc) " +
-         "$(location net/android/cert_verify_result_android.h) " +
-         "$(location net/android/keystore.h) " +
-         "$(location net/android/network_change_notifier_android.cc) " +
-         "$(location net/android/traffic_stats.cc)",
+    cmd: "mkdir -p $(genDir)/net/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/base/network_change_notifier.h)' " +
+         "'$(location net/socket/socket_tag.cc)' " +
+         "'$(location net/android/cert_verify_result_android.h)' " +
+         "'$(location net/android/keystore.h)' " +
+         "'$(location net/android/network_change_notifier_android.cc)' " +
+         "'$(location net/android/traffic_stats.cc)'",
     out: [
         "net/android/net_android_java_enums_srcjar.srcjar",
     ],
@@ -10417,14 +15919,16 @@
         "net/android/traffic_stats.cc",
         "net/socket/socket_tag.cc",
     ],
-    cmd: "mkdir -p $(genDir)/net/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/base/network_change_notifier.h) " +
-         "$(location net/socket/socket_tag.cc) " +
-         "$(location net/android/cert_verify_result_android.h) " +
-         "$(location net/android/keystore.h) " +
-         "$(location net/android/network_change_notifier_android.cc) " +
-         "$(location net/android/traffic_stats.cc)",
+    cmd: "mkdir -p $(genDir)/net/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/base/network_change_notifier.h)' " +
+         "'$(location net/socket/socket_tag.cc)' " +
+         "'$(location net/android/cert_verify_result_android.h)' " +
+         "'$(location net/android/keystore.h)' " +
+         "'$(location net/android/network_change_notifier_android.cc)' " +
+         "'$(location net/android/traffic_stats.cc)'",
     out: [
         "net/android/net_android_java_enums_srcjar.srcjar",
     ],
@@ -10539,12 +16043,76 @@
     ],
 }
 
-// GN: //net/android:net_java_test_support__testing
+// GN: //net/android:net_java__process_device
+java_genrule {
+    name: "tot_cronet_net_android_net_java__process_device",
+    srcs: [
+        ":tot_cronet_net_android_net_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/net/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "net/android/net_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/android:net_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_net_android_net_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_net_android_net_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/net/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "net/android/net_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/android:net_java_test_support__compile_java__testing
 java_library {
-    name: "tot_cronet_net_android_net_java_test_support__testing",
+    name: "tot_cronet_net_android_net_java_test_support__compile_java__testing",
     srcs: [
         ":tot_cronet_net_android_net_java_test_support_enums_srcjar__testing",
-        ":tot_cronet_net_android_net_test_support_jni__action__testing__java",
+        ":tot_cronet_net_android_net_test_support_jni__action__testing__java_proxy_only",
         "net/test/android/javatests/src/org/chromium/net/AndroidNetworkLibraryTestUtil.java",
         "net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServer.java",
         "net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServerRule.java",
@@ -10556,35 +16124,116 @@
     static_libs: [
         "androidx.test.uiautomator_uiautomator",
         "junit",
-        "tot_cronet_base_base_java__testing",
-        "tot_cronet_base_base_java_test_support__testing",
-        "tot_cronet_base_base_java_url_utils_for_test__testing",
-        "tot_cronet_net_android_embedded_test_server_aidl_java__testing",
-        "tot_cronet_net_android_net_java__testing",
-        "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
     ],
     apex_available: [
         "com.android.tethering",
     ],
     min_sdk_version: "30",
     libs: [
+        "android.test.mock.stubs",
         "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "androidx.core_core",
         "androidx.test.monitor",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_android_info_java__compile_java__testing",
+        "tot_cronet_base_android_runtime_jni_headers_java__testing",
+        "tot_cronet_base_base_cached_flags_java__compile_java__testing",
+        "tot_cronet_base_base_java__compile_java__testing",
+        "tot_cronet_base_base_java_test_support__compile_java__testing",
+        "tot_cronet_base_base_java_url_utils_for_test__compile_java__testing",
+        "tot_cronet_base_base_jni_java__compile_java__testing",
+        "tot_cronet_base_base_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_base_shared_preferences_java__compile_java__testing",
+        "tot_cronet_base_base_shared_preferences_jni_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_build_info_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_flagged_apis_java__compile_java__testing",
+        "tot_cronet_base_jank_tracker_java__compile_java__testing",
+        "tot_cronet_base_library_loader_java__compile_java__testing",
+        "tot_cronet_base_library_loader_jni_java__compile_java__testing",
+        "tot_cronet_base_lifetime_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_memory_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_promise_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_service_loader_java__compile_java__testing",
+        "tot_cronet_base_stream_util_java__compile_java__testing",
+        "tot_cronet_base_supplier_java__compile_java__testing",
+        "tot_cronet_base_sys_utils_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_base_unowned_user_data_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_channel_enum_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_version_constants_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_net_android_embedded_test_server_aidl__testing",
+        "tot_cronet_net_android_embedded_test_server_aidl_java__compile_java__testing",
+        "tot_cronet_net_android_net_java__compile_java__testing",
+        "tot_cronet_net_android_net_thread_stats_uid_java__compile_java__testing",
+        "tot_cronet_testing_android_instrumentation_test_runner_java__compile_java__testing",
+        "tot_cronet_testing_android_instrumentation_test_runner_permissions_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
     ],
     sdk_version: "current",
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //net/android:net_java_test_support__process_device__testing
+java_genrule {
+    name: "tot_cronet_net_android_net_java_test_support__process_device__testing",
+    srcs: [
+        ":tot_cronet_net_android_net_java_test_support__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/net/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "net/android/net_java_test_support.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //net/android:net_java_test_support_enums_srcjar__testing
 java_genrule {
     name: "tot_cronet_net_android_net_java_test_support_enums_srcjar__testing",
-    cmd: "mkdir -p $(genDir)/net/android && $(location build/android/gyp/java_cpp_enum.py) --srcjar " +
-         "$(out) " +
-         "$(location net/test/embedded_test_server/embedded_test_server.h) " +
-         "$(location net/test/url_request/url_request_failed_job.h)",
+    cmd: "mkdir -p $(genDir)/net/android &&  " +
+         "$(location build/android/gyp/java_cpp_enum.py) " +
+         "--srcjar " +
+         "'$(out)' " +
+         "'$(location net/test/embedded_test_server/embedded_test_server.h)' " +
+         "'$(location net/test/url_request/url_request_failed_job.h)'",
     out: [
         "net/android/net_java_test_support_enums_srcjar.srcjar",
     ],
@@ -10611,24 +16260,27 @@
         "net/test/android/javatests/src/org/chromium/net/AndroidNetworkLibraryTestUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/net/android/net_test_support_jni &&  " +
-         "mkdir -p $(genDir)/net/android && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/net/android &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/net/android/net_test_support_jni " +
+         "'$(genDir)/net/android/net_test_support_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/net/android/net_test_support_jni.srcjar " +
+         "'$(genDir)/net/android/net_test_support_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/net/android/net_test_support_jni_placeholder.srcjar " +
+         "'$(genDir)/net/android/net_test_support_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "AndroidNetworkLibraryTestUtil_jni.h " +
          "--input-file " +
-         "$(location net/test/android/javatests/src/org/chromium/net/AndroidNetworkLibraryTestUtil.java)",
+         "'$(location net/test/android/javatests/src/org/chromium/net/AndroidNetworkLibraryTestUtil.java)'",
     host_cross_supported: false,
     out: [
         "net/android/net_test_support_jni.srcjar",
         "net/android/net_test_support_jni/AndroidNetworkLibraryTestUtil_jni.h",
+        "net/android/net_test_support_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -10664,23 +16316,26 @@
         "net/test/android/javatests/src/org/chromium/net/AndroidNetworkLibraryTestUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/net/android/net_test_support_jni &&  " +
-         "mkdir -p $(genDir)/net/android && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/net/android &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/net/android/net_test_support_jni " +
+         "'$(genDir)/net/android/net_test_support_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/net/android/net_test_support_jni.srcjar " +
+         "'$(genDir)/net/android/net_test_support_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/net/android/net_test_support_jni_placeholder.srcjar " +
+         "'$(genDir)/net/android/net_test_support_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "AndroidNetworkLibraryTestUtil_jni.h " +
          "--input-file " +
-         "$(location net/test/android/javatests/src/org/chromium/net/AndroidNetworkLibraryTestUtil.java)",
+         "'$(location net/test/android/javatests/src/org/chromium/net/AndroidNetworkLibraryTestUtil.java)'",
     out: [
         "net/android/net_test_support_jni.srcjar",
         "net/android/net_test_support_jni/AndroidNetworkLibraryTestUtil_jni.h",
+        "net/android/net_test_support_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -10706,31 +16361,115 @@
     ],
 }
 
-// GN: //net/android:net_test_support_provider_java__testing
-java_library {
-    name: "tot_cronet_net_android_net_test_support_provider_java__testing",
+// GN: //net/android:net_test_support_jni__action__testing
+java_genrule {
+    name: "tot_cronet_net_android_net_test_support_jni__action__testing__java_proxy_only",
     srcs: [
-        ":tot_cronet_net_android_net_test_support_provider_jni__action__testing__java",
+        ":tot_cronet_net_android_net_test_support_jni__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "net_test_support_jni.srcjar",
+    ],
+}
+
+// GN: //net/android:net_test_support_provider_java__compile_java__testing
+java_library {
+    name: "tot_cronet_net_android_net_test_support_provider_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_net_android_net_test_support_provider_jni__action__testing__java_proxy_only",
         "net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServerImpl.java",
         "net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServerService.java",
     ],
-    static_libs: [
-        "tot_cronet_base_base_java__testing",
-        "tot_cronet_base_base_java_url_utils_for_test__testing",
-        "tot_cronet_net_android_embedded_test_server_aidl_java__testing",
-        "tot_cronet_net_android_net_java__testing",
-        "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
-    ],
     apex_available: [
         "com.android.tethering",
     ],
     min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_android_info_java__compile_java__testing",
+        "tot_cronet_base_android_runtime_jni_headers_java__testing",
+        "tot_cronet_base_base_java__compile_java__testing",
+        "tot_cronet_base_base_java_url_utils_for_test__compile_java__testing",
+        "tot_cronet_base_base_jni_java__compile_java__testing",
+        "tot_cronet_base_base_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_build_info_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_flagged_apis_java__compile_java__testing",
+        "tot_cronet_base_jank_tracker_java__compile_java__testing",
+        "tot_cronet_base_library_loader_java__compile_java__testing",
+        "tot_cronet_base_library_loader_jni_java__compile_java__testing",
+        "tot_cronet_base_lifetime_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_memory_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_promise_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_service_loader_java__compile_java__testing",
+        "tot_cronet_base_stream_util_java__compile_java__testing",
+        "tot_cronet_base_supplier_java__compile_java__testing",
+        "tot_cronet_base_sys_utils_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_base_unowned_user_data_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_channel_enum_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_version_constants_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_net_android_embedded_test_server_aidl__testing",
+        "tot_cronet_net_android_embedded_test_server_aidl_java__compile_java__testing",
+        "tot_cronet_net_android_net_java__compile_java__testing",
+        "tot_cronet_net_android_net_thread_stats_uid_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
     sdk_version: "current",
     visibility: [
         "//external/cronet:__subpackages__",
-        "//packages/modules/Connectivity:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //net/android:net_test_support_provider_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_net_android_net_test_support_provider_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_net_android_net_test_support_provider_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/net/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "net/android/net_test_support_provider_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //net/android:net_test_support_provider_jni__action__testing
@@ -10740,23 +16479,26 @@
         "net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServerImpl.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/net/android/net_test_support_provider_jni &&  " +
-         "mkdir -p $(genDir)/net/android && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/net/android &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/net/android/net_test_support_provider_jni " +
+         "'$(genDir)/net/android/net_test_support_provider_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/net/android/net_test_support_provider_jni.srcjar " +
+         "'$(genDir)/net/android/net_test_support_provider_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/net/android/net_test_support_provider_jni_placeholder.srcjar " +
+         "'$(genDir)/net/android/net_test_support_provider_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "EmbeddedTestServerImpl_jni.h " +
          "--input-file " +
-         "$(location net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServerImpl.java)",
+         "'$(location net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServerImpl.java)'",
     out: [
         "net/android/net_test_support_provider_jni.srcjar",
         "net/android/net_test_support_provider_jni/EmbeddedTestServerImpl_jni.h",
+        "net/android/net_test_support_provider_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -10782,6 +16524,50 @@
     ],
 }
 
+// GN: //net/android:net_test_support_provider_jni__action__testing
+java_genrule {
+    name: "tot_cronet_net_android_net_test_support_provider_jni__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_net_android_net_test_support_provider_jni__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "net_test_support_provider_jni.srcjar",
+    ],
+}
+
+// GN: //net/android:net_tests_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_net_android_net_tests_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_net_android_net_tests_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/net/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "net/android/net_tests_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //net/android:net_tests_jni__action__testing
 cc_genrule {
     name: "tot_cronet_net_android_net_tests_jni__action__testing",
@@ -10790,29 +16576,32 @@
         "net/android/javatests/src/org/chromium/net/AndroidProxyConfigServiceTestUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/net/android/net_tests_jni &&  " +
-         "mkdir -p $(genDir)/net/android && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/net/android &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/net/android/net_tests_jni " +
+         "'$(genDir)/net/android/net_tests_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/net/android/net_tests_jni.srcjar " +
+         "'$(genDir)/net/android/net_tests_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/net/android/net_tests_jni_placeholder.srcjar " +
+         "'$(genDir)/net/android/net_tests_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "AndroidKeyStoreTestUtil_jni.h " +
          "--output-name " +
          "AndroidProxyConfigServiceTestUtil_jni.h " +
          "--input-file " +
-         "$(location net/android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java) " +
+         "'$(location net/android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java)' " +
          "--input-file " +
-         "$(location net/android/javatests/src/org/chromium/net/AndroidProxyConfigServiceTestUtil.java)",
+         "'$(location net/android/javatests/src/org/chromium/net/AndroidProxyConfigServiceTestUtil.java)'",
     host_cross_supported: false,
     out: [
         "net/android/net_tests_jni.srcjar",
         "net/android/net_tests_jni/AndroidKeyStoreTestUtil_jni.h",
         "net/android/net_tests_jni/AndroidProxyConfigServiceTestUtil_jni.h",
+        "net/android/net_tests_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -10849,28 +16638,31 @@
         "net/android/javatests/src/org/chromium/net/AndroidProxyConfigServiceTestUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/net/android/net_tests_jni &&  " +
-         "mkdir -p $(genDir)/net/android && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/net/android &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/net/android/net_tests_jni " +
+         "'$(genDir)/net/android/net_tests_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/net/android/net_tests_jni.srcjar " +
+         "'$(genDir)/net/android/net_tests_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/net/android/net_tests_jni_placeholder.srcjar " +
+         "'$(genDir)/net/android/net_tests_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "AndroidKeyStoreTestUtil_jni.h " +
          "--output-name " +
          "AndroidProxyConfigServiceTestUtil_jni.h " +
          "--input-file " +
-         "$(location net/android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java) " +
+         "'$(location net/android/javatests/src/org/chromium/net/AndroidKeyStoreTestUtil.java)' " +
          "--input-file " +
-         "$(location net/android/javatests/src/org/chromium/net/AndroidProxyConfigServiceTestUtil.java)",
+         "'$(location net/android/javatests/src/org/chromium/net/AndroidProxyConfigServiceTestUtil.java)'",
     out: [
         "net/android/net_tests_jni.srcjar",
         "net/android/net_tests_jni/AndroidKeyStoreTestUtil_jni.h",
         "net/android/net_tests_jni/AndroidProxyConfigServiceTestUtil_jni.h",
+        "net/android/net_tests_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -10896,52 +16688,232 @@
     ],
 }
 
-// GN: //net/base/registry_controlled_domains:lookup_strings_test_sets__testing
+// GN: //net/android:net_tests_jni__action__testing
+java_genrule {
+    name: "tot_cronet_net_android_net_tests_jni__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_net_android_net_tests_jni__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "net_tests_jni.srcjar",
+    ],
+}
+
+// GN: //net/android:net_thread_stats_uid_java__process_device
+java_genrule {
+    name: "tot_cronet_net_android_net_thread_stats_uid_java__process_device",
+    srcs: [
+        ":tot_cronet_net_android_net_thread_stats_uid_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/net/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "net/android/net_thread_stats_uid_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/android:net_thread_stats_uid_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_net_android_net_thread_stats_uid_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_net_android_net_thread_stats_uid_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/net/android &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "net/android/net_thread_stats_uid_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:lookup_strings_test_sets__testing_0
 cc_genrule {
-    name: "tot_cronet_net_base_registry_controlled_domains_lookup_strings_test_sets__testing",
-    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains && $(location net/tools/dafsa/make_dafsa.py) $(location net/base/registry_controlled_domains/effective_tld_names.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest1.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest1-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest2.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest2-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest3.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest3-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest4.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest4-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest5.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest5-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest6.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest6-inc.cc)",
+    name: "tot_cronet_net_base_registry_controlled_domains_lookup_strings_test_sets__testing_0",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names-inc.cc)'",
     host_cross_supported: false,
     out: [
         "net/base/registry_controlled_domains/effective_tld_names-inc.cc",
+    ],
+    tool_files: [
+        "net/base/registry_controlled_domains/effective_tld_names.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:lookup_strings_test_sets__testing_1
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_lookup_strings_test_sets__testing_1",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest1.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest1-inc.cc)'",
+    host_cross_supported: false,
+    out: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest1-inc.cc",
+    ],
+    tool_files: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest1.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:lookup_strings_test_sets__testing_2
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_lookup_strings_test_sets__testing_2",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest2.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest2-inc.cc)'",
+    host_cross_supported: false,
+    out: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest2-inc.cc",
+    ],
+    tool_files: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest2.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:lookup_strings_test_sets__testing_3
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_lookup_strings_test_sets__testing_3",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest3.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest3-inc.cc)'",
+    host_cross_supported: false,
+    out: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest3-inc.cc",
+    ],
+    tool_files: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest3.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:lookup_strings_test_sets__testing_4
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_lookup_strings_test_sets__testing_4",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest4.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest4-inc.cc)'",
+    host_cross_supported: false,
+    out: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest4-inc.cc",
+    ],
+    tool_files: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest4.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:lookup_strings_test_sets__testing_5
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_lookup_strings_test_sets__testing_5",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest5.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest5-inc.cc)'",
+    host_cross_supported: false,
+    out: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest5-inc.cc",
+    ],
+    tool_files: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest5.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:lookup_strings_test_sets__testing_6
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_lookup_strings_test_sets__testing_6",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest6.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest6-inc.cc)'",
+    host_cross_supported: false,
+    out: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest6-inc.cc",
     ],
     tool_files: [
-        "net/base/registry_controlled_domains/effective_tld_names.gperf",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest1.gperf",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest2.gperf",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest3.gperf",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest4.gperf",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest5.gperf",
         "net/base/registry_controlled_domains/effective_tld_names_unittest6.gperf",
         "net/tools/dafsa/make_dafsa.py",
     ],
@@ -10953,59 +16925,163 @@
     ],
 }
 
-// GN: //net/base/registry_controlled_domains:registry_controlled_domains
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains_0
 cc_genrule {
-    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains",
-    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains && $(location net/tools/dafsa/make_dafsa.py) --reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names-reversed-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains_0",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
          "--reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest1.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest1-reversed-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "--reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest2.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest2-reversed-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "--reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest3.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest3-reversed-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "--reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest4.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest4-reversed-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "--reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest5.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest5-reversed-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "--reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest6.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest6-reversed-inc.cc)",
+         "'$(location net/base/registry_controlled_domains/effective_tld_names.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names-reversed-inc.cc)'",
     host_cross_supported: false,
     out: [
         "net/base/registry_controlled_domains/effective_tld_names-reversed-inc.cc",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest1-reversed-inc.cc",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest2-reversed-inc.cc",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest3-reversed-inc.cc",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest4-reversed-inc.cc",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest5-reversed-inc.cc",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest6-reversed-inc.cc",
     ],
     tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains_1
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains_1",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "--reverse " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest1.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest1-reversed-inc.cc)'",
+    host_cross_supported: false,
+    out: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest1-reversed-inc.cc",
+    ],
+    tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest1.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains_2
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains_2",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "--reverse " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest2.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest2-reversed-inc.cc)'",
+    host_cross_supported: false,
+    out: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest2-reversed-inc.cc",
+    ],
+    tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest2.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains_3
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains_3",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "--reverse " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest3.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest3-reversed-inc.cc)'",
+    host_cross_supported: false,
+    out: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest3-reversed-inc.cc",
+    ],
+    tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest3.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains_4
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains_4",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "--reverse " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest4.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest4-reversed-inc.cc)'",
+    host_cross_supported: false,
+    out: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest4-reversed-inc.cc",
+    ],
+    tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest4.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains_5
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains_5",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "--reverse " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest5.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest5-reversed-inc.cc)'",
+    host_cross_supported: false,
+    out: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest5-reversed-inc.cc",
+    ],
+    tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest5.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains_6
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains_6",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "--reverse " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest6.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest6-reversed-inc.cc)'",
+    host_cross_supported: false,
+    out: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest6-reversed-inc.cc",
+    ],
+    tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest6.gperf",
         "net/tools/dafsa/make_dafsa.py",
     ],
@@ -11017,59 +17093,163 @@
     ],
 }
 
-// GN: //net/base/registry_controlled_domains:registry_controlled_domains__testing
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains__testing_0
 cc_genrule {
-    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains__testing",
-    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains && $(location net/tools/dafsa/make_dafsa.py) --reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names-reversed-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains__testing_0",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
          "--reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest1.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest1-reversed-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "--reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest2.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest2-reversed-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "--reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest3.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest3-reversed-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "--reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest4.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest4-reversed-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "--reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest5.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest5-reversed-inc.cc) " +
-         "&& " +
-         "python3 $(location net/tools/dafsa/make_dafsa.py) " +
-         "--reverse " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest6.gperf) " +
-         "$(location net/base/registry_controlled_domains/effective_tld_names_unittest6-reversed-inc.cc)",
+         "'$(location net/base/registry_controlled_domains/effective_tld_names.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names-reversed-inc.cc)'",
     host_cross_supported: false,
     out: [
         "net/base/registry_controlled_domains/effective_tld_names-reversed-inc.cc",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest1-reversed-inc.cc",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest2-reversed-inc.cc",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest3-reversed-inc.cc",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest4-reversed-inc.cc",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest5-reversed-inc.cc",
-        "net/base/registry_controlled_domains/effective_tld_names_unittest6-reversed-inc.cc",
     ],
     tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains__testing_1
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains__testing_1",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "--reverse " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest1.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest1-reversed-inc.cc)'",
+    host_cross_supported: false,
+    out: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest1-reversed-inc.cc",
+    ],
+    tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest1.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains__testing_2
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains__testing_2",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "--reverse " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest2.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest2-reversed-inc.cc)'",
+    host_cross_supported: false,
+    out: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest2-reversed-inc.cc",
+    ],
+    tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest2.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains__testing_3
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains__testing_3",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "--reverse " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest3.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest3-reversed-inc.cc)'",
+    host_cross_supported: false,
+    out: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest3-reversed-inc.cc",
+    ],
+    tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest3.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains__testing_4
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains__testing_4",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "--reverse " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest4.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest4-reversed-inc.cc)'",
+    host_cross_supported: false,
+    out: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest4-reversed-inc.cc",
+    ],
+    tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest4.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains__testing_5
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains__testing_5",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "--reverse " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest5.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest5-reversed-inc.cc)'",
+    host_cross_supported: false,
+    out: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest5-reversed-inc.cc",
+    ],
+    tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest5.gperf",
+        "net/tools/dafsa/make_dafsa.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/base/registry_controlled_domains:registry_controlled_domains__testing_6
+cc_genrule {
+    name: "tot_cronet_net_base_registry_controlled_domains_registry_controlled_domains__testing_6",
+    cmd: "mkdir -p $(genDir)/net/base/registry_controlled_domains &&  " +
+         "$(location net/tools/dafsa/make_dafsa.py) " +
+         "--reverse " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest6.gperf)' " +
+         "'$(location net/base/registry_controlled_domains/effective_tld_names_unittest6-reversed-inc.cc)'",
+    host_cross_supported: false,
+    out: [
+        "net/base/registry_controlled_domains/effective_tld_names_unittest6-reversed-inc.cc",
+    ],
+    tool_files: [
         "net/base/registry_controlled_domains/effective_tld_names_unittest6.gperf",
         "net/tools/dafsa/make_dafsa.py",
     ],
@@ -11086,64 +17266,74 @@
     name: "tot_cronet_net_buildflags",
     cmd: "if [[ ( $$CC_ARCH == 'arm' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/net && echo '--flags POSIX_BYPASS_MMAP=\"true\" DISABLE_FILE_SUPPORT=\"true\" ENABLE_MDNS=\"false\" ENABLE_REPORTING=\"true\" ENABLE_WEBSOCKETS=\"false\" ENABLE_CLIENT_CERTIFICATES=\"true\" INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=\"false\" USE_KERBEROS=\"true\" USE_EXTERNAL_GSSAPI=\"false\" CHROME_ROOT_STORE_OPTIONAL=\"false\" CHROME_ROOT_STORE_ONLY=\"false\" CHROME_ROOT_STORE_SUPPORTED=\"false\" ENABLE_DEVICE_BOUND_SESSIONS=\"false\" ENABLE_BRACKETED_PROXY_URIS=\"false\" ENABLE_QUIC_PROXY_SUPPORT=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/net &&  " +
+         "echo '--flags POSIX_BYPASS_MMAP=true DISABLE_FILE_SUPPORT=true ENABLE_MDNS=false ENABLE_REPORTING=true ENABLE_WEBSOCKETS=false ENABLE_CLIENT_CERTIFICATES=true INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=false USE_KERBEROS=true USE_EXTERNAL_GSSAPI=false CHROME_ROOT_STORE_OPTIONAL=false CHROME_ROOT_STORE_ONLY=false CHROME_ROOT_STORE_SUPPORTED=false ENABLE_DEVICE_BOUND_SESSIONS=false ENABLE_BRACKETED_PROXY_URIS=false ENABLE_QUIC_PROXY_SUPPORT=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//net:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'arm64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/net && echo '--flags POSIX_BYPASS_MMAP=\"true\" DISABLE_FILE_SUPPORT=\"true\" ENABLE_MDNS=\"false\" ENABLE_REPORTING=\"true\" ENABLE_WEBSOCKETS=\"false\" ENABLE_CLIENT_CERTIFICATES=\"true\" INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=\"false\" USE_KERBEROS=\"true\" USE_EXTERNAL_GSSAPI=\"false\" CHROME_ROOT_STORE_OPTIONAL=\"false\" CHROME_ROOT_STORE_ONLY=\"false\" CHROME_ROOT_STORE_SUPPORTED=\"false\" ENABLE_DEVICE_BOUND_SESSIONS=\"false\" ENABLE_BRACKETED_PROXY_URIS=\"false\" ENABLE_QUIC_PROXY_SUPPORT=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/net &&  " +
+         "echo '--flags POSIX_BYPASS_MMAP=true DISABLE_FILE_SUPPORT=true ENABLE_MDNS=false ENABLE_REPORTING=true ENABLE_WEBSOCKETS=false ENABLE_CLIENT_CERTIFICATES=true INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=false USE_KERBEROS=true USE_EXTERNAL_GSSAPI=false CHROME_ROOT_STORE_OPTIONAL=false CHROME_ROOT_STORE_ONLY=false CHROME_ROOT_STORE_SUPPORTED=false ENABLE_DEVICE_BOUND_SESSIONS=false ENABLE_BRACKETED_PROXY_URIS=false ENABLE_QUIC_PROXY_SUPPORT=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//net:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'riscv64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/net && echo '--flags POSIX_BYPASS_MMAP=\"true\" DISABLE_FILE_SUPPORT=\"true\" ENABLE_MDNS=\"false\" ENABLE_REPORTING=\"true\" ENABLE_WEBSOCKETS=\"false\" ENABLE_CLIENT_CERTIFICATES=\"true\" INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=\"false\" USE_KERBEROS=\"true\" USE_EXTERNAL_GSSAPI=\"false\" CHROME_ROOT_STORE_OPTIONAL=\"false\" CHROME_ROOT_STORE_ONLY=\"false\" CHROME_ROOT_STORE_SUPPORTED=\"false\" ENABLE_DEVICE_BOUND_SESSIONS=\"false\" ENABLE_BRACKETED_PROXY_URIS=\"false\" ENABLE_QUIC_PROXY_SUPPORT=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/net &&  " +
+         "echo '--flags POSIX_BYPASS_MMAP=true DISABLE_FILE_SUPPORT=true ENABLE_MDNS=false ENABLE_REPORTING=true ENABLE_WEBSOCKETS=false ENABLE_CLIENT_CERTIFICATES=true INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=false USE_KERBEROS=true USE_EXTERNAL_GSSAPI=false CHROME_ROOT_STORE_OPTIONAL=false CHROME_ROOT_STORE_ONLY=false CHROME_ROOT_STORE_SUPPORTED=false ENABLE_DEVICE_BOUND_SESSIONS=false ENABLE_BRACKETED_PROXY_URIS=false ENABLE_QUIC_PROXY_SUPPORT=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//net:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/net && echo '--flags POSIX_BYPASS_MMAP=\"false\" DISABLE_FILE_SUPPORT=\"true\" ENABLE_MDNS=\"false\" ENABLE_REPORTING=\"true\" ENABLE_WEBSOCKETS=\"false\" ENABLE_CLIENT_CERTIFICATES=\"true\" INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=\"false\" USE_KERBEROS=\"true\" USE_EXTERNAL_GSSAPI=\"false\" CHROME_ROOT_STORE_OPTIONAL=\"false\" CHROME_ROOT_STORE_ONLY=\"false\" CHROME_ROOT_STORE_SUPPORTED=\"false\" ENABLE_DEVICE_BOUND_SESSIONS=\"false\" ENABLE_BRACKETED_PROXY_URIS=\"false\" ENABLE_QUIC_PROXY_SUPPORT=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/net &&  " +
+         "echo '--flags POSIX_BYPASS_MMAP=false DISABLE_FILE_SUPPORT=true ENABLE_MDNS=false ENABLE_REPORTING=true ENABLE_WEBSOCKETS=false ENABLE_CLIENT_CERTIFICATES=true INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=false USE_KERBEROS=true USE_EXTERNAL_GSSAPI=false CHROME_ROOT_STORE_OPTIONAL=false CHROME_ROOT_STORE_ONLY=false CHROME_ROOT_STORE_SUPPORTED=false ENABLE_DEVICE_BOUND_SESSIONS=false ENABLE_BRACKETED_PROXY_URIS=false ENABLE_QUIC_PROXY_SUPPORT=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//net:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86_64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/net && echo '--flags POSIX_BYPASS_MMAP=\"true\" DISABLE_FILE_SUPPORT=\"true\" ENABLE_MDNS=\"false\" ENABLE_REPORTING=\"true\" ENABLE_WEBSOCKETS=\"false\" ENABLE_CLIENT_CERTIFICATES=\"true\" INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=\"false\" USE_KERBEROS=\"true\" USE_EXTERNAL_GSSAPI=\"false\" CHROME_ROOT_STORE_OPTIONAL=\"false\" CHROME_ROOT_STORE_ONLY=\"false\" CHROME_ROOT_STORE_SUPPORTED=\"false\" ENABLE_DEVICE_BOUND_SESSIONS=\"false\" ENABLE_BRACKETED_PROXY_URIS=\"false\" ENABLE_QUIC_PROXY_SUPPORT=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/net &&  " +
+         "echo '--flags POSIX_BYPASS_MMAP=true DISABLE_FILE_SUPPORT=true ENABLE_MDNS=false ENABLE_REPORTING=true ENABLE_WEBSOCKETS=false ENABLE_CLIENT_CERTIFICATES=true INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=false USE_KERBEROS=true USE_EXTERNAL_GSSAPI=false CHROME_ROOT_STORE_OPTIONAL=false CHROME_ROOT_STORE_ONLY=false CHROME_ROOT_STORE_SUPPORTED=false ENABLE_DEVICE_BOUND_SESSIONS=false ENABLE_BRACKETED_PROXY_URIS=false ENABLE_QUIC_PROXY_SUPPORT=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//net:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi;",
+         "/dev/stdin " +
+         ";fi;",
     host_cross_supported: false,
     out: [
         "net/net_buildflags.h",
@@ -11164,64 +17354,74 @@
     name: "tot_cronet_net_buildflags__testing",
     cmd: "if [[ ( $$CC_ARCH == 'arm' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/net && echo '--flags POSIX_BYPASS_MMAP=\"true\" DISABLE_FILE_SUPPORT=\"true\" ENABLE_MDNS=\"false\" ENABLE_REPORTING=\"true\" ENABLE_WEBSOCKETS=\"false\" ENABLE_CLIENT_CERTIFICATES=\"true\" INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=\"false\" USE_KERBEROS=\"true\" USE_EXTERNAL_GSSAPI=\"false\" CHROME_ROOT_STORE_OPTIONAL=\"false\" CHROME_ROOT_STORE_ONLY=\"false\" CHROME_ROOT_STORE_SUPPORTED=\"false\" ENABLE_DEVICE_BOUND_SESSIONS=\"false\" ENABLE_BRACKETED_PROXY_URIS=\"false\" ENABLE_QUIC_PROXY_SUPPORT=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/net &&  " +
+         "echo '--flags POSIX_BYPASS_MMAP=true DISABLE_FILE_SUPPORT=true ENABLE_MDNS=false ENABLE_REPORTING=true ENABLE_WEBSOCKETS=false ENABLE_CLIENT_CERTIFICATES=true INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=false USE_KERBEROS=true USE_EXTERNAL_GSSAPI=false CHROME_ROOT_STORE_OPTIONAL=false CHROME_ROOT_STORE_ONLY=false CHROME_ROOT_STORE_SUPPORTED=false ENABLE_DEVICE_BOUND_SESSIONS=false ENABLE_BRACKETED_PROXY_URIS=false ENABLE_QUIC_PROXY_SUPPORT=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//net:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'arm64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/net && echo '--flags POSIX_BYPASS_MMAP=\"true\" DISABLE_FILE_SUPPORT=\"true\" ENABLE_MDNS=\"false\" ENABLE_REPORTING=\"true\" ENABLE_WEBSOCKETS=\"false\" ENABLE_CLIENT_CERTIFICATES=\"true\" INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=\"false\" USE_KERBEROS=\"true\" USE_EXTERNAL_GSSAPI=\"false\" CHROME_ROOT_STORE_OPTIONAL=\"false\" CHROME_ROOT_STORE_ONLY=\"false\" CHROME_ROOT_STORE_SUPPORTED=\"false\" ENABLE_DEVICE_BOUND_SESSIONS=\"false\" ENABLE_BRACKETED_PROXY_URIS=\"false\" ENABLE_QUIC_PROXY_SUPPORT=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/net &&  " +
+         "echo '--flags POSIX_BYPASS_MMAP=true DISABLE_FILE_SUPPORT=true ENABLE_MDNS=false ENABLE_REPORTING=true ENABLE_WEBSOCKETS=false ENABLE_CLIENT_CERTIFICATES=true INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=false USE_KERBEROS=true USE_EXTERNAL_GSSAPI=false CHROME_ROOT_STORE_OPTIONAL=false CHROME_ROOT_STORE_ONLY=false CHROME_ROOT_STORE_SUPPORTED=false ENABLE_DEVICE_BOUND_SESSIONS=false ENABLE_BRACKETED_PROXY_URIS=false ENABLE_QUIC_PROXY_SUPPORT=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//net:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'riscv64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/net && echo '--flags POSIX_BYPASS_MMAP=\"true\" DISABLE_FILE_SUPPORT=\"true\" ENABLE_MDNS=\"false\" ENABLE_REPORTING=\"true\" ENABLE_WEBSOCKETS=\"false\" ENABLE_CLIENT_CERTIFICATES=\"true\" INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=\"false\" USE_KERBEROS=\"true\" USE_EXTERNAL_GSSAPI=\"false\" CHROME_ROOT_STORE_OPTIONAL=\"false\" CHROME_ROOT_STORE_ONLY=\"false\" CHROME_ROOT_STORE_SUPPORTED=\"false\" ENABLE_DEVICE_BOUND_SESSIONS=\"false\" ENABLE_BRACKETED_PROXY_URIS=\"false\" ENABLE_QUIC_PROXY_SUPPORT=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/net &&  " +
+         "echo '--flags POSIX_BYPASS_MMAP=true DISABLE_FILE_SUPPORT=true ENABLE_MDNS=false ENABLE_REPORTING=true ENABLE_WEBSOCKETS=false ENABLE_CLIENT_CERTIFICATES=true INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=false USE_KERBEROS=true USE_EXTERNAL_GSSAPI=false CHROME_ROOT_STORE_OPTIONAL=false CHROME_ROOT_STORE_ONLY=false CHROME_ROOT_STORE_SUPPORTED=false ENABLE_DEVICE_BOUND_SESSIONS=false ENABLE_BRACKETED_PROXY_URIS=false ENABLE_QUIC_PROXY_SUPPORT=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//net:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/net && echo '--flags POSIX_BYPASS_MMAP=\"false\" DISABLE_FILE_SUPPORT=\"true\" ENABLE_MDNS=\"false\" ENABLE_REPORTING=\"true\" ENABLE_WEBSOCKETS=\"false\" ENABLE_CLIENT_CERTIFICATES=\"true\" INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=\"false\" USE_KERBEROS=\"true\" USE_EXTERNAL_GSSAPI=\"false\" CHROME_ROOT_STORE_OPTIONAL=\"false\" CHROME_ROOT_STORE_ONLY=\"false\" CHROME_ROOT_STORE_SUPPORTED=\"false\" ENABLE_DEVICE_BOUND_SESSIONS=\"false\" ENABLE_BRACKETED_PROXY_URIS=\"false\" ENABLE_QUIC_PROXY_SUPPORT=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/net &&  " +
+         "echo '--flags POSIX_BYPASS_MMAP=false DISABLE_FILE_SUPPORT=true ENABLE_MDNS=false ENABLE_REPORTING=true ENABLE_WEBSOCKETS=false ENABLE_CLIENT_CERTIFICATES=true INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=false USE_KERBEROS=true USE_EXTERNAL_GSSAPI=false CHROME_ROOT_STORE_OPTIONAL=false CHROME_ROOT_STORE_ONLY=false CHROME_ROOT_STORE_SUPPORTED=false ENABLE_DEVICE_BOUND_SESSIONS=false ENABLE_BRACKETED_PROXY_URIS=false ENABLE_QUIC_PROXY_SUPPORT=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//net:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi; " +
+         "/dev/stdin " +
+         ";fi; " +
          "if [[ ( $$CC_ARCH == 'x86_64' && $$CC_OS == 'android' ) ]]; " +
          "then " +
-         "mkdir -p $(genDir)/net && echo '--flags POSIX_BYPASS_MMAP=\"true\" DISABLE_FILE_SUPPORT=\"true\" ENABLE_MDNS=\"false\" ENABLE_REPORTING=\"true\" ENABLE_WEBSOCKETS=\"false\" ENABLE_CLIENT_CERTIFICATES=\"true\" INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=\"false\" USE_KERBEROS=\"true\" USE_EXTERNAL_GSSAPI=\"false\" CHROME_ROOT_STORE_OPTIONAL=\"false\" CHROME_ROOT_STORE_ONLY=\"false\" CHROME_ROOT_STORE_SUPPORTED=\"false\" ENABLE_DEVICE_BOUND_SESSIONS=\"false\" ENABLE_BRACKETED_PROXY_URIS=\"false\" ENABLE_QUIC_PROXY_SUPPORT=\"false\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+         "mkdir -p $(genDir)/net &&  " +
+         "echo '--flags POSIX_BYPASS_MMAP=true DISABLE_FILE_SUPPORT=true ENABLE_MDNS=false ENABLE_REPORTING=true ENABLE_WEBSOCKETS=false ENABLE_CLIENT_CERTIFICATES=true INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST=false USE_KERBEROS=true USE_EXTERNAL_GSSAPI=false CHROME_ROOT_STORE_OPTIONAL=false CHROME_ROOT_STORE_ONLY=false CHROME_ROOT_STORE_SUPPORTED=false ENABLE_DEVICE_BOUND_SESSIONS=false ENABLE_BRACKETED_PROXY_URIS=false ENABLE_QUIC_PROXY_SUPPORT=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//net:buildflags " +
          "--gen-dir " +
          ". " +
          "--definitions " +
-         "/dev/stdin; " +
-         "fi;",
+         "/dev/stdin " +
+         ";fi;",
     host_cross_supported: false,
     out: [
         "net/net_buildflags.h",
@@ -11240,9 +17440,11 @@
 // GN: //net:cronet_buildflags
 cc_genrule {
     name: "tot_cronet_net_cronet_buildflags",
-    cmd: "mkdir -p $(genDir)/net/base && echo '--flags CRONET_BUILD=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/net/base &&  " +
+         "echo '--flags CRONET_BUILD=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//net:cronet_buildflags " +
          "--gen-dir " +
@@ -11267,9 +17469,11 @@
 // GN: //net:cronet_buildflags__testing
 cc_genrule {
     name: "tot_cronet_net_cronet_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/net/base && echo '--flags CRONET_BUILD=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/net/base &&  " +
+         "echo '--flags CRONET_BUILD=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//net:cronet_buildflags " +
          "--gen-dir " +
@@ -11291,37 +17495,22 @@
     ],
 }
 
-// GN: //net/http:transport_security_state_unittest_data__testing
+// GN: //net/http:transport_security_state_unittest_data__testing_0
 cc_genrule {
-    name: "tot_cronet_net_http_transport_security_state_unittest_data__testing",
+    name: "tot_cronet_net_http_transport_security_state_unittest_data__testing_0",
     tools: [
         "tot_cronet_net_tools_transport_security_state_generator_transport_security_state_generator__testing",
     ],
-    cmd: "mkdir -p $(genDir)/net/http && $(location tot_cronet_net_tools_transport_security_state_generator_transport_security_state_generator__testing) " +
-         "$(location net/http/transport_security_state_static_unittest1.json) " +
-         "$(location net/http/transport_security_state_static_unittest1_pins.json) " +
-         "$(location net/http/transport_security_state_static_unittest.pins) " +
-         "$(location net/http/transport_security_state_static_unittest.template) " +
-         "$(location net/http/transport_security_state_static_unittest1.h) " +
-         "&& " +
-         "$(location tot_cronet_net_tools_transport_security_state_generator_transport_security_state_generator__testing) " +
-         "$(location net/http/transport_security_state_static_unittest2.json) " +
-         "$(location net/http/transport_security_state_static_unittest2_pins.json) " +
-         "$(location net/http/transport_security_state_static_unittest.pins) " +
-         "$(location net/http/transport_security_state_static_unittest.template) " +
-         "$(location net/http/transport_security_state_static_unittest2.h) " +
-         "&& " +
-         "$(location tot_cronet_net_tools_transport_security_state_generator_transport_security_state_generator__testing) " +
-         "$(location net/http/transport_security_state_static_unittest3.json) " +
-         "$(location net/http/transport_security_state_static_unittest3_pins.json) " +
-         "$(location net/http/transport_security_state_static_unittest.pins) " +
-         "$(location net/http/transport_security_state_static_unittest.template) " +
-         "$(location net/http/transport_security_state_static_unittest3.h)",
+    cmd: "mkdir -p $(genDir)/net/http &&  " +
+         "'$(location tot_cronet_net_tools_transport_security_state_generator_transport_security_state_generator__testing)' " +
+         "'$(location net/http/transport_security_state_static_unittest1.json)' " +
+         "'$(location net/http/transport_security_state_static_unittest1_pins.json)' " +
+         "'$(location net/http/transport_security_state_static_unittest.pins)' " +
+         "'$(location net/http/transport_security_state_static_unittest.template)' " +
+         "'$(location net/http/transport_security_state_static_unittest1.h)'",
     host_cross_supported: false,
     out: [
         "net/http/transport_security_state_static_unittest1.h",
-        "net/http/transport_security_state_static_unittest2.h",
-        "net/http/transport_security_state_static_unittest3.h",
     ],
     tool_files: [
         "build/gn_run_binary.py",
@@ -11329,8 +17518,74 @@
         "net/http/transport_security_state_static_unittest.template",
         "net/http/transport_security_state_static_unittest1.json",
         "net/http/transport_security_state_static_unittest1_pins.json",
+        "net/http/transport_security_state_static_unittest2_pins.json",
+        "net/http/transport_security_state_static_unittest3_pins.json",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/http:transport_security_state_unittest_data__testing_1
+cc_genrule {
+    name: "tot_cronet_net_http_transport_security_state_unittest_data__testing_1",
+    tools: [
+        "tot_cronet_net_tools_transport_security_state_generator_transport_security_state_generator__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/net/http &&  " +
+         "'$(location tot_cronet_net_tools_transport_security_state_generator_transport_security_state_generator__testing)' " +
+         "'$(location net/http/transport_security_state_static_unittest2.json)' " +
+         "'$(location net/http/transport_security_state_static_unittest2_pins.json)' " +
+         "'$(location net/http/transport_security_state_static_unittest.pins)' " +
+         "'$(location net/http/transport_security_state_static_unittest.template)' " +
+         "'$(location net/http/transport_security_state_static_unittest2.h)'",
+    host_cross_supported: false,
+    out: [
+        "net/http/transport_security_state_static_unittest2.h",
+    ],
+    tool_files: [
+        "build/gn_run_binary.py",
+        "net/http/transport_security_state_static_unittest.pins",
+        "net/http/transport_security_state_static_unittest.template",
+        "net/http/transport_security_state_static_unittest1_pins.json",
         "net/http/transport_security_state_static_unittest2.json",
         "net/http/transport_security_state_static_unittest2_pins.json",
+        "net/http/transport_security_state_static_unittest3_pins.json",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/http:transport_security_state_unittest_data__testing_2
+cc_genrule {
+    name: "tot_cronet_net_http_transport_security_state_unittest_data__testing_2",
+    tools: [
+        "tot_cronet_net_tools_transport_security_state_generator_transport_security_state_generator__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/net/http &&  " +
+         "'$(location tot_cronet_net_tools_transport_security_state_generator_transport_security_state_generator__testing)' " +
+         "'$(location net/http/transport_security_state_static_unittest3.json)' " +
+         "'$(location net/http/transport_security_state_static_unittest3_pins.json)' " +
+         "'$(location net/http/transport_security_state_static_unittest.pins)' " +
+         "'$(location net/http/transport_security_state_static_unittest.template)' " +
+         "'$(location net/http/transport_security_state_static_unittest3.h)'",
+    host_cross_supported: false,
+    out: [
+        "net/http/transport_security_state_static_unittest3.h",
+    ],
+    tool_files: [
+        "build/gn_run_binary.py",
+        "net/http/transport_security_state_static_unittest.pins",
+        "net/http/transport_security_state_static_unittest.template",
+        "net/http/transport_security_state_static_unittest1_pins.json",
+        "net/http/transport_security_state_static_unittest2_pins.json",
         "net/http/transport_security_state_static_unittest3.json",
         "net/http/transport_security_state_static_unittest3_pins.json",
     ],
@@ -11348,12 +17603,13 @@
     tools: [
         "tot_cronet_net_tools_transport_security_state_generator_transport_security_state_generator__testing",
     ],
-    cmd: "mkdir -p $(genDir)/net/http && $(location tot_cronet_net_tools_transport_security_state_generator_transport_security_state_generator__testing) " +
-         "$(location net/http/transport_security_state_static_unittest_default.json) " +
-         "$(location net/http/transport_security_state_static_unittest_default_pins.json) " +
-         "$(location net/http/transport_security_state_static_unittest_default.pins) " +
-         "$(location net/http/transport_security_state_static_unittest.template) " +
-         "$(location net/http/transport_security_state_static_unittest_default.h)",
+    cmd: "mkdir -p $(genDir)/net/http &&  " +
+         "'$(location tot_cronet_net_tools_transport_security_state_generator_transport_security_state_generator__testing)' " +
+         "'$(location net/http/transport_security_state_static_unittest_default.json)' " +
+         "'$(location net/http/transport_security_state_static_unittest_default_pins.json)' " +
+         "'$(location net/http/transport_security_state_static_unittest_default.pins)' " +
+         "'$(location net/http/transport_security_state_static_unittest.template)' " +
+         "'$(location net/http/transport_security_state_static_unittest_default.h)'",
     host_cross_supported: false,
     out: [
         "net/http/transport_security_state_static_unittest_default.h",
@@ -11373,6 +17629,112 @@
     ],
 }
 
+// GN: //net:isolation_info_proto_gen
+cc_genrule {
+    name: "tot_cronet_net_isolation_info_proto_gen",
+    srcs: [
+        "net/base/isolation_info.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/base " +
+         "--cpp_out=lite=true:$(genDir)/net/base/ " +
+         "external/cronet/tot/net/base/isolation_info.proto",
+    host_cross_supported: false,
+    out: [
+        "net/base/isolation_info.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net:isolation_info_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_net_isolation_info_proto_gen__testing",
+    srcs: [
+        "net/base/isolation_info.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/base " +
+         "--cpp_out=lite=true:$(genDir)/net/base/ " +
+         "external/cronet/tot/net/base/isolation_info.proto",
+    host_cross_supported: false,
+    out: [
+        "net/base/isolation_info.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net:isolation_info_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_net_isolation_info_proto_gen__testing_headers",
+    srcs: [
+        "net/base/isolation_info.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/base " +
+         "--cpp_out=lite=true:$(genDir)/net/base/ " +
+         "external/cronet/tot/net/base/isolation_info.proto",
+    out: [
+        "net/base/isolation_info.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "net/base",
+        "protos",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
+// GN: //net:isolation_info_proto_gen
+cc_genrule {
+    name: "tot_cronet_net_isolation_info_proto_gen_headers",
+    srcs: [
+        "net/base/isolation_info.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/base " +
+         "--cpp_out=lite=true:$(genDir)/net/base/ " +
+         "external/cronet/tot/net/base/isolation_info.proto",
+    out: [
+        "net/base/isolation_info.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "net/base",
+        "protos",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
 // GN: //net:net_jni_headers__action
 cc_genrule {
     name: "tot_cronet_net_net_jni_headers__action",
@@ -11392,15 +17754,17 @@
         "net/android/java/src/org/chromium/net/X509Util.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/net/net_jni_headers &&  " +
-         "mkdir -p $(genDir)/net && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/net &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/net/net_jni_headers " +
+         "'$(genDir)/net/net_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/net/net_jni_headers.srcjar " +
+         "'$(genDir)/net/net_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/net/net_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/net/net_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "AndroidCertVerifyResult_jni.h " +
@@ -11429,31 +17793,31 @@
          "--output-name " +
          "X509Util_jni.h " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidCertVerifyResult.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidCertVerifyResult.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidKeyStore.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidKeyStore.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidNetworkLibrary.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidNetworkLibrary.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidTrafficStats.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidTrafficStats.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/DnsStatus.java) " +
+         "'$(location net/android/java/src/org/chromium/net/DnsStatus.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/GURLUtils.java) " +
+         "'$(location net/android/java/src/org/chromium/net/GURLUtils.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/HttpNegotiateAuthenticator.java) " +
+         "'$(location net/android/java/src/org/chromium/net/HttpNegotiateAuthenticator.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/HttpUtil.java) " +
+         "'$(location net/android/java/src/org/chromium/net/HttpUtil.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/NetStringUtil.java) " +
+         "'$(location net/android/java/src/org/chromium/net/NetStringUtil.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/NetworkActiveNotifier.java) " +
+         "'$(location net/android/java/src/org/chromium/net/NetworkActiveNotifier.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/NetworkChangeNotifier.java) " +
+         "'$(location net/android/java/src/org/chromium/net/NetworkChangeNotifier.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/ProxyChangeListener.java) " +
+         "'$(location net/android/java/src/org/chromium/net/ProxyChangeListener.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/X509Util.java) " +
+         "'$(location net/android/java/src/org/chromium/net/X509Util.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
@@ -11472,6 +17836,7 @@
         "net/net_jni_headers/NetworkChangeNotifier_jni.h",
         "net/net_jni_headers/ProxyChangeListener_jni.h",
         "net/net_jni_headers/X509Util_jni.h",
+        "net/net_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -11519,15 +17884,17 @@
         "net/android/java/src/org/chromium/net/X509Util.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/net/net_jni_headers &&  " +
-         "mkdir -p $(genDir)/net && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/net &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/net/net_jni_headers " +
+         "'$(genDir)/net/net_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/net/net_jni_headers.srcjar " +
+         "'$(genDir)/net/net_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/net/net_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/net/net_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "AndroidCertVerifyResult_jni.h " +
@@ -11556,31 +17923,31 @@
          "--output-name " +
          "X509Util_jni.h " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidCertVerifyResult.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidCertVerifyResult.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidKeyStore.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidKeyStore.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidNetworkLibrary.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidNetworkLibrary.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidTrafficStats.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidTrafficStats.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/DnsStatus.java) " +
+         "'$(location net/android/java/src/org/chromium/net/DnsStatus.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/GURLUtils.java) " +
+         "'$(location net/android/java/src/org/chromium/net/GURLUtils.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/HttpNegotiateAuthenticator.java) " +
+         "'$(location net/android/java/src/org/chromium/net/HttpNegotiateAuthenticator.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/HttpUtil.java) " +
+         "'$(location net/android/java/src/org/chromium/net/HttpUtil.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/NetStringUtil.java) " +
+         "'$(location net/android/java/src/org/chromium/net/NetStringUtil.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/NetworkActiveNotifier.java) " +
+         "'$(location net/android/java/src/org/chromium/net/NetworkActiveNotifier.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/NetworkChangeNotifier.java) " +
+         "'$(location net/android/java/src/org/chromium/net/NetworkChangeNotifier.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/ProxyChangeListener.java) " +
+         "'$(location net/android/java/src/org/chromium/net/ProxyChangeListener.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/X509Util.java) " +
+         "'$(location net/android/java/src/org/chromium/net/X509Util.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     out: [
@@ -11598,6 +17965,7 @@
         "net/net_jni_headers/NetworkChangeNotifier_jni.h",
         "net/net_jni_headers/ProxyChangeListener_jni.h",
         "net/net_jni_headers/X509Util_jni.h",
+        "net/net_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -11623,6 +17991,18 @@
     ],
 }
 
+// GN: //net:net_jni_headers__action
+java_genrule {
+    name: "tot_cronet_net_net_jni_headers__action__java_proxy_only",
+    srcs: [
+        ":tot_cronet_net_net_jni_headers__action__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "net_jni_headers.srcjar",
+    ],
+}
+
 // GN: //net:net_jni_headers__action__testing
 cc_genrule {
     name: "tot_cronet_net_net_jni_headers__action__testing",
@@ -11642,15 +18022,17 @@
         "net/android/java/src/org/chromium/net/X509Util.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/net/net_jni_headers &&  " +
-         "mkdir -p $(genDir)/net && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/net &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/net/net_jni_headers " +
+         "'$(genDir)/net/net_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/net/net_jni_headers.srcjar " +
+         "'$(genDir)/net/net_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/net/net_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/net/net_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "AndroidCertVerifyResult_jni.h " +
@@ -11679,31 +18061,31 @@
          "--output-name " +
          "X509Util_jni.h " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidCertVerifyResult.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidCertVerifyResult.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidKeyStore.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidKeyStore.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidNetworkLibrary.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidNetworkLibrary.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidTrafficStats.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidTrafficStats.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/DnsStatus.java) " +
+         "'$(location net/android/java/src/org/chromium/net/DnsStatus.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/GURLUtils.java) " +
+         "'$(location net/android/java/src/org/chromium/net/GURLUtils.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/HttpNegotiateAuthenticator.java) " +
+         "'$(location net/android/java/src/org/chromium/net/HttpNegotiateAuthenticator.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/HttpUtil.java) " +
+         "'$(location net/android/java/src/org/chromium/net/HttpUtil.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/NetStringUtil.java) " +
+         "'$(location net/android/java/src/org/chromium/net/NetStringUtil.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/NetworkActiveNotifier.java) " +
+         "'$(location net/android/java/src/org/chromium/net/NetworkActiveNotifier.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/NetworkChangeNotifier.java) " +
+         "'$(location net/android/java/src/org/chromium/net/NetworkChangeNotifier.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/ProxyChangeListener.java) " +
+         "'$(location net/android/java/src/org/chromium/net/ProxyChangeListener.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/X509Util.java)",
+         "'$(location net/android/java/src/org/chromium/net/X509Util.java)'",
     host_cross_supported: false,
     out: [
         "net/net_jni_headers.srcjar",
@@ -11720,6 +18102,7 @@
         "net/net_jni_headers/NetworkChangeNotifier_jni.h",
         "net/net_jni_headers/ProxyChangeListener_jni.h",
         "net/net_jni_headers/X509Util_jni.h",
+        "net/net_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -11767,15 +18150,17 @@
         "net/android/java/src/org/chromium/net/X509Util.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/net/net_jni_headers &&  " +
-         "mkdir -p $(genDir)/net && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/net &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/net/net_jni_headers " +
+         "'$(genDir)/net/net_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/net/net_jni_headers.srcjar " +
+         "'$(genDir)/net/net_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/net/net_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/net/net_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "AndroidCertVerifyResult_jni.h " +
@@ -11804,31 +18189,31 @@
          "--output-name " +
          "X509Util_jni.h " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidCertVerifyResult.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidCertVerifyResult.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidKeyStore.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidKeyStore.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidNetworkLibrary.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidNetworkLibrary.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/AndroidTrafficStats.java) " +
+         "'$(location net/android/java/src/org/chromium/net/AndroidTrafficStats.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/DnsStatus.java) " +
+         "'$(location net/android/java/src/org/chromium/net/DnsStatus.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/GURLUtils.java) " +
+         "'$(location net/android/java/src/org/chromium/net/GURLUtils.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/HttpNegotiateAuthenticator.java) " +
+         "'$(location net/android/java/src/org/chromium/net/HttpNegotiateAuthenticator.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/HttpUtil.java) " +
+         "'$(location net/android/java/src/org/chromium/net/HttpUtil.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/NetStringUtil.java) " +
+         "'$(location net/android/java/src/org/chromium/net/NetStringUtil.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/NetworkActiveNotifier.java) " +
+         "'$(location net/android/java/src/org/chromium/net/NetworkActiveNotifier.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/NetworkChangeNotifier.java) " +
+         "'$(location net/android/java/src/org/chromium/net/NetworkChangeNotifier.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/ProxyChangeListener.java) " +
+         "'$(location net/android/java/src/org/chromium/net/ProxyChangeListener.java)' " +
          "--input-file " +
-         "$(location net/android/java/src/org/chromium/net/X509Util.java)",
+         "'$(location net/android/java/src/org/chromium/net/X509Util.java)'",
     out: [
         "net/net_jni_headers.srcjar",
         "net/net_jni_headers/AndroidCertVerifyResult_jni.h",
@@ -11844,6 +18229,7 @@
         "net/net_jni_headers/NetworkChangeNotifier_jni.h",
         "net/net_jni_headers/ProxyChangeListener_jni.h",
         "net/net_jni_headers/X509Util_jni.h",
+        "net/net_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -11869,6 +18255,124 @@
     ],
 }
 
+// GN: //net:net_jni_headers__action__testing
+java_genrule {
+    name: "tot_cronet_net_net_jni_headers__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_net_net_jni_headers__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "net_jni_headers.srcjar",
+    ],
+}
+
+// GN: //net:net_nqe_proto_gen
+cc_genrule {
+    name: "tot_cronet_net_net_nqe_proto_gen",
+    srcs: [
+        "net/nqe/proto/network_id_proto.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/nqe/proto " +
+         "--cpp_out=lite=true:$(genDir)/net/nqe/proto/ " +
+         "external/cronet/tot/net/nqe/proto/network_id_proto.proto",
+    host_cross_supported: false,
+    out: [
+        "net/nqe/proto/network_id_proto.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net:net_nqe_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_net_net_nqe_proto_gen__testing",
+    srcs: [
+        "net/nqe/proto/network_id_proto.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/nqe/proto " +
+         "--cpp_out=lite=true:$(genDir)/net/nqe/proto/ " +
+         "external/cronet/tot/net/nqe/proto/network_id_proto.proto",
+    host_cross_supported: false,
+    out: [
+        "net/nqe/proto/network_id_proto.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net:net_nqe_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_net_net_nqe_proto_gen__testing_headers",
+    srcs: [
+        "net/nqe/proto/network_id_proto.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/nqe/proto " +
+         "--cpp_out=lite=true:$(genDir)/net/nqe/proto/ " +
+         "external/cronet/tot/net/nqe/proto/network_id_proto.proto",
+    out: [
+        "net/nqe/proto/network_id_proto.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "net/nqe/proto",
+        "protos",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
+// GN: //net:net_nqe_proto_gen
+cc_genrule {
+    name: "tot_cronet_net_net_nqe_proto_gen_headers",
+    srcs: [
+        "net/nqe/proto/network_id_proto.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/nqe/proto " +
+         "--cpp_out=lite=true:$(genDir)/net/nqe/proto/ " +
+         "external/cronet/tot/net/nqe/proto/network_id_proto.proto",
+    out: [
+        "net/nqe/proto/network_id_proto.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "net/nqe/proto",
+        "protos",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
 // GN: //net/third_party/quiche:blind_sign_auth_proto_gen__testing
 cc_genrule {
     name: "tot_cronet_net_third_party_quiche_blind_sign_auth_proto_gen__testing",
@@ -11883,11 +18387,24 @@
         "net/third_party/quiche/src/quiche/blind_sign_auth/proto/public_metadata.proto",
         "net/third_party/quiche/src/quiche/blind_sign_auth/proto/spend_token_data.proto",
         "third_party/anonymous_tokens/src/anonymous_tokens/proto/anonymous_tokens.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
     ],
     tools: [
         "tot_cronet_third_party_protobuf_protoc",
     ],
-    cmd: "$(location tot_cronet_third_party_protobuf_protoc) --proto_path=external/cronet/tot/net/third_party/quiche/src --proto_path=external/cronet/tot/third_party/anonymous_tokens/src/ --cpp_out=lite=true:$(genDir)/net/third_party/quiche/src/ $(in)",
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/third_party/quiche/src " +
+         "--proto_path=external/cronet/tot/third_party/anonymous_tokens/src/ " +
+         "--cpp_out=lite=true:$(genDir)/net/third_party/quiche/src/ " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/any.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/attestation.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/auth_and_sign.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/blind_sign_auth_options.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/get_initial_data.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/key_services.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/proxy_layer.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/public_metadata.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/spend_token_data.proto",
     host_cross_supported: false,
     out: [
         "net/third_party/quiche/src/quiche/blind_sign_auth/proto/any.pb.cc",
@@ -11922,11 +18439,24 @@
         "net/third_party/quiche/src/quiche/blind_sign_auth/proto/public_metadata.proto",
         "net/third_party/quiche/src/quiche/blind_sign_auth/proto/spend_token_data.proto",
         "third_party/anonymous_tokens/src/anonymous_tokens/proto/anonymous_tokens.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
     ],
     tools: [
         "tot_cronet_third_party_protobuf_protoc",
     ],
-    cmd: "$(location tot_cronet_third_party_protobuf_protoc) --proto_path=external/cronet/tot/net/third_party/quiche/src --proto_path=external/cronet/tot/third_party/anonymous_tokens/src/ --cpp_out=lite=true:$(genDir)/net/third_party/quiche/src/ $(in)",
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/third_party/quiche/src " +
+         "--proto_path=external/cronet/tot/third_party/anonymous_tokens/src/ " +
+         "--cpp_out=lite=true:$(genDir)/net/third_party/quiche/src/ " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/any.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/attestation.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/auth_and_sign.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/blind_sign_auth_options.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/get_initial_data.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/key_services.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/proxy_layer.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/public_metadata.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/blind_sign_auth/proto/spend_token_data.proto",
     out: [
         "net/third_party/quiche/src/quiche/blind_sign_auth/proto/any.pb.h",
         "net/third_party/quiche/src/quiche/blind_sign_auth/proto/attestation.pb.h",
@@ -11948,6 +18478,308 @@
     ],
 }
 
+// GN: //net/third_party/quiche:net_quic_proto_gen
+cc_genrule {
+    name: "tot_cronet_net_third_party_quiche_net_quic_proto_gen",
+    srcs: [
+        "net/third_party/quiche/src/quiche/quic/core/proto/cached_network_parameters.proto",
+        "net/third_party/quiche/src/quiche/quic/core/proto/crypto_server_config.proto",
+        "net/third_party/quiche/src/quiche/quic/core/proto/source_address_token.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/third_party/quiche/src " +
+         "--cpp_out=lite=true:$(genDir)/net/third_party/quiche/src/ " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/core/proto/cached_network_parameters.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/core/proto/crypto_server_config.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/core/proto/source_address_token.proto",
+    host_cross_supported: false,
+    out: [
+        "net/third_party/quiche/src/quiche/quic/core/proto/cached_network_parameters.pb.cc",
+        "net/third_party/quiche/src/quiche/quic/core/proto/crypto_server_config.pb.cc",
+        "net/third_party/quiche/src/quiche/quic/core/proto/source_address_token.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/third_party/quiche:net_quic_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_net_third_party_quiche_net_quic_proto_gen__testing",
+    srcs: [
+        "net/third_party/quiche/src/quiche/quic/core/proto/cached_network_parameters.proto",
+        "net/third_party/quiche/src/quiche/quic/core/proto/crypto_server_config.proto",
+        "net/third_party/quiche/src/quiche/quic/core/proto/source_address_token.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/third_party/quiche/src " +
+         "--cpp_out=lite=true:$(genDir)/net/third_party/quiche/src/ " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/core/proto/cached_network_parameters.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/core/proto/crypto_server_config.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/core/proto/source_address_token.proto",
+    host_cross_supported: false,
+    out: [
+        "net/third_party/quiche/src/quiche/quic/core/proto/cached_network_parameters.pb.cc",
+        "net/third_party/quiche/src/quiche/quic/core/proto/crypto_server_config.pb.cc",
+        "net/third_party/quiche/src/quiche/quic/core/proto/source_address_token.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/third_party/quiche:net_quic_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_net_third_party_quiche_net_quic_proto_gen__testing_headers",
+    srcs: [
+        "net/third_party/quiche/src/quiche/quic/core/proto/cached_network_parameters.proto",
+        "net/third_party/quiche/src/quiche/quic/core/proto/crypto_server_config.proto",
+        "net/third_party/quiche/src/quiche/quic/core/proto/source_address_token.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/third_party/quiche/src " +
+         "--cpp_out=lite=true:$(genDir)/net/third_party/quiche/src/ " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/core/proto/cached_network_parameters.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/core/proto/crypto_server_config.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/core/proto/source_address_token.proto",
+    out: [
+        "net/third_party/quiche/src/quiche/quic/core/proto/cached_network_parameters.pb.h",
+        "net/third_party/quiche/src/quiche/quic/core/proto/crypto_server_config.pb.h",
+        "net/third_party/quiche/src/quiche/quic/core/proto/source_address_token.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "net/third_party/quiche/src",
+        "protos",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
+// GN: //net/third_party/quiche:net_quic_proto_gen
+cc_genrule {
+    name: "tot_cronet_net_third_party_quiche_net_quic_proto_gen_headers",
+    srcs: [
+        "net/third_party/quiche/src/quiche/quic/core/proto/cached_network_parameters.proto",
+        "net/third_party/quiche/src/quiche/quic/core/proto/crypto_server_config.proto",
+        "net/third_party/quiche/src/quiche/quic/core/proto/source_address_token.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/third_party/quiche/src " +
+         "--cpp_out=lite=true:$(genDir)/net/third_party/quiche/src/ " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/core/proto/cached_network_parameters.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/core/proto/crypto_server_config.proto " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/core/proto/source_address_token.proto",
+    out: [
+        "net/third_party/quiche/src/quiche/quic/core/proto/cached_network_parameters.pb.h",
+        "net/third_party/quiche/src/quiche/quic/core/proto/crypto_server_config.pb.h",
+        "net/third_party/quiche/src/quiche/quic/core/proto/source_address_token.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "net/third_party/quiche/src",
+        "protos",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
+// GN: //net/third_party/quiche:net_quic_test_tools_proto_gen
+cc_genrule {
+    name: "tot_cronet_net_third_party_quiche_net_quic_test_tools_proto_gen",
+    srcs: [
+        "net/third_party/quiche/src/quiche/quic/test_tools/send_algorithm_test_result.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/third_party/quiche/src/quiche/quic/test_tools " +
+         "--cpp_out=lite=true:$(genDir)/net/third_party/quiche/src/quiche/quic/test_tools/ " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/test_tools/send_algorithm_test_result.proto",
+    host_cross_supported: false,
+    out: [
+        "net/third_party/quiche/src/quiche/quic/test_tools/send_algorithm_test_result.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/third_party/quiche:net_quic_test_tools_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_net_third_party_quiche_net_quic_test_tools_proto_gen__testing",
+    srcs: [
+        "net/third_party/quiche/src/quiche/quic/test_tools/send_algorithm_test_result.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/third_party/quiche/src/quiche/quic/test_tools " +
+         "--cpp_out=lite=true:$(genDir)/net/third_party/quiche/src/quiche/quic/test_tools/ " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/test_tools/send_algorithm_test_result.proto",
+    host_cross_supported: false,
+    out: [
+        "net/third_party/quiche/src/quiche/quic/test_tools/send_algorithm_test_result.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //net/third_party/quiche:net_quic_test_tools_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_net_third_party_quiche_net_quic_test_tools_proto_gen__testing_headers",
+    srcs: [
+        "net/third_party/quiche/src/quiche/quic/test_tools/send_algorithm_test_result.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/third_party/quiche/src/quiche/quic/test_tools " +
+         "--cpp_out=lite=true:$(genDir)/net/third_party/quiche/src/quiche/quic/test_tools/ " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/test_tools/send_algorithm_test_result.proto",
+    out: [
+        "net/third_party/quiche/src/quiche/quic/test_tools/send_algorithm_test_result.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "net/third_party/quiche/src",
+        "net/third_party/quiche/src/quiche/quic/test_tools",
+        "protos",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
+// GN: //net/third_party/quiche:net_quic_test_tools_proto_gen
+cc_genrule {
+    name: "tot_cronet_net_third_party_quiche_net_quic_test_tools_proto_gen_headers",
+    srcs: [
+        "net/third_party/quiche/src/quiche/quic/test_tools/send_algorithm_test_result.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/net/third_party/quiche/src/quiche/quic/test_tools " +
+         "--cpp_out=lite=true:$(genDir)/net/third_party/quiche/src/quiche/quic/test_tools/ " +
+         "external/cronet/tot/net/third_party/quiche/src/quiche/quic/test_tools/send_algorithm_test_result.proto",
+    out: [
+        "net/third_party/quiche/src/quiche/quic/test_tools/send_algorithm_test_result.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "net/third_party/quiche/src",
+        "net/third_party/quiche/src/quiche/quic/test_tools",
+        "protos",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
+// GN: //testing/android/instrumentation:test_runner_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_testing_android_instrumentation_test_runner_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_testing_android_instrumentation_test_runner_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/testing/android/instrumentation &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "testing/android/instrumentation/test_runner_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //testing/android/native_test:native_main_runner_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_testing_android_native_test_native_main_runner_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_testing_android_native_test_native_main_runner_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/testing/android/native_test &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "testing/android/native_test/native_main_runner_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //testing/android/native_test:native_main_runner_jni__action__testing
 cc_genrule {
     name: "tot_cronet_testing_android_native_test_native_main_runner_jni__action__testing",
@@ -11955,24 +18787,27 @@
         "testing/android/native_test/java/src/org/chromium/native_test/MainRunner.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/testing/android/native_test/native_main_runner_jni &&  " +
-         "mkdir -p $(genDir)/testing/android/native_test && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/testing/android/native_test &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/testing/android/native_test/native_main_runner_jni " +
+         "'$(genDir)/testing/android/native_test/native_main_runner_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/testing/android/native_test/native_main_runner_jni.srcjar " +
+         "'$(genDir)/testing/android/native_test/native_main_runner_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/testing/android/native_test/native_main_runner_jni_placeholder.srcjar " +
+         "'$(genDir)/testing/android/native_test/native_main_runner_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "MainRunner_jni.h " +
          "--input-file " +
-         "$(location testing/android/native_test/java/src/org/chromium/native_test/MainRunner.java)",
+         "'$(location testing/android/native_test/java/src/org/chromium/native_test/MainRunner.java)'",
     host_cross_supported: false,
     out: [
         "testing/android/native_test/native_main_runner_jni.srcjar",
         "testing/android/native_test/native_main_runner_jni/MainRunner_jni.h",
+        "testing/android/native_test/native_main_runner_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -12008,23 +18843,26 @@
         "testing/android/native_test/java/src/org/chromium/native_test/MainRunner.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/testing/android/native_test/native_main_runner_jni &&  " +
-         "mkdir -p $(genDir)/testing/android/native_test && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/testing/android/native_test &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/testing/android/native_test/native_main_runner_jni " +
+         "'$(genDir)/testing/android/native_test/native_main_runner_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/testing/android/native_test/native_main_runner_jni.srcjar " +
+         "'$(genDir)/testing/android/native_test/native_main_runner_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/testing/android/native_test/native_main_runner_jni_placeholder.srcjar " +
+         "'$(genDir)/testing/android/native_test/native_main_runner_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "MainRunner_jni.h " +
          "--input-file " +
-         "$(location testing/android/native_test/java/src/org/chromium/native_test/MainRunner.java)",
+         "'$(location testing/android/native_test/java/src/org/chromium/native_test/MainRunner.java)'",
     out: [
         "testing/android/native_test/native_main_runner_jni.srcjar",
         "testing/android/native_test/native_main_runner_jni/MainRunner_jni.h",
+        "testing/android/native_test/native_main_runner_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -12050,6 +18888,50 @@
     ],
 }
 
+// GN: //testing/android/native_test:native_main_runner_jni__action__testing
+java_genrule {
+    name: "tot_cronet_testing_android_native_test_native_main_runner_jni__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_testing_android_native_test_native_main_runner_jni__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "native_main_runner_jni.srcjar",
+    ],
+}
+
+// GN: //testing/android/native_test:native_test_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_testing_android_native_test_native_test_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_testing_android_native_test_native_test_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/testing/android/native_test &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "testing/android/native_test/native_test_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //testing/android/native_test:native_test_jni__action__testing
 cc_genrule {
     name: "tot_cronet_testing_android_native_test_native_test_jni__action__testing",
@@ -12057,24 +18939,27 @@
         "testing/android/native_test/java/src/org/chromium/native_test/NativeTest.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/testing/android/native_test/native_test_jni &&  " +
-         "mkdir -p $(genDir)/testing/android/native_test && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/testing/android/native_test &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/testing/android/native_test/native_test_jni " +
+         "'$(genDir)/testing/android/native_test/native_test_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/testing/android/native_test/native_test_jni.srcjar " +
+         "'$(genDir)/testing/android/native_test/native_test_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/testing/android/native_test/native_test_jni_placeholder.srcjar " +
+         "'$(genDir)/testing/android/native_test/native_test_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "NativeTest_jni.h " +
          "--input-file " +
-         "$(location testing/android/native_test/java/src/org/chromium/native_test/NativeTest.java)",
+         "'$(location testing/android/native_test/java/src/org/chromium/native_test/NativeTest.java)'",
     host_cross_supported: false,
     out: [
         "testing/android/native_test/native_test_jni.srcjar",
         "testing/android/native_test/native_test_jni/NativeTest_jni.h",
+        "testing/android/native_test/native_test_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -12110,23 +18995,26 @@
         "testing/android/native_test/java/src/org/chromium/native_test/NativeTest.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/testing/android/native_test/native_test_jni &&  " +
-         "mkdir -p $(genDir)/testing/android/native_test && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/testing/android/native_test &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/testing/android/native_test/native_test_jni " +
+         "'$(genDir)/testing/android/native_test/native_test_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/testing/android/native_test/native_test_jni.srcjar " +
+         "'$(genDir)/testing/android/native_test/native_test_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/testing/android/native_test/native_test_jni_placeholder.srcjar " +
+         "'$(genDir)/testing/android/native_test/native_test_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "NativeTest_jni.h " +
          "--input-file " +
-         "$(location testing/android/native_test/java/src/org/chromium/native_test/NativeTest.java)",
+         "'$(location testing/android/native_test/java/src/org/chromium/native_test/NativeTest.java)'",
     out: [
         "testing/android/native_test/native_test_jni.srcjar",
         "testing/android/native_test/native_test_jni/NativeTest_jni.h",
+        "testing/android/native_test/native_test_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -12152,6 +19040,50 @@
     ],
 }
 
+// GN: //testing/android/native_test:native_test_jni__action__testing
+java_genrule {
+    name: "tot_cronet_testing_android_native_test_native_test_jni__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_testing_android_native_test_native_test_jni__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "native_test_jni.srcjar",
+    ],
+}
+
+// GN: //testing/android/reporter:reporter_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_testing_android_reporter_reporter_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_testing_android_reporter_reporter_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/testing/android/reporter &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "testing/android/reporter/reporter_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //testing/gtest:gtest__testing
 cc_library_static {
     name: "tot_cronet_testing_gtest_gtest__testing",
@@ -12231,8 +19163,8 @@
     cflags: [
         "-DANDROID",
         "-DANDROID_NDK_VERSION_ROLL=r27_1",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DGTEST_API_=",
         "-DGTEST_HAS_ABSL",
@@ -12311,10 +19243,93 @@
     },
 }
 
+// GN: //testing/libfuzzer:confirm_fuzztest_init_buildflags__testing
+cc_genrule {
+    name: "tot_cronet_testing_libfuzzer_confirm_fuzztest_init_buildflags__testing",
+    cmd: "mkdir -p $(genDir)/testing/libfuzzer &&  " +
+         "echo '--flags REGISTER_FUZZTESTS_IN_TEST_SUITES=false' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
+         "--rulename " +
+         "//testing/libfuzzer:confirm_fuzztest_init_buildflags " +
+         "--gen-dir " +
+         ". " +
+         "--definitions " +
+         "/dev/stdin",
+    host_cross_supported: false,
+    out: [
+        "testing/libfuzzer/confirm_fuzztest_init_buildflags.h",
+    ],
+    tool_files: [
+        "build/write_buildflag_header.py",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //third_party/anonymous_tokens:anonymous_tokens_cc_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_third_party_anonymous_tokens_anonymous_tokens_cc_proto_gen__testing",
+    srcs: [
+        "third_party/anonymous_tokens/src/anonymous_tokens/proto/anonymous_tokens.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/third_party/anonymous_tokens/src " +
+         "--cpp_out=lite=true:$(genDir)/third_party/anonymous_tokens/src/ " +
+         "external/cronet/tot/third_party/anonymous_tokens/src/anonymous_tokens/proto/anonymous_tokens.proto",
+    host_cross_supported: false,
+    out: [
+        "third_party/anonymous_tokens/src/anonymous_tokens/proto/anonymous_tokens.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //third_party/anonymous_tokens:anonymous_tokens_cc_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_third_party_anonymous_tokens_anonymous_tokens_cc_proto_gen__testing_headers",
+    srcs: [
+        "third_party/anonymous_tokens/src/anonymous_tokens/proto/anonymous_tokens.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/third_party/anonymous_tokens/src " +
+         "--cpp_out=lite=true:$(genDir)/third_party/anonymous_tokens/src/ " +
+         "external/cronet/tot/third_party/anonymous_tokens/src/anonymous_tokens/proto/anonymous_tokens.proto",
+    out: [
+        "third_party/anonymous_tokens/src/anonymous_tokens/proto/anonymous_tokens.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "protos",
+        "third_party/anonymous_tokens/src",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
 // GN: //third_party/boringssl:boringssl__testing
 cc_library_static {
     name: "tot_cronet_third_party_boringssl_boringssl__testing",
     srcs: [
+        "third_party/boringssl/src/crypto/aes/aes.cc",
         "third_party/boringssl/src/crypto/asn1/a_bitstr.cc",
         "third_party/boringssl/src/crypto/asn1/a_bool.cc",
         "third_party/boringssl/src/crypto/asn1/a_d2i_fp.cc",
@@ -12355,8 +19370,9 @@
         "third_party/boringssl/src/crypto/bio/socket.cc",
         "third_party/boringssl/src/crypto/bio/socket_helper.cc",
         "third_party/boringssl/src/crypto/blake2/blake2.cc",
-        "third_party/boringssl/src/crypto/bn_extra/bn_asn1.cc",
-        "third_party/boringssl/src/crypto/bn_extra/convert.cc",
+        "third_party/boringssl/src/crypto/bn/bn_asn1.cc",
+        "third_party/boringssl/src/crypto/bn/convert.cc",
+        "third_party/boringssl/src/crypto/bn/exponentiation.cc",
         "third_party/boringssl/src/crypto/buf/buf.cc",
         "third_party/boringssl/src/crypto/bytestring/asn1_compat.cc",
         "third_party/boringssl/src/crypto/bytestring/ber.cc",
@@ -12364,17 +19380,18 @@
         "third_party/boringssl/src/crypto/bytestring/cbs.cc",
         "third_party/boringssl/src/crypto/bytestring/unicode.cc",
         "third_party/boringssl/src/crypto/chacha/chacha.cc",
-        "third_party/boringssl/src/crypto/cipher_extra/cipher_extra.cc",
-        "third_party/boringssl/src/crypto/cipher_extra/derive_key.cc",
-        "third_party/boringssl/src/crypto/cipher_extra/e_aesctrhmac.cc",
-        "third_party/boringssl/src/crypto/cipher_extra/e_aesgcmsiv.cc",
-        "third_party/boringssl/src/crypto/cipher_extra/e_chacha20poly1305.cc",
-        "third_party/boringssl/src/crypto/cipher_extra/e_des.cc",
-        "third_party/boringssl/src/crypto/cipher_extra/e_null.cc",
-        "third_party/boringssl/src/crypto/cipher_extra/e_rc2.cc",
-        "third_party/boringssl/src/crypto/cipher_extra/e_rc4.cc",
-        "third_party/boringssl/src/crypto/cipher_extra/e_tls.cc",
-        "third_party/boringssl/src/crypto/cipher_extra/tls_cbc.cc",
+        "third_party/boringssl/src/crypto/cipher/derive_key.cc",
+        "third_party/boringssl/src/crypto/cipher/e_aesctrhmac.cc",
+        "third_party/boringssl/src/crypto/cipher/e_aeseax.cc",
+        "third_party/boringssl/src/crypto/cipher/e_aesgcmsiv.cc",
+        "third_party/boringssl/src/crypto/cipher/e_chacha20poly1305.cc",
+        "third_party/boringssl/src/crypto/cipher/e_des.cc",
+        "third_party/boringssl/src/crypto/cipher/e_null.cc",
+        "third_party/boringssl/src/crypto/cipher/e_rc2.cc",
+        "third_party/boringssl/src/crypto/cipher/e_rc4.cc",
+        "third_party/boringssl/src/crypto/cipher/e_tls.cc",
+        "third_party/boringssl/src/crypto/cipher/get_cipher.cc",
+        "third_party/boringssl/src/crypto/cipher/tls_cbc.cc",
         "third_party/boringssl/src/crypto/conf/conf.cc",
         "third_party/boringssl/src/crypto/cpu_aarch64_apple.cc",
         "third_party/boringssl/src/crypto/cpu_aarch64_fuchsia.cc",
@@ -12390,16 +19407,16 @@
         "third_party/boringssl/src/crypto/curve25519/curve25519_64_adx.cc",
         "third_party/boringssl/src/crypto/curve25519/spake25519.cc",
         "third_party/boringssl/src/crypto/des/des.cc",
-        "third_party/boringssl/src/crypto/dh_extra/dh_asn1.cc",
-        "third_party/boringssl/src/crypto/dh_extra/params.cc",
-        "third_party/boringssl/src/crypto/digest_extra/digest_extra.cc",
+        "third_party/boringssl/src/crypto/dh/dh_asn1.cc",
+        "third_party/boringssl/src/crypto/dh/params.cc",
+        "third_party/boringssl/src/crypto/digest/digest_extra.cc",
         "third_party/boringssl/src/crypto/dsa/dsa.cc",
         "third_party/boringssl/src/crypto/dsa/dsa_asn1.cc",
-        "third_party/boringssl/src/crypto/ec_extra/ec_asn1.cc",
-        "third_party/boringssl/src/crypto/ec_extra/ec_derive.cc",
-        "third_party/boringssl/src/crypto/ec_extra/hash_to_curve.cc",
-        "third_party/boringssl/src/crypto/ecdh_extra/ecdh_extra.cc",
-        "third_party/boringssl/src/crypto/ecdsa_extra/ecdsa_asn1.cc",
+        "third_party/boringssl/src/crypto/ec/ec_asn1.cc",
+        "third_party/boringssl/src/crypto/ec/ec_derive.cc",
+        "third_party/boringssl/src/crypto/ec/hash_to_curve.cc",
+        "third_party/boringssl/src/crypto/ecdh/ecdh.cc",
+        "third_party/boringssl/src/crypto/ecdsa/ecdsa_asn1.cc",
         "third_party/boringssl/src/crypto/engine/engine.cc",
         "third_party/boringssl/src/crypto/err/err.cc",
         "third_party/boringssl/src/crypto/evp/evp.cc",
@@ -12426,7 +19443,6 @@
         "third_party/boringssl/src/crypto/fipsmodule/fips_shared_support.cc",
         "third_party/boringssl/src/crypto/hpke/hpke.cc",
         "third_party/boringssl/src/crypto/hrss/hrss.cc",
-        "third_party/boringssl/src/crypto/keccak/keccak.cc",
         "third_party/boringssl/src/crypto/kyber/kyber.cc",
         "third_party/boringssl/src/crypto/lhash/lhash.cc",
         "third_party/boringssl/src/crypto/md4/md4.cc",
@@ -12453,38 +19469,28 @@
         "third_party/boringssl/src/crypto/poly1305/poly1305_arm.cc",
         "third_party/boringssl/src/crypto/poly1305/poly1305_vec.cc",
         "third_party/boringssl/src/crypto/pool/pool.cc",
-        "third_party/boringssl/src/crypto/rand_extra/deterministic.cc",
-        "third_party/boringssl/src/crypto/rand_extra/fork_detect.cc",
-        "third_party/boringssl/src/crypto/rand_extra/forkunsafe.cc",
-        "third_party/boringssl/src/crypto/rand_extra/getentropy.cc",
-        "third_party/boringssl/src/crypto/rand_extra/ios.cc",
-        "third_party/boringssl/src/crypto/rand_extra/passive.cc",
-        "third_party/boringssl/src/crypto/rand_extra/rand_extra.cc",
-        "third_party/boringssl/src/crypto/rand_extra/trusty.cc",
-        "third_party/boringssl/src/crypto/rand_extra/urandom.cc",
-        "third_party/boringssl/src/crypto/rand_extra/windows.cc",
+        "third_party/boringssl/src/crypto/rand/deterministic.cc",
+        "third_party/boringssl/src/crypto/rand/fork_detect.cc",
+        "third_party/boringssl/src/crypto/rand/forkunsafe.cc",
+        "third_party/boringssl/src/crypto/rand/getentropy.cc",
+        "third_party/boringssl/src/crypto/rand/ios.cc",
+        "third_party/boringssl/src/crypto/rand/passive.cc",
+        "third_party/boringssl/src/crypto/rand/rand.cc",
+        "third_party/boringssl/src/crypto/rand/trusty.cc",
+        "third_party/boringssl/src/crypto/rand/urandom.cc",
+        "third_party/boringssl/src/crypto/rand/windows.cc",
         "third_party/boringssl/src/crypto/rc4/rc4.cc",
         "third_party/boringssl/src/crypto/refcount.cc",
-        "third_party/boringssl/src/crypto/rsa_extra/rsa_asn1.cc",
-        "third_party/boringssl/src/crypto/rsa_extra/rsa_crypt.cc",
-        "third_party/boringssl/src/crypto/rsa_extra/rsa_extra.cc",
-        "third_party/boringssl/src/crypto/rsa_extra/rsa_print.cc",
+        "third_party/boringssl/src/crypto/rsa/rsa_asn1.cc",
+        "third_party/boringssl/src/crypto/rsa/rsa_crypt.cc",
+        "third_party/boringssl/src/crypto/rsa/rsa_extra.cc",
+        "third_party/boringssl/src/crypto/rsa/rsa_print.cc",
         "third_party/boringssl/src/crypto/sha/sha1.cc",
         "third_party/boringssl/src/crypto/sha/sha256.cc",
         "third_party/boringssl/src/crypto/sha/sha512.cc",
         "third_party/boringssl/src/crypto/siphash/siphash.cc",
-        "third_party/boringssl/src/crypto/slhdsa/fors.cc",
-        "third_party/boringssl/src/crypto/slhdsa/merkle.cc",
         "third_party/boringssl/src/crypto/slhdsa/slhdsa.cc",
-        "third_party/boringssl/src/crypto/slhdsa/thash.cc",
-        "third_party/boringssl/src/crypto/slhdsa/wots.cc",
-        "third_party/boringssl/src/crypto/spx/spx.cc",
-        "third_party/boringssl/src/crypto/spx/spx_address.cc",
-        "third_party/boringssl/src/crypto/spx/spx_fors.cc",
-        "third_party/boringssl/src/crypto/spx/spx_merkle.cc",
-        "third_party/boringssl/src/crypto/spx/spx_thash.cc",
-        "third_party/boringssl/src/crypto/spx/spx_util.cc",
-        "third_party/boringssl/src/crypto/spx/spx_wots.cc",
+        "third_party/boringssl/src/crypto/spake2plus/spake2plus.cc",
         "third_party/boringssl/src/crypto/stack/stack.cc",
         "third_party/boringssl/src/crypto/thread.cc",
         "third_party/boringssl/src/crypto/thread_none.cc",
@@ -12579,7 +19585,6 @@
         "third_party/boringssl/src/pki/ip_util.cc",
         "third_party/boringssl/src/pki/name_constraints.cc",
         "third_party/boringssl/src/pki/ocsp.cc",
-        "third_party/boringssl/src/pki/ocsp_verify_result.cc",
         "third_party/boringssl/src/pki/parse_certificate.cc",
         "third_party/boringssl/src/pki/parse_name.cc",
         "third_party/boringssl/src/pki/parse_values.cc",
@@ -12645,8 +19650,8 @@
     ],
     cflags: [
         "-DBORINGSSL_IMPLEMENTATION",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DNDEBUG",
         "-DNVALGRIND",
@@ -12729,7 +19734,7 @@
         },
         host: {
             cflags: [
-                "-DCR_SYSROOT_KEY=20230611T210420Z-2",
+                "-DCR_SYSROOT_KEY=20250129T203412Z-1",
                 "-DNO_UNWIND_TABLES",
                 "-DUSE_AURA=1",
                 "-DUSE_OZONE=1",
@@ -12752,6 +19757,10 @@
         "third_party/boringssl/src/crypto/curve25519/asm/x25519-asm-arm.S",
         "third_party/boringssl/src/crypto/hrss/asm/poly_rq_mul.S",
         "third_party/boringssl/src/crypto/poly1305/poly1305_arm_asm.S",
+        "third_party/boringssl/src/gen/bcm/aes-gcm-avx10-x86_64-apple.S",
+        "third_party/boringssl/src/gen/bcm/aes-gcm-avx10-x86_64-linux.S",
+        "third_party/boringssl/src/gen/bcm/aes-gcm-avx2-x86_64-apple.S",
+        "third_party/boringssl/src/gen/bcm/aes-gcm-avx2-x86_64-linux.S",
         "third_party/boringssl/src/gen/bcm/aesni-gcm-x86_64-apple.S",
         "third_party/boringssl/src/gen/bcm/aesni-gcm-x86_64-linux.S",
         "third_party/boringssl/src/gen/bcm/aesni-x86-apple.S",
@@ -12875,8 +19884,8 @@
         "tot_cronet_cc_defaults",
     ],
     cflags: [
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DNDEBUG",
         "-DNVALGRIND",
@@ -12965,7 +19974,7 @@
         },
         host: {
             cflags: [
-                "-DCR_SYSROOT_KEY=20230611T210420Z-2",
+                "-DCR_SYSROOT_KEY=20250129T203412Z-1",
                 "-DNO_UNWIND_TABLES",
                 "-DUSE_AURA=1",
                 "-DUSE_OZONE=1",
@@ -12983,6 +19992,70 @@
     },
 }
 
+// GN: //third_party/jni_zero:gendeps_java__process_device
+java_genrule {
+    name: "tot_cronet_third_party_jni_zero_gendeps_java__process_device",
+    srcs: [
+        ":tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/third_party/jni_zero &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "third_party/jni_zero/gendeps_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //third_party/jni_zero:gendeps_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_third_party_jni_zero_gendeps_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/third_party/jni_zero &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "third_party/jni_zero/gendeps_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //third_party/jni_zero:generate_jni__action
 cc_genrule {
     name: "tot_cronet_third_party_jni_zero_generate_jni__action",
@@ -12991,24 +20064,26 @@
         "third_party/jni_zero/java/src/org/jni_zero/JniUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/third_party/jni_zero/generate_jni &&  " +
-         "mkdir -p $(genDir)/third_party/jni_zero && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/third_party/jni_zero &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/third_party/jni_zero/generate_jni " +
+         "'$(genDir)/third_party/jni_zero/generate_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/third_party/jni_zero/generate_jni.srcjar " +
+         "'$(genDir)/third_party/jni_zero/generate_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/third_party/jni_zero/generate_jni_placeholder.srcjar " +
+         "'$(genDir)/third_party/jni_zero/generate_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "JniInit_jni.h " +
          "--output-name " +
          "JniUtil_jni.h " +
          "--input-file " +
-         "$(location third_party/jni_zero/java/src/org/jni_zero/JniInit.java) " +
+         "'$(location third_party/jni_zero/java/src/org/jni_zero/JniInit.java)' " +
          "--input-file " +
-         "$(location third_party/jni_zero/java/src/org/jni_zero/JniUtil.java) " +
+         "'$(location third_party/jni_zero/java/src/org/jni_zero/JniUtil.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
@@ -13016,6 +20091,7 @@
         "third_party/jni_zero/generate_jni.srcjar",
         "third_party/jni_zero/generate_jni/JniInit_jni.h",
         "third_party/jni_zero/generate_jni/JniUtil_jni.h",
+        "third_party/jni_zero/generate_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -13052,30 +20128,33 @@
         "third_party/jni_zero/java/src/org/jni_zero/JniUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/third_party/jni_zero/generate_jni &&  " +
-         "mkdir -p $(genDir)/third_party/jni_zero && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/third_party/jni_zero &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/third_party/jni_zero/generate_jni " +
+         "'$(genDir)/third_party/jni_zero/generate_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/third_party/jni_zero/generate_jni.srcjar " +
+         "'$(genDir)/third_party/jni_zero/generate_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/third_party/jni_zero/generate_jni_placeholder.srcjar " +
+         "'$(genDir)/third_party/jni_zero/generate_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "JniInit_jni.h " +
          "--output-name " +
          "JniUtil_jni.h " +
          "--input-file " +
-         "$(location third_party/jni_zero/java/src/org/jni_zero/JniInit.java) " +
+         "'$(location third_party/jni_zero/java/src/org/jni_zero/JniInit.java)' " +
          "--input-file " +
-         "$(location third_party/jni_zero/java/src/org/jni_zero/JniUtil.java) " +
+         "'$(location third_party/jni_zero/java/src/org/jni_zero/JniUtil.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     out: [
         "third_party/jni_zero/generate_jni.srcjar",
         "third_party/jni_zero/generate_jni/JniInit_jni.h",
         "third_party/jni_zero/generate_jni/JniUtil_jni.h",
+        "third_party/jni_zero/generate_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -13109,29 +20188,32 @@
         "third_party/jni_zero/java/src/org/jni_zero/JniUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/third_party/jni_zero/generate_jni &&  " +
-         "mkdir -p $(genDir)/third_party/jni_zero && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/third_party/jni_zero &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/third_party/jni_zero/generate_jni " +
+         "'$(genDir)/third_party/jni_zero/generate_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/third_party/jni_zero/generate_jni.srcjar " +
+         "'$(genDir)/third_party/jni_zero/generate_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/third_party/jni_zero/generate_jni_placeholder.srcjar " +
+         "'$(genDir)/third_party/jni_zero/generate_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "JniInit_jni.h " +
          "--output-name " +
          "JniUtil_jni.h " +
          "--input-file " +
-         "$(location third_party/jni_zero/java/src/org/jni_zero/JniInit.java) " +
+         "'$(location third_party/jni_zero/java/src/org/jni_zero/JniInit.java)' " +
          "--input-file " +
-         "$(location third_party/jni_zero/java/src/org/jni_zero/JniUtil.java)",
+         "'$(location third_party/jni_zero/java/src/org/jni_zero/JniUtil.java)'",
     host_cross_supported: false,
     out: [
         "third_party/jni_zero/generate_jni.srcjar",
         "third_party/jni_zero/generate_jni/JniInit_jni.h",
         "third_party/jni_zero/generate_jni/JniUtil_jni.h",
+        "third_party/jni_zero/generate_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -13168,28 +20250,31 @@
         "third_party/jni_zero/java/src/org/jni_zero/JniUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/third_party/jni_zero/generate_jni &&  " +
-         "mkdir -p $(genDir)/third_party/jni_zero && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/third_party/jni_zero &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/third_party/jni_zero/generate_jni " +
+         "'$(genDir)/third_party/jni_zero/generate_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/third_party/jni_zero/generate_jni.srcjar " +
+         "'$(genDir)/third_party/jni_zero/generate_jni.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/third_party/jni_zero/generate_jni_placeholder.srcjar " +
+         "'$(genDir)/third_party/jni_zero/generate_jni_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "JniInit_jni.h " +
          "--output-name " +
          "JniUtil_jni.h " +
          "--input-file " +
-         "$(location third_party/jni_zero/java/src/org/jni_zero/JniInit.java) " +
+         "'$(location third_party/jni_zero/java/src/org/jni_zero/JniInit.java)' " +
          "--input-file " +
-         "$(location third_party/jni_zero/java/src/org/jni_zero/JniUtil.java)",
+         "'$(location third_party/jni_zero/java/src/org/jni_zero/JniUtil.java)'",
     out: [
         "third_party/jni_zero/generate_jni.srcjar",
         "third_party/jni_zero/generate_jni/JniInit_jni.h",
         "third_party/jni_zero/generate_jni/JniUtil_jni.h",
+        "third_party/jni_zero/generate_jni_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -13215,21 +20300,151 @@
     ],
 }
 
+// GN: //third_party/jni_zero:generate_jni_java__process_device
+java_genrule {
+    name: "tot_cronet_third_party_jni_zero_generate_jni_java__process_device",
+    srcs: [
+        ":tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/third_party/jni_zero &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "third_party/jni_zero/generate_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //third_party/jni_zero:generate_jni_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_third_party_jni_zero_generate_jni_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/third_party/jni_zero &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[]' " +
+         "--include-globs " +
+         "'[\"*Jni.class\", \"*Jni\\$$*.class\"]'",
+    out: [
+        "third_party/jni_zero/generate_jni_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //third_party/jni_zero:jni_zero_java__process_device
+java_genrule {
+    name: "tot_cronet_third_party_jni_zero_jni_zero_java__process_device",
+    srcs: [
+        ":tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/third_party/jni_zero &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "third_party/jni_zero/jni_zero_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //third_party/jni_zero:jni_zero_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_third_party_jni_zero_jni_zero_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/third_party/jni_zero &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "third_party/jni_zero/jni_zero_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //third_party/jni_zero:system_jni__action
 cc_genrule {
     name: "tot_cronet_third_party_jni_zero_system_jni__action",
     tools: [
         ":javap",
     ],
-    cmd: "mkdir -p $(genDir)/jni_headers/third_party/jni_zero/system_jni && $(location third_party/jni_zero/jni_zero.py) from-jar " +
+    cmd: "mkdir -p $(genDir)/jni_headers/third_party/jni_zero/system_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-jar " +
          "--output-dir " +
-         "$(genDir)/third_party/jni_zero/system_jni " +
+         "'$(genDir)/third_party/jni_zero/system_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--jar-file " +
-         "$(location :current_android_jar) " +
+         "'$(location :current_android_jar)' " +
          "--javap " +
-         "$(location :javap) " +
+         "'$(location :javap)' " +
          "--output-name " +
          "Arrays_jni.h " +
          "--output-name " +
@@ -13238,6 +20453,12 @@
          "List_jni.h " +
          "--output-name " +
          "Map_jni.h " +
+         "--output-name " +
+         "Integer_jni.h " +
+         "--output-name " +
+         "Long_jni.h " +
+         "--output-name " +
+         "Boolean_jni.h " +
          "--input-file " +
          "java/util/Arrays.class " +
          "--input-file " +
@@ -13245,12 +20466,21 @@
          "--input-file " +
          "java/util/List.class " +
          "--input-file " +
-         "java/util/Map.class",
+         "java/util/Map.class " +
+         "--input-file " +
+         "java/lang/Integer.class " +
+         "--input-file " +
+         "java/lang/Long.class " +
+         "--input-file " +
+         "java/lang/Boolean.class",
     host_cross_supported: false,
     out: [
         "third_party/jni_zero/system_jni/Arrays_jni.h",
+        "third_party/jni_zero/system_jni/Boolean_jni.h",
         "third_party/jni_zero/system_jni/Collection_jni.h",
+        "third_party/jni_zero/system_jni/Integer_jni.h",
         "third_party/jni_zero/system_jni/List_jni.h",
+        "third_party/jni_zero/system_jni/Long_jni.h",
         "third_party/jni_zero/system_jni/Map_jni.h",
     ],
     tool_files: [
@@ -13287,15 +20517,17 @@
     tools: [
         ":javap",
     ],
-    cmd: "mkdir -p $(genDir)/jni_headers/third_party/jni_zero/system_jni && $(location third_party/jni_zero/jni_zero.py) from-jar " +
+    cmd: "mkdir -p $(genDir)/jni_headers/third_party/jni_zero/system_jni &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-jar " +
          "--output-dir " +
-         "$(genDir)/third_party/jni_zero/system_jni " +
+         "'$(genDir)/third_party/jni_zero/system_jni' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--jar-file " +
-         "$(location :current_android_jar) " +
+         "'$(location :current_android_jar)' " +
          "--javap " +
-         "$(location :javap) " +
+         "'$(location :javap)' " +
          "--output-name " +
          "Arrays_jni.h " +
          "--output-name " +
@@ -13304,6 +20536,12 @@
          "List_jni.h " +
          "--output-name " +
          "Map_jni.h " +
+         "--output-name " +
+         "Integer_jni.h " +
+         "--output-name " +
+         "Long_jni.h " +
+         "--output-name " +
+         "Boolean_jni.h " +
          "--input-file " +
          "java/util/Arrays.class " +
          "--input-file " +
@@ -13311,12 +20549,21 @@
          "--input-file " +
          "java/util/List.class " +
          "--input-file " +
-         "java/util/Map.class",
+         "java/util/Map.class " +
+         "--input-file " +
+         "java/lang/Integer.class " +
+         "--input-file " +
+         "java/lang/Long.class " +
+         "--input-file " +
+         "java/lang/Boolean.class",
     host_cross_supported: false,
     out: [
         "third_party/jni_zero/system_jni/Arrays_jni.h",
+        "third_party/jni_zero/system_jni/Boolean_jni.h",
         "third_party/jni_zero/system_jni/Collection_jni.h",
+        "third_party/jni_zero/system_jni/Integer_jni.h",
         "third_party/jni_zero/system_jni/List_jni.h",
+        "third_party/jni_zero/system_jni/Long_jni.h",
         "third_party/jni_zero/system_jni/Map_jni.h",
     ],
     tool_files: [
@@ -13347,6 +20594,546 @@
     ],
 }
 
+// GN: //third_party/metrics_proto:metrics_proto_gen
+cc_genrule {
+    name: "tot_cronet_third_party_metrics_proto_metrics_proto_gen",
+    srcs: [
+        "third_party/metrics_proto/call_stack_profile.proto",
+        "third_party/metrics_proto/cast_logs.proto",
+        "third_party/metrics_proto/chrome_os_app_list_launch_event.proto",
+        "third_party/metrics_proto/chrome_user_metrics_extension.proto",
+        "third_party/metrics_proto/custom_tab_session.proto",
+        "third_party/metrics_proto/device_state.proto",
+        "third_party/metrics_proto/dwa/deidentified_web_analytics.proto",
+        "third_party/metrics_proto/execution_context.proto",
+        "third_party/metrics_proto/extension_install.proto",
+        "third_party/metrics_proto/histogram_event.proto",
+        "third_party/metrics_proto/omnibox_event.proto",
+        "third_party/metrics_proto/omnibox_focus_type.proto",
+        "third_party/metrics_proto/omnibox_input_type.proto",
+        "third_party/metrics_proto/omnibox_scoring_signals.proto",
+        "third_party/metrics_proto/perf_data.proto",
+        "third_party/metrics_proto/perf_stat.proto",
+        "third_party/metrics_proto/printer_event.proto",
+        "third_party/metrics_proto/reporting_info.proto",
+        "third_party/metrics_proto/sampled_profile.proto",
+        "third_party/metrics_proto/structured_data.proto",
+        "third_party/metrics_proto/system_profile.proto",
+        "third_party/metrics_proto/trace_log.proto",
+        "third_party/metrics_proto/translate_event.proto",
+        "third_party/metrics_proto/ukm/aggregate.proto",
+        "third_party/metrics_proto/ukm/entry.proto",
+        "third_party/metrics_proto/ukm/report.proto",
+        "third_party/metrics_proto/ukm/source.proto",
+        "third_party/metrics_proto/ukm/web_features.proto",
+        "third_party/metrics_proto/user_action_event.proto",
+        "third_party/metrics_proto/user_demographics.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/third_party/metrics_proto " +
+         "--cpp_out=lite=true:$(genDir)/third_party/metrics_proto/ " +
+         "external/cronet/tot/third_party/metrics_proto/call_stack_profile.proto " +
+         "external/cronet/tot/third_party/metrics_proto/cast_logs.proto " +
+         "external/cronet/tot/third_party/metrics_proto/chrome_os_app_list_launch_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/chrome_user_metrics_extension.proto " +
+         "external/cronet/tot/third_party/metrics_proto/custom_tab_session.proto " +
+         "external/cronet/tot/third_party/metrics_proto/device_state.proto " +
+         "external/cronet/tot/third_party/metrics_proto/dwa/deidentified_web_analytics.proto " +
+         "external/cronet/tot/third_party/metrics_proto/execution_context.proto " +
+         "external/cronet/tot/third_party/metrics_proto/extension_install.proto " +
+         "external/cronet/tot/third_party/metrics_proto/histogram_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_focus_type.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_input_type.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_scoring_signals.proto " +
+         "external/cronet/tot/third_party/metrics_proto/perf_data.proto " +
+         "external/cronet/tot/third_party/metrics_proto/perf_stat.proto " +
+         "external/cronet/tot/third_party/metrics_proto/printer_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/reporting_info.proto " +
+         "external/cronet/tot/third_party/metrics_proto/sampled_profile.proto " +
+         "external/cronet/tot/third_party/metrics_proto/structured_data.proto " +
+         "external/cronet/tot/third_party/metrics_proto/system_profile.proto " +
+         "external/cronet/tot/third_party/metrics_proto/trace_log.proto " +
+         "external/cronet/tot/third_party/metrics_proto/translate_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/aggregate.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/entry.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/report.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/source.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/web_features.proto " +
+         "external/cronet/tot/third_party/metrics_proto/user_action_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/user_demographics.proto",
+    host_cross_supported: false,
+    out: [
+        "third_party/metrics_proto/call_stack_profile.pb.cc",
+        "third_party/metrics_proto/cast_logs.pb.cc",
+        "third_party/metrics_proto/chrome_os_app_list_launch_event.pb.cc",
+        "third_party/metrics_proto/chrome_user_metrics_extension.pb.cc",
+        "third_party/metrics_proto/custom_tab_session.pb.cc",
+        "third_party/metrics_proto/device_state.pb.cc",
+        "third_party/metrics_proto/dwa/deidentified_web_analytics.pb.cc",
+        "third_party/metrics_proto/execution_context.pb.cc",
+        "third_party/metrics_proto/extension_install.pb.cc",
+        "third_party/metrics_proto/histogram_event.pb.cc",
+        "third_party/metrics_proto/omnibox_event.pb.cc",
+        "third_party/metrics_proto/omnibox_focus_type.pb.cc",
+        "third_party/metrics_proto/omnibox_input_type.pb.cc",
+        "third_party/metrics_proto/omnibox_scoring_signals.pb.cc",
+        "third_party/metrics_proto/perf_data.pb.cc",
+        "third_party/metrics_proto/perf_stat.pb.cc",
+        "third_party/metrics_proto/printer_event.pb.cc",
+        "third_party/metrics_proto/reporting_info.pb.cc",
+        "third_party/metrics_proto/sampled_profile.pb.cc",
+        "third_party/metrics_proto/structured_data.pb.cc",
+        "third_party/metrics_proto/system_profile.pb.cc",
+        "third_party/metrics_proto/trace_log.pb.cc",
+        "third_party/metrics_proto/translate_event.pb.cc",
+        "third_party/metrics_proto/ukm/aggregate.pb.cc",
+        "third_party/metrics_proto/ukm/entry.pb.cc",
+        "third_party/metrics_proto/ukm/report.pb.cc",
+        "third_party/metrics_proto/ukm/source.pb.cc",
+        "third_party/metrics_proto/ukm/web_features.pb.cc",
+        "third_party/metrics_proto/user_action_event.pb.cc",
+        "third_party/metrics_proto/user_demographics.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //third_party/metrics_proto:metrics_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_third_party_metrics_proto_metrics_proto_gen__testing",
+    srcs: [
+        "third_party/metrics_proto/call_stack_profile.proto",
+        "third_party/metrics_proto/cast_logs.proto",
+        "third_party/metrics_proto/chrome_os_app_list_launch_event.proto",
+        "third_party/metrics_proto/chrome_user_metrics_extension.proto",
+        "third_party/metrics_proto/custom_tab_session.proto",
+        "third_party/metrics_proto/device_state.proto",
+        "third_party/metrics_proto/dwa/deidentified_web_analytics.proto",
+        "third_party/metrics_proto/execution_context.proto",
+        "third_party/metrics_proto/extension_install.proto",
+        "third_party/metrics_proto/histogram_event.proto",
+        "third_party/metrics_proto/omnibox_event.proto",
+        "third_party/metrics_proto/omnibox_focus_type.proto",
+        "third_party/metrics_proto/omnibox_input_type.proto",
+        "third_party/metrics_proto/omnibox_scoring_signals.proto",
+        "third_party/metrics_proto/perf_data.proto",
+        "third_party/metrics_proto/perf_stat.proto",
+        "third_party/metrics_proto/printer_event.proto",
+        "third_party/metrics_proto/reporting_info.proto",
+        "third_party/metrics_proto/sampled_profile.proto",
+        "third_party/metrics_proto/structured_data.proto",
+        "third_party/metrics_proto/system_profile.proto",
+        "third_party/metrics_proto/trace_log.proto",
+        "third_party/metrics_proto/translate_event.proto",
+        "third_party/metrics_proto/ukm/aggregate.proto",
+        "third_party/metrics_proto/ukm/entry.proto",
+        "third_party/metrics_proto/ukm/report.proto",
+        "third_party/metrics_proto/ukm/source.proto",
+        "third_party/metrics_proto/ukm/web_features.proto",
+        "third_party/metrics_proto/user_action_event.proto",
+        "third_party/metrics_proto/user_demographics.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/third_party/metrics_proto " +
+         "--cpp_out=lite=true:$(genDir)/third_party/metrics_proto/ " +
+         "external/cronet/tot/third_party/metrics_proto/call_stack_profile.proto " +
+         "external/cronet/tot/third_party/metrics_proto/cast_logs.proto " +
+         "external/cronet/tot/third_party/metrics_proto/chrome_os_app_list_launch_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/chrome_user_metrics_extension.proto " +
+         "external/cronet/tot/third_party/metrics_proto/custom_tab_session.proto " +
+         "external/cronet/tot/third_party/metrics_proto/device_state.proto " +
+         "external/cronet/tot/third_party/metrics_proto/dwa/deidentified_web_analytics.proto " +
+         "external/cronet/tot/third_party/metrics_proto/execution_context.proto " +
+         "external/cronet/tot/third_party/metrics_proto/extension_install.proto " +
+         "external/cronet/tot/third_party/metrics_proto/histogram_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_focus_type.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_input_type.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_scoring_signals.proto " +
+         "external/cronet/tot/third_party/metrics_proto/perf_data.proto " +
+         "external/cronet/tot/third_party/metrics_proto/perf_stat.proto " +
+         "external/cronet/tot/third_party/metrics_proto/printer_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/reporting_info.proto " +
+         "external/cronet/tot/third_party/metrics_proto/sampled_profile.proto " +
+         "external/cronet/tot/third_party/metrics_proto/structured_data.proto " +
+         "external/cronet/tot/third_party/metrics_proto/system_profile.proto " +
+         "external/cronet/tot/third_party/metrics_proto/trace_log.proto " +
+         "external/cronet/tot/third_party/metrics_proto/translate_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/aggregate.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/entry.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/report.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/source.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/web_features.proto " +
+         "external/cronet/tot/third_party/metrics_proto/user_action_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/user_demographics.proto",
+    host_cross_supported: false,
+    out: [
+        "third_party/metrics_proto/call_stack_profile.pb.cc",
+        "third_party/metrics_proto/cast_logs.pb.cc",
+        "third_party/metrics_proto/chrome_os_app_list_launch_event.pb.cc",
+        "third_party/metrics_proto/chrome_user_metrics_extension.pb.cc",
+        "third_party/metrics_proto/custom_tab_session.pb.cc",
+        "third_party/metrics_proto/device_state.pb.cc",
+        "third_party/metrics_proto/dwa/deidentified_web_analytics.pb.cc",
+        "third_party/metrics_proto/execution_context.pb.cc",
+        "third_party/metrics_proto/extension_install.pb.cc",
+        "third_party/metrics_proto/histogram_event.pb.cc",
+        "third_party/metrics_proto/omnibox_event.pb.cc",
+        "third_party/metrics_proto/omnibox_focus_type.pb.cc",
+        "third_party/metrics_proto/omnibox_input_type.pb.cc",
+        "third_party/metrics_proto/omnibox_scoring_signals.pb.cc",
+        "third_party/metrics_proto/perf_data.pb.cc",
+        "third_party/metrics_proto/perf_stat.pb.cc",
+        "third_party/metrics_proto/printer_event.pb.cc",
+        "third_party/metrics_proto/reporting_info.pb.cc",
+        "third_party/metrics_proto/sampled_profile.pb.cc",
+        "third_party/metrics_proto/structured_data.pb.cc",
+        "third_party/metrics_proto/system_profile.pb.cc",
+        "third_party/metrics_proto/trace_log.pb.cc",
+        "third_party/metrics_proto/translate_event.pb.cc",
+        "third_party/metrics_proto/ukm/aggregate.pb.cc",
+        "third_party/metrics_proto/ukm/entry.pb.cc",
+        "third_party/metrics_proto/ukm/report.pb.cc",
+        "third_party/metrics_proto/ukm/source.pb.cc",
+        "third_party/metrics_proto/ukm/web_features.pb.cc",
+        "third_party/metrics_proto/user_action_event.pb.cc",
+        "third_party/metrics_proto/user_demographics.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //third_party/metrics_proto:metrics_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_third_party_metrics_proto_metrics_proto_gen__testing_headers",
+    srcs: [
+        "third_party/metrics_proto/call_stack_profile.proto",
+        "third_party/metrics_proto/cast_logs.proto",
+        "third_party/metrics_proto/chrome_os_app_list_launch_event.proto",
+        "third_party/metrics_proto/chrome_user_metrics_extension.proto",
+        "third_party/metrics_proto/custom_tab_session.proto",
+        "third_party/metrics_proto/device_state.proto",
+        "third_party/metrics_proto/dwa/deidentified_web_analytics.proto",
+        "third_party/metrics_proto/execution_context.proto",
+        "third_party/metrics_proto/extension_install.proto",
+        "third_party/metrics_proto/histogram_event.proto",
+        "third_party/metrics_proto/omnibox_event.proto",
+        "third_party/metrics_proto/omnibox_focus_type.proto",
+        "third_party/metrics_proto/omnibox_input_type.proto",
+        "third_party/metrics_proto/omnibox_scoring_signals.proto",
+        "third_party/metrics_proto/perf_data.proto",
+        "third_party/metrics_proto/perf_stat.proto",
+        "third_party/metrics_proto/printer_event.proto",
+        "third_party/metrics_proto/reporting_info.proto",
+        "third_party/metrics_proto/sampled_profile.proto",
+        "third_party/metrics_proto/structured_data.proto",
+        "third_party/metrics_proto/system_profile.proto",
+        "third_party/metrics_proto/trace_log.proto",
+        "third_party/metrics_proto/translate_event.proto",
+        "third_party/metrics_proto/ukm/aggregate.proto",
+        "third_party/metrics_proto/ukm/entry.proto",
+        "third_party/metrics_proto/ukm/report.proto",
+        "third_party/metrics_proto/ukm/source.proto",
+        "third_party/metrics_proto/ukm/web_features.proto",
+        "third_party/metrics_proto/user_action_event.proto",
+        "third_party/metrics_proto/user_demographics.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/third_party/metrics_proto " +
+         "--cpp_out=lite=true:$(genDir)/third_party/metrics_proto/ " +
+         "external/cronet/tot/third_party/metrics_proto/call_stack_profile.proto " +
+         "external/cronet/tot/third_party/metrics_proto/cast_logs.proto " +
+         "external/cronet/tot/third_party/metrics_proto/chrome_os_app_list_launch_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/chrome_user_metrics_extension.proto " +
+         "external/cronet/tot/third_party/metrics_proto/custom_tab_session.proto " +
+         "external/cronet/tot/third_party/metrics_proto/device_state.proto " +
+         "external/cronet/tot/third_party/metrics_proto/dwa/deidentified_web_analytics.proto " +
+         "external/cronet/tot/third_party/metrics_proto/execution_context.proto " +
+         "external/cronet/tot/third_party/metrics_proto/extension_install.proto " +
+         "external/cronet/tot/third_party/metrics_proto/histogram_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_focus_type.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_input_type.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_scoring_signals.proto " +
+         "external/cronet/tot/third_party/metrics_proto/perf_data.proto " +
+         "external/cronet/tot/third_party/metrics_proto/perf_stat.proto " +
+         "external/cronet/tot/third_party/metrics_proto/printer_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/reporting_info.proto " +
+         "external/cronet/tot/third_party/metrics_proto/sampled_profile.proto " +
+         "external/cronet/tot/third_party/metrics_proto/structured_data.proto " +
+         "external/cronet/tot/third_party/metrics_proto/system_profile.proto " +
+         "external/cronet/tot/third_party/metrics_proto/trace_log.proto " +
+         "external/cronet/tot/third_party/metrics_proto/translate_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/aggregate.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/entry.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/report.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/source.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/web_features.proto " +
+         "external/cronet/tot/third_party/metrics_proto/user_action_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/user_demographics.proto",
+    out: [
+        "third_party/metrics_proto/call_stack_profile.pb.h",
+        "third_party/metrics_proto/cast_logs.pb.h",
+        "third_party/metrics_proto/chrome_os_app_list_launch_event.pb.h",
+        "third_party/metrics_proto/chrome_user_metrics_extension.pb.h",
+        "third_party/metrics_proto/custom_tab_session.pb.h",
+        "third_party/metrics_proto/device_state.pb.h",
+        "third_party/metrics_proto/dwa/deidentified_web_analytics.pb.h",
+        "third_party/metrics_proto/execution_context.pb.h",
+        "third_party/metrics_proto/extension_install.pb.h",
+        "third_party/metrics_proto/histogram_event.pb.h",
+        "third_party/metrics_proto/omnibox_event.pb.h",
+        "third_party/metrics_proto/omnibox_focus_type.pb.h",
+        "third_party/metrics_proto/omnibox_input_type.pb.h",
+        "third_party/metrics_proto/omnibox_scoring_signals.pb.h",
+        "third_party/metrics_proto/perf_data.pb.h",
+        "third_party/metrics_proto/perf_stat.pb.h",
+        "third_party/metrics_proto/printer_event.pb.h",
+        "third_party/metrics_proto/reporting_info.pb.h",
+        "third_party/metrics_proto/sampled_profile.pb.h",
+        "third_party/metrics_proto/structured_data.pb.h",
+        "third_party/metrics_proto/system_profile.pb.h",
+        "third_party/metrics_proto/trace_log.pb.h",
+        "third_party/metrics_proto/translate_event.pb.h",
+        "third_party/metrics_proto/ukm/aggregate.pb.h",
+        "third_party/metrics_proto/ukm/entry.pb.h",
+        "third_party/metrics_proto/ukm/report.pb.h",
+        "third_party/metrics_proto/ukm/source.pb.h",
+        "third_party/metrics_proto/ukm/web_features.pb.h",
+        "third_party/metrics_proto/user_action_event.pb.h",
+        "third_party/metrics_proto/user_demographics.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "protos",
+        "third_party/metrics_proto",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
+// GN: //third_party/metrics_proto:metrics_proto_gen
+cc_genrule {
+    name: "tot_cronet_third_party_metrics_proto_metrics_proto_gen_headers",
+    srcs: [
+        "third_party/metrics_proto/call_stack_profile.proto",
+        "third_party/metrics_proto/cast_logs.proto",
+        "third_party/metrics_proto/chrome_os_app_list_launch_event.proto",
+        "third_party/metrics_proto/chrome_user_metrics_extension.proto",
+        "third_party/metrics_proto/custom_tab_session.proto",
+        "third_party/metrics_proto/device_state.proto",
+        "third_party/metrics_proto/dwa/deidentified_web_analytics.proto",
+        "third_party/metrics_proto/execution_context.proto",
+        "third_party/metrics_proto/extension_install.proto",
+        "third_party/metrics_proto/histogram_event.proto",
+        "third_party/metrics_proto/omnibox_event.proto",
+        "third_party/metrics_proto/omnibox_focus_type.proto",
+        "third_party/metrics_proto/omnibox_input_type.proto",
+        "third_party/metrics_proto/omnibox_scoring_signals.proto",
+        "third_party/metrics_proto/perf_data.proto",
+        "third_party/metrics_proto/perf_stat.proto",
+        "third_party/metrics_proto/printer_event.proto",
+        "third_party/metrics_proto/reporting_info.proto",
+        "third_party/metrics_proto/sampled_profile.proto",
+        "third_party/metrics_proto/structured_data.proto",
+        "third_party/metrics_proto/system_profile.proto",
+        "third_party/metrics_proto/trace_log.proto",
+        "third_party/metrics_proto/translate_event.proto",
+        "third_party/metrics_proto/ukm/aggregate.proto",
+        "third_party/metrics_proto/ukm/entry.proto",
+        "third_party/metrics_proto/ukm/report.proto",
+        "third_party/metrics_proto/ukm/source.proto",
+        "third_party/metrics_proto/ukm/web_features.proto",
+        "third_party/metrics_proto/user_action_event.proto",
+        "third_party/metrics_proto/user_demographics.proto",
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/third_party/metrics_proto " +
+         "--cpp_out=lite=true:$(genDir)/third_party/metrics_proto/ " +
+         "external/cronet/tot/third_party/metrics_proto/call_stack_profile.proto " +
+         "external/cronet/tot/third_party/metrics_proto/cast_logs.proto " +
+         "external/cronet/tot/third_party/metrics_proto/chrome_os_app_list_launch_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/chrome_user_metrics_extension.proto " +
+         "external/cronet/tot/third_party/metrics_proto/custom_tab_session.proto " +
+         "external/cronet/tot/third_party/metrics_proto/device_state.proto " +
+         "external/cronet/tot/third_party/metrics_proto/dwa/deidentified_web_analytics.proto " +
+         "external/cronet/tot/third_party/metrics_proto/execution_context.proto " +
+         "external/cronet/tot/third_party/metrics_proto/extension_install.proto " +
+         "external/cronet/tot/third_party/metrics_proto/histogram_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_focus_type.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_input_type.proto " +
+         "external/cronet/tot/third_party/metrics_proto/omnibox_scoring_signals.proto " +
+         "external/cronet/tot/third_party/metrics_proto/perf_data.proto " +
+         "external/cronet/tot/third_party/metrics_proto/perf_stat.proto " +
+         "external/cronet/tot/third_party/metrics_proto/printer_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/reporting_info.proto " +
+         "external/cronet/tot/third_party/metrics_proto/sampled_profile.proto " +
+         "external/cronet/tot/third_party/metrics_proto/structured_data.proto " +
+         "external/cronet/tot/third_party/metrics_proto/system_profile.proto " +
+         "external/cronet/tot/third_party/metrics_proto/trace_log.proto " +
+         "external/cronet/tot/third_party/metrics_proto/translate_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/aggregate.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/entry.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/report.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/source.proto " +
+         "external/cronet/tot/third_party/metrics_proto/ukm/web_features.proto " +
+         "external/cronet/tot/third_party/metrics_proto/user_action_event.proto " +
+         "external/cronet/tot/third_party/metrics_proto/user_demographics.proto",
+    out: [
+        "third_party/metrics_proto/call_stack_profile.pb.h",
+        "third_party/metrics_proto/cast_logs.pb.h",
+        "third_party/metrics_proto/chrome_os_app_list_launch_event.pb.h",
+        "third_party/metrics_proto/chrome_user_metrics_extension.pb.h",
+        "third_party/metrics_proto/custom_tab_session.pb.h",
+        "third_party/metrics_proto/device_state.pb.h",
+        "third_party/metrics_proto/dwa/deidentified_web_analytics.pb.h",
+        "third_party/metrics_proto/execution_context.pb.h",
+        "third_party/metrics_proto/extension_install.pb.h",
+        "third_party/metrics_proto/histogram_event.pb.h",
+        "third_party/metrics_proto/omnibox_event.pb.h",
+        "third_party/metrics_proto/omnibox_focus_type.pb.h",
+        "third_party/metrics_proto/omnibox_input_type.pb.h",
+        "third_party/metrics_proto/omnibox_scoring_signals.pb.h",
+        "third_party/metrics_proto/perf_data.pb.h",
+        "third_party/metrics_proto/perf_stat.pb.h",
+        "third_party/metrics_proto/printer_event.pb.h",
+        "third_party/metrics_proto/reporting_info.pb.h",
+        "third_party/metrics_proto/sampled_profile.pb.h",
+        "third_party/metrics_proto/structured_data.pb.h",
+        "third_party/metrics_proto/system_profile.pb.h",
+        "third_party/metrics_proto/trace_log.pb.h",
+        "third_party/metrics_proto/translate_event.pb.h",
+        "third_party/metrics_proto/ukm/aggregate.pb.h",
+        "third_party/metrics_proto/ukm/entry.pb.h",
+        "third_party/metrics_proto/ukm/report.pb.h",
+        "third_party/metrics_proto/ukm/source.pb.h",
+        "third_party/metrics_proto/ukm/web_features.pb.h",
+        "third_party/metrics_proto/user_action_event.pb.h",
+        "third_party/metrics_proto/user_demographics.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "protos",
+        "third_party/metrics_proto",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
+// GN: //third_party/netty4:netty_all_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_third_party_netty4_netty_all_java__process_device__testing",
+    srcs: [
+        "third_party/netty4/src/jar/all-in-one/netty-all-4.1.9.Final.jar",
+    ],
+    cmd: "mkdir -p $(genDir)/third_party/netty4 &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "third_party/netty4/netty_all_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //third_party/quic_trace:quic_trace_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_third_party_quic_trace_quic_trace_proto_gen__testing",
+    srcs: [
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+        "third_party/quic_trace/src/quic_trace/quic_trace.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/third_party/quic_trace/src/quic_trace " +
+         "--cpp_out=lite=true:$(genDir)/third_party/quic_trace/src/quic_trace/ " +
+         "external/cronet/tot/third_party/quic_trace/src/quic_trace/quic_trace.proto",
+    host_cross_supported: false,
+    out: [
+        "third_party/quic_trace/src/quic_trace/quic_trace.pb.cc",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //third_party/quic_trace:quic_trace_proto_gen__testing
+cc_genrule {
+    name: "tot_cronet_third_party_quic_trace_quic_trace_proto_gen__testing_headers",
+    srcs: [
+        "third_party/protobuf/src/google/protobuf/descriptor.proto",
+        "third_party/quic_trace/src/quic_trace/quic_trace.proto",
+    ],
+    tools: [
+        "tot_cronet_third_party_protobuf_protoc",
+    ],
+    cmd: "$(location tot_cronet_third_party_protobuf_protoc) " +
+         "--proto_path=external/cronet/tot/third_party/quic_trace/src/quic_trace " +
+         "--cpp_out=lite=true:$(genDir)/third_party/quic_trace/src/quic_trace/ " +
+         "external/cronet/tot/third_party/quic_trace/src/quic_trace/quic_trace.proto",
+    out: [
+        "third_party/quic_trace/src/quic_trace/quic_trace.pb.h",
+    ],
+    export_include_dirs: [
+        ".",
+        "protos",
+        "third_party/quic_trace/src",
+        "third_party/quic_trace/src/quic_trace",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
 // GN: //third_party/rust/serde_json_lenient/v0_2/wrapper:wrapper_cxx_generated_gen
 cc_genrule {
     name: "tot_cronet_third_party_rust_serde_json_lenient_v0_2_wrapper_wrapper_cxx_generated_gen",
@@ -13440,9 +21227,11 @@
 // GN: //url:buildflags
 cc_genrule {
     name: "tot_cronet_url_buildflags",
-    cmd: "mkdir -p $(genDir)/url && echo '--flags USE_PLATFORM_ICU_ALTERNATIVES=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/url &&  " +
+         "echo '--flags USE_PLATFORM_ICU_ALTERNATIVES=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//url:buildflags " +
          "--gen-dir " +
@@ -13467,9 +21256,11 @@
 // GN: //url:buildflags__testing
 cc_genrule {
     name: "tot_cronet_url_buildflags__testing",
-    cmd: "mkdir -p $(genDir)/url && echo '--flags USE_PLATFORM_ICU_ALTERNATIVES=\"true\"' | " +
-         "$(location build/write_buildflag_header.py) --output " +
-         "$(out) " +
+    cmd: "mkdir -p $(genDir)/url &&  " +
+         "echo '--flags USE_PLATFORM_ICU_ALTERNATIVES=true' | " +
+         "$(location build/write_buildflag_header.py) " +
+         "--output " +
+         "'$(out)' " +
          "--rulename " +
          "//url:buildflags " +
          "--gen-dir " +
@@ -13491,6 +21282,70 @@
     ],
 }
 
+// GN: //url:url_java__process_device
+java_genrule {
+    name: "tot_cronet_url_url_java__process_device",
+    srcs: [
+        ":tot_cronet_url_url_java__compile_java",
+    ],
+    cmd: "mkdir -p $(genDir)/url &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "url/url_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //url:url_java__process_device__testing
+java_genrule {
+    name: "tot_cronet_url_url_java__process_device__testing",
+    srcs: [
+        ":tot_cronet_url_url_java__compile_java__testing",
+    ],
+    cmd: "mkdir -p $(genDir)/url &&  " +
+         "$(location build/android/gyp/filter_zip.py) " +
+         "--input " +
+         "'$(in)' " +
+         "--output " +
+         "'$(out)' " +
+         "--exclude-globs " +
+         "'[\"*/R.class\", \"*/R\\$$*.class\", \"*/Manifest.class\", \"*/Manifest\\$$*.class\", \"*/*GEN_JNI.class\"]' " +
+         "--include-globs " +
+         "'[]'",
+    out: [
+        "url/url_java.processed.jar",
+    ],
+    tool_files: [
+        "build/action_helpers.py",
+        "build/android/gyp/filter_zip.py",
+        "build/android/gyp/util/__init__.py",
+        "build/android/gyp/util/build_utils.py",
+        "build/gn_helpers.py",
+        "build/zip_helpers.py",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //url:url_jni_headers__action
 cc_genrule {
     name: "tot_cronet_url_url_jni_headers__action",
@@ -13498,26 +21353,29 @@
         "url/android/java/src/org/chromium/url/IDNStringUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/url/url_jni_headers &&  " +
-         "mkdir -p $(genDir)/url && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/url &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/url/url_jni_headers " +
+         "'$(genDir)/url/url_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/url/url_jni_headers.srcjar " +
+         "'$(genDir)/url/url_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/url/url_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/url/url_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "IDNStringUtil_jni.h " +
          "--input-file " +
-         "$(location url/android/java/src/org/chromium/url/IDNStringUtil.java) " +
+         "'$(location url/android/java/src/org/chromium/url/IDNStringUtil.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     host_cross_supported: false,
     out: [
         "url/url_jni_headers.srcjar",
         "url/url_jni_headers/IDNStringUtil_jni.h",
+        "url/url_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -13553,25 +21411,28 @@
         "url/android/java/src/org/chromium/url/IDNStringUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/url/url_jni_headers &&  " +
-         "mkdir -p $(genDir)/url && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/url &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/url/url_jni_headers " +
+         "'$(genDir)/url/url_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/url/url_jni_headers.srcjar " +
+         "'$(genDir)/url/url_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/url/url_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/url/url_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "IDNStringUtil_jni.h " +
          "--input-file " +
-         "$(location url/android/java/src/org/chromium/url/IDNStringUtil.java) " +
+         "'$(location url/android/java/src/org/chromium/url/IDNStringUtil.java)' " +
          "--package-prefix " +
          "android.net.connectivity",
     out: [
         "url/url_jni_headers.srcjar",
         "url/url_jni_headers/IDNStringUtil_jni.h",
+        "url/url_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -13597,6 +21458,18 @@
     ],
 }
 
+// GN: //url:url_jni_headers__action
+java_genrule {
+    name: "tot_cronet_url_url_jni_headers__action__java_proxy_only",
+    srcs: [
+        ":tot_cronet_url_url_jni_headers__action__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "url_jni_headers.srcjar",
+    ],
+}
+
 // GN: //url:url_jni_headers__action__testing
 cc_genrule {
     name: "tot_cronet_url_url_jni_headers__action__testing",
@@ -13604,24 +21477,27 @@
         "url/android/java/src/org/chromium/url/IDNStringUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/url/url_jni_headers &&  " +
-         "mkdir -p $(genDir)/url && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/url &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/url/url_jni_headers " +
+         "'$(genDir)/url/url_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/url/url_jni_headers.srcjar " +
+         "'$(genDir)/url/url_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/url/url_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/url/url_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "IDNStringUtil_jni.h " +
          "--input-file " +
-         "$(location url/android/java/src/org/chromium/url/IDNStringUtil.java)",
+         "'$(location url/android/java/src/org/chromium/url/IDNStringUtil.java)'",
     host_cross_supported: false,
     out: [
         "url/url_jni_headers.srcjar",
         "url/url_jni_headers/IDNStringUtil_jni.h",
+        "url/url_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -13657,23 +21533,26 @@
         "url/android/java/src/org/chromium/url/IDNStringUtil.java",
     ],
     cmd: "mkdir -p $(genDir)/jni_headers/url/url_jni_headers &&  " +
-         "mkdir -p $(genDir)/url && $(location third_party/jni_zero/jni_zero.py) from-source " +
+         "mkdir -p $(genDir)/url &&  " +
+         "$(location third_party/jni_zero/jni_zero.py) " +
+         "from-source " +
          "--output-dir " +
-         "$(genDir)/url/url_jni_headers " +
+         "'$(genDir)/url/url_jni_headers' " +
          "--extra-include " +
          "third_party/jni_zero/jni_zero_internal.h " +
          "--srcjar-path " +
-         "$(genDir)/url/url_jni_headers.srcjar " +
+         "'$(genDir)/url/url_jni_headers.srcjar' " +
          "--placeholder-srcjar-path " +
-         "$(genDir)/url/url_jni_headers_placeholder.srcjar " +
+         "'$(genDir)/url/url_jni_headers_placeholder.srcjar' " +
          "--use-proxy-hash " +
          "--output-name " +
          "IDNStringUtil_jni.h " +
          "--input-file " +
-         "$(location url/android/java/src/org/chromium/url/IDNStringUtil.java)",
+         "'$(location url/android/java/src/org/chromium/url/IDNStringUtil.java)'",
     out: [
         "url/url_jni_headers.srcjar",
         "url/url_jni_headers/IDNStringUtil_jni.h",
+        "url/url_jni_headers_placeholder.srcjar",
     ],
     tool_files: [
         "third_party/jni_zero/codegen/called_by_native_header.py",
@@ -13698,3 +21577,15 @@
         "//external/cronet:__subpackages__",
     ],
 }
+
+// GN: //url:url_jni_headers__action__testing
+java_genrule {
+    name: "tot_cronet_url_url_jni_headers__action__testing__java_proxy_only",
+    srcs: [
+        ":tot_cronet_url_url_jni_headers__action__testing__java",
+    ],
+    cmd: "cp $(in) $(genDir)",
+    out: [
+        "url_jni_headers.srcjar",
+    ],
+}
diff --git a/tot/Android.extras.bp b/tot/Android.extras.bp
index aa64736..3472407 100644
--- a/tot/Android.extras.bp
+++ b/tot/Android.extras.bp
@@ -12,8 +12,6 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-// This is manually maintained and automatically included into the Android.bp by the gn2bp script.
-
 license {
     name: "tot_cronet_license",
     license_kinds: [
@@ -44,7 +42,6 @@
 }
 
 java_library {
-    // Don't change the name of the module.
     name: "tot_cronet_api_java",
     static_libs: [
         "tot_cronet_components_cronet_android_cronet_api_java",
@@ -61,11 +58,10 @@
 }
 
 java_library {
-    // Don't change the name of the module.
     name: "tot_cronet_java",
     static_libs: [
         "tot_cronet_components_cronet_android_cronet_impl_native_java",
-        "tot_cronet_components_cronet_android_cronet_jni_registration_java",
+        "tot_cronet_components_cronet_android_cronet_build_config_and_jni_registration_java",
     ],
     sdk_version: "module_current",
     min_sdk_version: "30",
@@ -79,11 +75,10 @@
 }
 
 java_library {
-    // Don't change the name of the module.
     name: "tot_cronet_java__testing",
     static_libs: [
         "tot_cronet_components_cronet_android_cronet_impl_native_java__testing",
-        "tot_cronet_components_cronet_android_cronet_jni_registration_java__testing",
+        "tot_cronet_components_cronet_android_cronet_build_config_and_jni_registration_java__testing",
         "tot_cronet_components_cronet_android_cronet_tests_jni_registration_java__testing",
     ],
     sdk_version: "module_current",
@@ -169,12 +164,12 @@
     ],
 }
 
-// the current rust_bindgen modules does not have a `include_dirs` attribute which means
-// that the CC header generated from the rust_bindgen will not be allowed to reference
-// other headers through relative path from repository root like how Chromium does, so
-// in order to circumvent this issue, this module exists in order to allow
-// rust_bindgen module access to include header files  using the relative path
-// from the repository root.
+// rust_bindgen modules do not have an `include_dirs` attribute. Due to that,
+// C++ headers generated from rust_bindgen can't reference other headers
+// through paths relative to the repository root. This is what Chromium does
+// so, to circumvent this issue, create this module that adds the root of the
+// repository to `include_dirs`. This will be added to all modules depending
+// on a rust_bindgen module.
 cc_library_headers {
     name: "tot_cronet_repository_root_include_dirs_anchor",
     host_supported: true,
diff --git a/tot/LICENSE b/tot/LICENSE
index 51d09ae..32e012b 100644
--- a/tot/LICENSE
+++ b/tot/LICENSE
@@ -1134,188 +1134,208 @@
 
 ============================
 
-BoringSSL is a fork of OpenSSL. As such, large parts of it fall under OpenSSL
-licensing. Files that are completely new have a Google copyright and an ISC
-license. This license is reproduced at the bottom of this file.
 
-Contributors to BoringSSL are required to follow the CLA rules for Chromium:
-https://cla.developers.google.com/clas
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
 
-Files in third_party/ have their own licenses, as described therein. The MIT
-license, for third_party/fiat, which, unlike other third_party directories, is
-compiled into non-test libraries, is included below.
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
 
-The OpenSSL toolkit stays under a dual license, i.e. both the conditions of the
-OpenSSL License and the original SSLeay license apply to the toolkit. See below
-for the actual license texts. Actually both licenses are BSD-style Open Source
-licenses. In case of any license issues related to OpenSSL please contact
-openssl-core@openssl.org.
+   1. Definitions.
 
-The following are Google-internal bug numbers where explicit permission from
-some authors is recorded for use of their work. (This is purely for our own
-record keeping.)
-  27287199
-  27287880
-  27287883
-  263291445
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
 
-  OpenSSL License
-  ---------------
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
 
-/* ====================================================================
- * Copyright (c) 1998-2011 The OpenSSL Project.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer. 
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. All advertising materials mentioning features or use of this
- *    software must display the following acknowledgment:
- *    "This product includes software developed by the OpenSSL Project
- *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
- *
- * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
- *    endorse or promote products derived from this software without
- *    prior written permission. For written permission, please contact
- *    openssl-core@openssl.org.
- *
- * 5. Products derived from this software may not be called "OpenSSL"
- *    nor may "OpenSSL" appear in their names without prior written
- *    permission of the OpenSSL Project.
- *
- * 6. Redistributions of any form whatsoever must retain the following
- *    acknowledgment:
- *    "This product includes software developed by the OpenSSL Project
- *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
- *
- * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
- * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- * OF THE POSSIBILITY OF SUCH DAMAGE.
- * ====================================================================
- *
- * This product includes cryptographic software written by Eric Young
- * (eay@cryptsoft.com).  This product includes software written by Tim
- * Hudson (tjh@cryptsoft.com).
- *
- */
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
 
- Original SSLeay License
- -----------------------
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
 
-/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
- * All rights reserved.
- *
- * This package is an SSL implementation written
- * by Eric Young (eay@cryptsoft.com).
- * The implementation was written so as to conform with Netscapes SSL.
- * 
- * This library is free for commercial and non-commercial use as long as
- * the following conditions are aheared to.  The following conditions
- * apply to all code found in this distribution, be it the RC4, RSA,
- * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
- * included with this distribution is covered by the same copyright terms
- * except that the holder is Tim Hudson (tjh@cryptsoft.com).
- * 
- * Copyright remains Eric Young's, and as such any Copyright notices in
- * the code are not to be removed.
- * If this package is used in a product, Eric Young should be given attribution
- * as the author of the parts of the library used.
- * This can be in the form of a textual message at program startup or
- * in documentation (online or textual) provided with the package.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- *    must display the following acknowledgement:
- *    "This product includes cryptographic software written by
- *     Eric Young (eay@cryptsoft.com)"
- *    The word 'cryptographic' can be left out if the rouines from the library
- *    being used are not cryptographic related :-).
- * 4. If you include any Windows specific code (or a derivative thereof) from 
- *    the apps directory (application code) you must include an acknowledgement:
- *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
- * 
- * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * 
- * The licence and distribution terms for any publically available version or
- * derivative of this code cannot be changed.  i.e. this code cannot simply be
- * copied and put under another distribution licence
- * [including the GNU Public Licence.]
- */
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
 
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
 
-ISC license used for completely new code in BoringSSL:
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
 
-/* Copyright (c) 2015, Google Inc.
- *
- * Permission to use, copy, modify, and/or distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
- * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
- * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
- * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
 
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
 
-The code in third_party/fiat carries the MIT license:
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
 
-Copyright (c) 2015-2016 the fiat-crypto authors (see
-https://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS).
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
 
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
 
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
 
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
 
 
 Licenses for support code
@@ -1389,39 +1409,25 @@
 
 ============================
 
-Path = third_party/boringssl/src/pki/testdata/nist-pkits/README.chromium
-
-============================
-
-unencumbered
-============================
-
 Path = third_party/boringssl/src/third_party/fiat/README.chromium
 
 ============================
 
-The MIT License (MIT)
+The Apache License, Version 2.0 (Apache-2.0)
 
-Copyright (c) 2015-2020 the fiat-crypto authors (see
-https://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS).
+Copyright 2015-2020 the fiat-crypto authors (see the AUTHORS file)
 
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
+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
 
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
+    http://www.apache.org/licenses/LICENSE-2.0
 
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+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.
 
 ============================
 
@@ -5077,6 +5083,31 @@
 
 ============================
 
+Path = third_party/rust/foldhash/v0_1/README.chromium
+
+============================
+
+Copyright (c) 2024 Orson Peters
+
+This software is provided 'as-is', without any express or implied warranty. In
+no event will the authors be held liable for any damages arising from the use of
+this software.
+
+Permission is granted to anyone to use this software for any purpose, including
+commercial applications, and to alter it and redistribute it freely, subject to
+the following restrictions:
+
+1. The origin of this software must not be misrepresented; you must not claim
+    that you wrote the original software. If you use this software in a product,
+    an acknowledgment in the product documentation would be appreciated but is
+    not required.
+
+2. Altered source versions must be plainly marked as such, and must not be
+    misrepresented as being the original software.
+
+3. This notice may not be removed or altered from any source distribution.
+============================
+
 Path = third_party/rust/itoa/v1/README.chromium
 
 ============================
@@ -7409,6 +7440,31 @@
 
 ============================
 
+Path = third_party/simdutf/README.chromium
+
+============================
+
+Copyright 2021 The simdutf authors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+============================
+
 Path = third_party/zlib/README.chromium
 
 ============================
diff --git a/tot/base/Android.bp b/tot/base/Android.bp
index 99642f9..0614b01 100644
--- a/tot/base/Android.bp
+++ b/tot/base/Android.bp
@@ -43,21 +43,20 @@
         "libbase_clogging_urust_ulog_uintegration_ubindgen__28d64ef8b615a427",
         "libchromium__c6c34dd5a98579f2",
         "libcxx__2cd805ef869e78fa",
+        "libfoldhash__3d2886e384b4e895",
         "liblog__7d83bd71ca2985fc",
     ],
     target: {
         android_arm: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -68,15 +67,13 @@
         android_arm64: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -87,15 +84,13 @@
         android_riscv64: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -106,15 +101,13 @@
         android_x86: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -125,15 +118,13 @@
         android_x86_64: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -145,15 +136,13 @@
             compile_multilib: "64",
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=no",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -191,21 +180,20 @@
         "libbase_clogging_urust_ulog_uintegration_ubindgen__89890e5f0e59f767",
         "libchromium__ada7dbc4acbf8156",
         "libcxx__3d5c3771dead539b",
+        "libfoldhash__9d82c8b43061ff92",
         "liblog__5ca9d3f4be387055",
     ],
     target: {
         android_arm: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -216,15 +204,13 @@
         android_arm64: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -235,15 +221,13 @@
         android_riscv64: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -254,15 +238,13 @@
         android_x86: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -273,15 +255,13 @@
         android_x86_64: {
             edition: "2021",
             cfgs: [
-                "cr_rustc_revision=\"a522d78598415cdd614ccc6d961160f192f64b5c-1-llvmorg-20-init-13894-g8cb44859\"",
+                "cr_rustc_revision=\"f7b43542838f0a4a6cfdb17fbeadf45002042a77-1-llvmorg-21-init-5118-g52cd27e6\"",
             ],
             flags: [
                 "-Dunsafe_op_in_unsafe_fn",
                 "-Dwarnings",
-                "-Aunused-imports",
                 "-Cforce-unwind-tables=yes",
                 "-Crelocation-model=pic",
-                "-Coverflow-checks=on",
                 "-Cdefault-linker-libraries",
                 "-Clto=no",
                 "-Ccodegen-units=1",
@@ -416,10 +396,9 @@
 // GN: //base:activity_state_java
 java_library {
     name: "tot_cronet_base_activity_state_java",
-    srcs: [
-        ":tot_cronet_base_application_status_enum_srcjar",
-        "android/java/src/org/chromium/base/ActivityLifecycleCallbacksAdapter.java",
-        "android/java/src/org/chromium/base/ActivityState.java",
+    static_libs: [
+        "tot_cronet_base_activity_state_java__process_device",
+        "tot_cronet_build_android_build_java",
     ],
     defaults: [
         "tot_cronet_java_framework_defaults",
@@ -434,16 +413,60 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:activity_state_java__compile_java
+java_library {
+    name: "tot_cronet_base_activity_state_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_application_status_enum_srcjar",
+        "android/java/src/org/chromium/base/ActivityLifecycleCallbacksAdapter.java",
+        "android/java/src/org/chromium/base/ActivityState.java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "tot_cronet_build_android_build_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:activity_state_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_activity_state_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_application_status_enum_srcjar__testing",
+        "android/java/src/org/chromium/base/ActivityLifecycleCallbacksAdapter.java",
+        "android/java/src/org/chromium/base/ActivityState.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:activity_state_java__testing
 java_library {
     name: "tot_cronet_base_activity_state_java__testing",
-    srcs: [
-        ":tot_cronet_base_application_status_enum_srcjar__testing",
-        "android/java/src/org/chromium/base/ActivityLifecycleCallbacksAdapter.java",
-        "android/java/src/org/chromium/base/ActivityState.java",
+    static_libs: [
+        "tot_cronet_base_activity_state_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
     ],
     apex_available: [
         "com.android.tethering",
@@ -456,7 +479,174 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:android_info_java
+java_library {
+    name: "tot_cronet_base_android_info_java",
+    static_libs: [
+        "jsr305",
+        "tot_cronet_base_android_info_java__process_device",
+        "tot_cronet_base_tasks_java",
+        "tot_cronet_build_android_build_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:android_info_java__compile_java
+java_library {
+    name: "tot_cronet_base_android_info_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_android_info_jni__action__java_proxy_only",
+        "android/java/src/org/chromium/base/AndroidInfo.java",
+    ],
+    static_libs: [
+        "jsr305",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java",
+        "tot_cronet_base_base_switches_java__compile_java",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_base_command_line_java__compile_java",
+        "tot_cronet_base_command_line_jni_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+        "tot_cronet_base_metrics_java__compile_java",
+        "tot_cronet_base_metrics_jni_java__compile_java",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_base_tasks_java__compile_java",
+        "tot_cronet_base_tasks_jni_java__compile_java",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java",
+        "tot_cronet_base_time_utils_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:android_info_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_android_info_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_android_info_jni__action__testing__java_proxy_only",
+        "android/java/src/org/chromium/base/AndroidInfo.java",
+    ],
+    static_libs: [
+        "jsr305",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:android_info_java__testing
+java_library {
+    name: "tot_cronet_base_android_info_java__testing",
+    static_libs: [
+        "jsr305",
+        "tot_cronet_base_android_info_java__process_device__testing",
+        "tot_cronet_base_tasks_java__testing",
+        "tot_cronet_build_android_build_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:android_runtime_jni_headers_java
+java_library {
+    name: "tot_cronet_base_android_runtime_jni_headers_java",
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:android_runtime_jni_headers_java__testing
+java_library {
+    name: "tot_cronet_base_android_runtime_jni_headers_java__testing",
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:base
@@ -470,8 +660,10 @@
         "allocator/dispatcher/tls.cc",
         "android/android_hardware_buffer_compat.cc",
         "android/android_image_reader_compat.cc",
+        "android/android_info.cc",
         "android/android_input_receiver_compat.cc",
         "android/apk_assets.cc",
+        "android/apk_info.cc",
         "android/application_status_listener.cc",
         "android/base_feature_map.cc",
         "android/base_jni_onload.cc",
@@ -484,6 +676,7 @@
         "android/command_line_android.cc",
         "android/content_uri_utils.cc",
         "android/cpu_features.cc",
+        "android/device_info.cc",
         "android/early_trace_event_binding.cc",
         "android/event_log.cc",
         "android/feature_list_jni.cc",
@@ -501,6 +694,7 @@
         "android/jni_android.cc",
         "android/jni_array.cc",
         "android/jni_bytebuffer.cc",
+        "android/jni_callback.cc",
         "android/jni_registrar.cc",
         "android/jni_string.cc",
         "android/jni_utils.cc",
@@ -520,6 +714,7 @@
         "android/radio_utils.cc",
         "android/scoped_hardware_buffer_fence_sync.cc",
         "android/scoped_hardware_buffer_handle.cc",
+        "android/scoped_input_event.cc",
         "android/shared_preferences/shared_preferences_manager.cc",
         "android/statistics_recorder_android.cc",
         "android/sys_utils.cc",
@@ -531,6 +726,7 @@
         "android/trace_event_binding.cc",
         "android/unguessable_token_android.cc",
         "at_exit.cc",
+        "atomicops.cc",
         "barrier_closure.cc",
         "base64.cc",
         "base64url.cc",
@@ -544,7 +740,6 @@
         "containers/intrusive_heap.cc",
         "containers/linked_list.cc",
         "cpu.cc",
-        "cpu_reduction_experiment.cc",
         "debug/alias.cc",
         "debug/asan_invalid_access.cc",
         "debug/asan_service.cc",
@@ -733,11 +928,13 @@
         "profiler/stack_sampling_profiler.cc",
         "profiler/stack_unwind_data.cc",
         "profiler/thread_delegate_posix.cc",
+        "profiler/thread_group_profiler.cc",
         "profiler/unwinder.cc",
         "rand_util.cc",
         "rand_util_posix.cc",
         "run_loop.cc",
         "sampling_heap_profiler/lock_free_address_hash_set.cc",
+        "sampling_heap_profiler/lock_free_bloom_filter.cc",
         "sampling_heap_profiler/poisson_allocation_sampler.cc",
         "sampling_heap_profiler/sampling_heap_profiler.cc",
         "scoped_add_feature_flags.cc",
@@ -892,6 +1089,7 @@
         "token.cc",
         "trace_event/heap_profiler_allocation_context.cc",
         "trace_event/heap_profiler_allocation_context_tracker.cc",
+        "trace_event/histogram_scope.cc",
         "trace_event/memory_allocator_dump_guid.cc",
         "trace_event/named_trigger.cc",
         "trace_event/trace_event_stub.cc",
@@ -916,10 +1114,13 @@
         "tot_cronet_base_allocator_buildflags",
         "tot_cronet_base_allocator_partition_allocator_src_partition_alloc_buildflags",
         "tot_cronet_base_anchor_functions_buildflags",
+        "tot_cronet_base_android_info_jni__action",
         "tot_cronet_base_android_runtime_jni_headers__action",
         "tot_cronet_base_base_jni__action",
+        "tot_cronet_base_base_minimal_jni__action",
         "tot_cronet_base_base_shared_preferences_jni__action",
         "tot_cronet_base_build_date",
+        "tot_cronet_base_build_info_jni__action",
         "tot_cronet_base_callback_jni__action",
         "tot_cronet_base_cfi_buildflags",
         "tot_cronet_base_check_version_internal_action",
@@ -944,6 +1145,7 @@
         "tot_cronet_base_synchronization_buildflags",
         "tot_cronet_base_sys_utils_jni__action",
         "tot_cronet_base_tasks_jni__action",
+        "tot_cronet_base_tasks_minimal_jni__action",
         "tot_cronet_base_tracing_buildflags",
         "tot_cronet_build_blink_buildflags",
         "tot_cronet_build_branding_buildflags",
@@ -960,10 +1162,13 @@
         "tot_cronet_base_allocator_buildflags",
         "tot_cronet_base_allocator_partition_allocator_src_partition_alloc_buildflags",
         "tot_cronet_base_anchor_functions_buildflags",
+        "tot_cronet_base_android_info_jni__action",
         "tot_cronet_base_android_runtime_jni_headers__action",
         "tot_cronet_base_base_jni__action",
+        "tot_cronet_base_base_minimal_jni__action",
         "tot_cronet_base_base_shared_preferences_jni__action",
         "tot_cronet_base_build_date",
+        "tot_cronet_base_build_info_jni__action",
         "tot_cronet_base_callback_jni__action",
         "tot_cronet_base_cfi_buildflags",
         "tot_cronet_base_check_version_internal_action",
@@ -988,6 +1193,7 @@
         "tot_cronet_base_synchronization_buildflags",
         "tot_cronet_base_sys_utils_jni__action",
         "tot_cronet_base_tasks_jni__action",
+        "tot_cronet_base_tasks_minimal_jni__action",
         "tot_cronet_base_tracing_buildflags",
         "tot_cronet_build_blink_buildflags",
         "tot_cronet_build_branding_buildflags",
@@ -1010,9 +1216,9 @@
         "-DANDROID",
         "-DANDROID_NDK_VERSION_ROLL=r27_1",
         "-DBASE_IMPLEMENTATION",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.130/include/cxx.h\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.146/include/cxx.h\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DHAVE_SYS_UIO_H",
         "-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE",
@@ -1073,7 +1279,6 @@
             srcs: [
                 "profiler/chrome_unwind_info_android_32.cc",
                 "profiler/chrome_unwinder_android_32.cc",
-                "trace_event/cfi_backtrace_android.cc",
             ],
             cflags: [
                 "-D_FORTIFY_SOURCE=2",
@@ -1115,6 +1320,7 @@
         "allocator/dispatcher/reentry_guard.cc",
         "allocator/dispatcher/tls.cc",
         "at_exit.cc",
+        "atomicops.cc",
         "barrier_closure.cc",
         "base64.cc",
         "base64url.cc",
@@ -1127,7 +1333,6 @@
         "containers/intrusive_heap.cc",
         "containers/linked_list.cc",
         "cpu.cc",
-        "cpu_reduction_experiment.cc",
         "debug/alias.cc",
         "debug/asan_invalid_access.cc",
         "debug/asan_service.cc",
@@ -1306,11 +1511,13 @@
         "profiler/stack_sampling_profiler.cc",
         "profiler/stack_unwind_data.cc",
         "profiler/thread_delegate_posix.cc",
+        "profiler/thread_group_profiler.cc",
         "profiler/unwinder.cc",
         "rand_util.cc",
         "rand_util_posix.cc",
         "run_loop.cc",
         "sampling_heap_profiler/lock_free_address_hash_set.cc",
+        "sampling_heap_profiler/lock_free_bloom_filter.cc",
         "sampling_heap_profiler/poisson_allocation_sampler.cc",
         "sampling_heap_profiler/sampling_heap_profiler.cc",
         "scoped_add_feature_flags.cc",
@@ -1462,6 +1669,7 @@
         "token.cc",
         "trace_event/heap_profiler_allocation_context.cc",
         "trace_event/heap_profiler_allocation_context_tracker.cc",
+        "trace_event/histogram_scope.cc",
         "trace_event/memory_allocator_dump_guid.cc",
         "trace_event/named_trigger.cc",
         "trace_event/trace_event_stub.cc",
@@ -1539,9 +1747,9 @@
     ],
     cflags: [
         "-DBASE_IMPLEMENTATION",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.130/include/cxx.h\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.146/include/cxx.h\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE",
         "-DIS_RAW_PTR_IMPL",
@@ -1602,8 +1810,10 @@
             srcs: [
                 "android/android_hardware_buffer_compat.cc",
                 "android/android_image_reader_compat.cc",
+                "android/android_info.cc",
                 "android/android_input_receiver_compat.cc",
                 "android/apk_assets.cc",
+                "android/apk_info.cc",
                 "android/application_status_listener.cc",
                 "android/base_feature_map.cc",
                 "android/base_jni_onload.cc",
@@ -1616,6 +1826,7 @@
                 "android/command_line_android.cc",
                 "android/content_uri_utils.cc",
                 "android/cpu_features.cc",
+                "android/device_info.cc",
                 "android/early_trace_event_binding.cc",
                 "android/event_log.cc",
                 "android/feature_list_jni.cc",
@@ -1633,6 +1844,7 @@
                 "android/jni_android.cc",
                 "android/jni_array.cc",
                 "android/jni_bytebuffer.cc",
+                "android/jni_callback.cc",
                 "android/jni_registrar.cc",
                 "android/jni_string.cc",
                 "android/jni_utils.cc",
@@ -1652,6 +1864,7 @@
                 "android/radio_utils.cc",
                 "android/scoped_hardware_buffer_fence_sync.cc",
                 "android/scoped_hardware_buffer_handle.cc",
+                "android/scoped_input_event.cc",
                 "android/shared_preferences/shared_preferences_manager.cc",
                 "android/statistics_recorder_android.cc",
                 "android/sys_utils.cc",
@@ -1678,7 +1891,6 @@
                 "system/sys_info_android.cc",
                 "threading/platform_thread_android.cc",
                 "time/time_android.cc",
-                "trace_event/cfi_backtrace_android.cc",
             ],
             shared_libs: [
                 "liblog",
@@ -1694,9 +1906,12 @@
                 "external/cronet/tot/third_party/cpu_features/src/ndk_compat/",
             ],
             generated_headers: [
+                "tot_cronet_base_android_info_jni__action__testing",
                 "tot_cronet_base_android_runtime_jni_headers__action__testing",
                 "tot_cronet_base_base_jni__action__testing",
+                "tot_cronet_base_base_minimal_jni__action__testing",
                 "tot_cronet_base_base_shared_preferences_jni__action__testing",
+                "tot_cronet_base_build_info_jni__action__testing",
                 "tot_cronet_base_callback_jni__action__testing",
                 "tot_cronet_base_command_line_jni__action__testing",
                 "tot_cronet_base_content_uri_utils_jni__action__testing",
@@ -1707,6 +1922,7 @@
                 "tot_cronet_base_process_launcher_jni__action__testing",
                 "tot_cronet_base_sys_utils_jni__action__testing",
                 "tot_cronet_base_tasks_jni__action__testing",
+                "tot_cronet_base_tasks_minimal_jni__action__testing",
                 "tot_cronet_build_robolectric_buildflags__testing",
                 "tot_cronet_third_party_jni_zero_generate_jni__action__testing",
                 "tot_cronet_third_party_jni_zero_system_jni__action__testing",
@@ -1716,8 +1932,10 @@
             srcs: [
                 "android/android_hardware_buffer_compat.cc",
                 "android/android_image_reader_compat.cc",
+                "android/android_info.cc",
                 "android/android_input_receiver_compat.cc",
                 "android/apk_assets.cc",
+                "android/apk_info.cc",
                 "android/application_status_listener.cc",
                 "android/base_feature_map.cc",
                 "android/base_jni_onload.cc",
@@ -1730,6 +1948,7 @@
                 "android/command_line_android.cc",
                 "android/content_uri_utils.cc",
                 "android/cpu_features.cc",
+                "android/device_info.cc",
                 "android/early_trace_event_binding.cc",
                 "android/event_log.cc",
                 "android/feature_list_jni.cc",
@@ -1747,6 +1966,7 @@
                 "android/jni_android.cc",
                 "android/jni_array.cc",
                 "android/jni_bytebuffer.cc",
+                "android/jni_callback.cc",
                 "android/jni_registrar.cc",
                 "android/jni_string.cc",
                 "android/jni_utils.cc",
@@ -1766,6 +1986,7 @@
                 "android/radio_utils.cc",
                 "android/scoped_hardware_buffer_fence_sync.cc",
                 "android/scoped_hardware_buffer_handle.cc",
+                "android/scoped_input_event.cc",
                 "android/shared_preferences/shared_preferences_manager.cc",
                 "android/statistics_recorder_android.cc",
                 "android/sys_utils.cc",
@@ -1809,9 +2030,12 @@
                 "external/cronet/tot/third_party/cpu_features/src/ndk_compat/",
             ],
             generated_headers: [
+                "tot_cronet_base_android_info_jni__action__testing",
                 "tot_cronet_base_android_runtime_jni_headers__action__testing",
                 "tot_cronet_base_base_jni__action__testing",
+                "tot_cronet_base_base_minimal_jni__action__testing",
                 "tot_cronet_base_base_shared_preferences_jni__action__testing",
+                "tot_cronet_base_build_info_jni__action__testing",
                 "tot_cronet_base_callback_jni__action__testing",
                 "tot_cronet_base_command_line_jni__action__testing",
                 "tot_cronet_base_content_uri_utils_jni__action__testing",
@@ -1822,6 +2046,7 @@
                 "tot_cronet_base_process_launcher_jni__action__testing",
                 "tot_cronet_base_sys_utils_jni__action__testing",
                 "tot_cronet_base_tasks_jni__action__testing",
+                "tot_cronet_base_tasks_minimal_jni__action__testing",
                 "tot_cronet_build_robolectric_buildflags__testing",
                 "tot_cronet_third_party_jni_zero_generate_jni__action__testing",
                 "tot_cronet_third_party_jni_zero_system_jni__action__testing",
@@ -1831,8 +2056,10 @@
             srcs: [
                 "android/android_hardware_buffer_compat.cc",
                 "android/android_image_reader_compat.cc",
+                "android/android_info.cc",
                 "android/android_input_receiver_compat.cc",
                 "android/apk_assets.cc",
+                "android/apk_info.cc",
                 "android/application_status_listener.cc",
                 "android/base_feature_map.cc",
                 "android/base_jni_onload.cc",
@@ -1845,6 +2072,7 @@
                 "android/command_line_android.cc",
                 "android/content_uri_utils.cc",
                 "android/cpu_features.cc",
+                "android/device_info.cc",
                 "android/early_trace_event_binding.cc",
                 "android/event_log.cc",
                 "android/feature_list_jni.cc",
@@ -1862,6 +2090,7 @@
                 "android/jni_android.cc",
                 "android/jni_array.cc",
                 "android/jni_bytebuffer.cc",
+                "android/jni_callback.cc",
                 "android/jni_registrar.cc",
                 "android/jni_string.cc",
                 "android/jni_utils.cc",
@@ -1881,6 +2110,7 @@
                 "android/radio_utils.cc",
                 "android/scoped_hardware_buffer_fence_sync.cc",
                 "android/scoped_hardware_buffer_handle.cc",
+                "android/scoped_input_event.cc",
                 "android/shared_preferences/shared_preferences_manager.cc",
                 "android/statistics_recorder_android.cc",
                 "android/sys_utils.cc",
@@ -1919,9 +2149,12 @@
                 "external/cronet/tot/third_party/cpu_features/src/ndk_compat/",
             ],
             generated_headers: [
+                "tot_cronet_base_android_info_jni__action__testing",
                 "tot_cronet_base_android_runtime_jni_headers__action__testing",
                 "tot_cronet_base_base_jni__action__testing",
+                "tot_cronet_base_base_minimal_jni__action__testing",
                 "tot_cronet_base_base_shared_preferences_jni__action__testing",
+                "tot_cronet_base_build_info_jni__action__testing",
                 "tot_cronet_base_callback_jni__action__testing",
                 "tot_cronet_base_command_line_jni__action__testing",
                 "tot_cronet_base_content_uri_utils_jni__action__testing",
@@ -1932,6 +2165,7 @@
                 "tot_cronet_base_process_launcher_jni__action__testing",
                 "tot_cronet_base_sys_utils_jni__action__testing",
                 "tot_cronet_base_tasks_jni__action__testing",
+                "tot_cronet_base_tasks_minimal_jni__action__testing",
                 "tot_cronet_build_robolectric_buildflags__testing",
                 "tot_cronet_third_party_jni_zero_generate_jni__action__testing",
                 "tot_cronet_third_party_jni_zero_system_jni__action__testing",
@@ -1941,8 +2175,10 @@
             srcs: [
                 "android/android_hardware_buffer_compat.cc",
                 "android/android_image_reader_compat.cc",
+                "android/android_info.cc",
                 "android/android_input_receiver_compat.cc",
                 "android/apk_assets.cc",
+                "android/apk_info.cc",
                 "android/application_status_listener.cc",
                 "android/base_feature_map.cc",
                 "android/base_jni_onload.cc",
@@ -1955,6 +2191,7 @@
                 "android/command_line_android.cc",
                 "android/content_uri_utils.cc",
                 "android/cpu_features.cc",
+                "android/device_info.cc",
                 "android/early_trace_event_binding.cc",
                 "android/event_log.cc",
                 "android/feature_list_jni.cc",
@@ -1972,6 +2209,7 @@
                 "android/jni_android.cc",
                 "android/jni_array.cc",
                 "android/jni_bytebuffer.cc",
+                "android/jni_callback.cc",
                 "android/jni_registrar.cc",
                 "android/jni_string.cc",
                 "android/jni_utils.cc",
@@ -1991,6 +2229,7 @@
                 "android/radio_utils.cc",
                 "android/scoped_hardware_buffer_fence_sync.cc",
                 "android/scoped_hardware_buffer_handle.cc",
+                "android/scoped_input_event.cc",
                 "android/shared_preferences/shared_preferences_manager.cc",
                 "android/statistics_recorder_android.cc",
                 "android/sys_utils.cc",
@@ -2031,9 +2270,12 @@
                 "external/cronet/tot/third_party/cpu_features/src/ndk_compat/",
             ],
             generated_headers: [
+                "tot_cronet_base_android_info_jni__action__testing",
                 "tot_cronet_base_android_runtime_jni_headers__action__testing",
                 "tot_cronet_base_base_jni__action__testing",
+                "tot_cronet_base_base_minimal_jni__action__testing",
                 "tot_cronet_base_base_shared_preferences_jni__action__testing",
+                "tot_cronet_base_build_info_jni__action__testing",
                 "tot_cronet_base_callback_jni__action__testing",
                 "tot_cronet_base_command_line_jni__action__testing",
                 "tot_cronet_base_content_uri_utils_jni__action__testing",
@@ -2044,6 +2286,7 @@
                 "tot_cronet_base_process_launcher_jni__action__testing",
                 "tot_cronet_base_sys_utils_jni__action__testing",
                 "tot_cronet_base_tasks_jni__action__testing",
+                "tot_cronet_base_tasks_minimal_jni__action__testing",
                 "tot_cronet_build_robolectric_buildflags__testing",
                 "tot_cronet_third_party_jni_zero_generate_jni__action__testing",
                 "tot_cronet_third_party_jni_zero_system_jni__action__testing",
@@ -2053,8 +2296,10 @@
             srcs: [
                 "android/android_hardware_buffer_compat.cc",
                 "android/android_image_reader_compat.cc",
+                "android/android_info.cc",
                 "android/android_input_receiver_compat.cc",
                 "android/apk_assets.cc",
+                "android/apk_info.cc",
                 "android/application_status_listener.cc",
                 "android/base_feature_map.cc",
                 "android/base_jni_onload.cc",
@@ -2067,6 +2312,7 @@
                 "android/command_line_android.cc",
                 "android/content_uri_utils.cc",
                 "android/cpu_features.cc",
+                "android/device_info.cc",
                 "android/early_trace_event_binding.cc",
                 "android/event_log.cc",
                 "android/feature_list_jni.cc",
@@ -2084,6 +2330,7 @@
                 "android/jni_android.cc",
                 "android/jni_array.cc",
                 "android/jni_bytebuffer.cc",
+                "android/jni_callback.cc",
                 "android/jni_registrar.cc",
                 "android/jni_string.cc",
                 "android/jni_utils.cc",
@@ -2103,6 +2350,7 @@
                 "android/radio_utils.cc",
                 "android/scoped_hardware_buffer_fence_sync.cc",
                 "android/scoped_hardware_buffer_handle.cc",
+                "android/scoped_input_event.cc",
                 "android/shared_preferences/shared_preferences_manager.cc",
                 "android/statistics_recorder_android.cc",
                 "android/sys_utils.cc",
@@ -2143,9 +2391,12 @@
                 "external/cronet/tot/third_party/cpu_features/src/ndk_compat/",
             ],
             generated_headers: [
+                "tot_cronet_base_android_info_jni__action__testing",
                 "tot_cronet_base_android_runtime_jni_headers__action__testing",
                 "tot_cronet_base_base_jni__action__testing",
+                "tot_cronet_base_base_minimal_jni__action__testing",
                 "tot_cronet_base_base_shared_preferences_jni__action__testing",
+                "tot_cronet_base_build_info_jni__action__testing",
                 "tot_cronet_base_callback_jni__action__testing",
                 "tot_cronet_base_command_line_jni__action__testing",
                 "tot_cronet_base_content_uri_utils_jni__action__testing",
@@ -2156,6 +2407,7 @@
                 "tot_cronet_base_process_launcher_jni__action__testing",
                 "tot_cronet_base_sys_utils_jni__action__testing",
                 "tot_cronet_base_tasks_jni__action__testing",
+                "tot_cronet_base_tasks_minimal_jni__action__testing",
                 "tot_cronet_build_robolectric_buildflags__testing",
                 "tot_cronet_third_party_jni_zero_generate_jni__action__testing",
                 "tot_cronet_third_party_jni_zero_system_jni__action__testing",
@@ -2171,6 +2423,7 @@
                 "power_monitor/power_monitor_device_source_stub.cc",
                 "process/process_linux.cc",
                 "process/set_process_title_linux.cc",
+                "profiler/core_unwinders_posix.cc",
                 "profiler/stack_sampler_posix.cc",
                 "stack_canary_linux.cc",
                 "threading/platform_thread_linux.cc",
@@ -2178,7 +2431,7 @@
                 "threading/thread_type_delegate.cc",
             ],
             cflags: [
-                "-DCR_SYSROOT_KEY=20230611T210420Z-2",
+                "-DCR_SYSROOT_KEY=20250129T203412Z-1",
                 "-DNO_UNWIND_TABLES",
                 "-DUSE_AURA=1",
                 "-DUSE_OZONE=1",
@@ -2195,13 +2448,71 @@
     },
 }
 
-// GN: //base:base_cached_flags_java__testing
+// GN: //base:base_cached_flags_java__compile_java__testing
 java_library {
-    name: "tot_cronet_base_base_cached_flags_java__testing",
+    name: "tot_cronet_base_base_cached_flags_java__compile_java__testing",
     srcs: [
         "android/java/src/org/chromium/base/cached_flags/ValuesReturned.java",
     ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_android_info_java__compile_java__testing",
+        "tot_cronet_base_android_runtime_jni_headers_java__testing",
+        "tot_cronet_base_base_java__compile_java__testing",
+        "tot_cronet_base_base_jni_java__compile_java__testing",
+        "tot_cronet_base_base_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_base_shared_preferences_java__compile_java__testing",
+        "tot_cronet_base_base_shared_preferences_jni_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_build_info_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_jank_tracker_java__compile_java__testing",
+        "tot_cronet_base_library_loader_java__compile_java__testing",
+        "tot_cronet_base_library_loader_jni_java__compile_java__testing",
+        "tot_cronet_base_lifetime_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_memory_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_promise_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_stream_util_java__compile_java__testing",
+        "tot_cronet_base_supplier_java__compile_java__testing",
+        "tot_cronet_base_sys_utils_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_base_unowned_user_data_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_channel_enum_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_version_constants_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_cached_flags_java__testing
+java_library {
+    name: "tot_cronet_base_base_cached_flags_java__testing",
     static_libs: [
+        "tot_cronet_base_base_cached_flags_java__process_device__testing",
         "tot_cronet_base_base_java__testing",
         "tot_cronet_base_base_shared_preferences_java__testing",
         "tot_cronet_build_android_build_java__testing",
@@ -2217,73 +2528,20 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
 // GN: //base:base_java
 java_library {
     name: "tot_cronet_base_base_java",
-    srcs: [
-        ":tot_cronet_base_base_android_java_enums_srcjar",
-        ":tot_cronet_base_base_jni__action__java",
-        ":tot_cronet_base_java_features_srcjar",
-        "android/java/src/org/chromium/base/ApkAssets.java",
-        "android/java/src/org/chromium/base/BaseFeatureMap.java",
-        "android/java/src/org/chromium/base/BinderCallsListener.java",
-        "android/java/src/org/chromium/base/BuildInfo.java",
-        "android/java/src/org/chromium/base/BundleUtils.java",
-        "android/java/src/org/chromium/base/CallbackController.java",
-        "android/java/src/org/chromium/base/CollectionUtil.java",
-        "android/java/src/org/chromium/base/CommandLineInitUtil.java",
-        "android/java/src/org/chromium/base/CpuFeatures.java",
-        "android/java/src/org/chromium/base/DiscardableReferencePool.java",
-        "android/java/src/org/chromium/base/EventLog.java",
-        "android/java/src/org/chromium/base/FeatureList.java",
-        "android/java/src/org/chromium/base/FeatureMap.java",
-        "android/java/src/org/chromium/base/FeatureParam.java",
-        "android/java/src/org/chromium/base/Features.java",
-        "android/java/src/org/chromium/base/FieldTrialList.java",
-        "android/java/src/org/chromium/base/FileProviderUtils.java",
-        "android/java/src/org/chromium/base/FileUtils.java",
-        "android/java/src/org/chromium/base/Flag.java",
-        "android/java/src/org/chromium/base/ImportantFileWriterAndroid.java",
-        "android/java/src/org/chromium/base/InputHintChecker.java",
-        "android/java/src/org/chromium/base/IntStringCallback.java",
-        "android/java/src/org/chromium/base/IntentUtils.java",
-        "android/java/src/org/chromium/base/JNIUtils.java",
-        "android/java/src/org/chromium/base/JavaExceptionReporter.java",
-        "android/java/src/org/chromium/base/JavaHandlerThread.java",
-        "android/java/src/org/chromium/base/JniAndroid.java",
-        "android/java/src/org/chromium/base/LocaleUtils.java",
-        "android/java/src/org/chromium/base/MathUtils.java",
-        "android/java/src/org/chromium/base/MutableBooleanParamWithSafeDefault.java",
-        "android/java/src/org/chromium/base/MutableFlagWithSafeDefault.java",
-        "android/java/src/org/chromium/base/MutableIntParamWithSafeDefault.java",
-        "android/java/src/org/chromium/base/MutableParamWithSafeDefault.java",
-        "android/java/src/org/chromium/base/PackageManagerUtils.java",
-        "android/java/src/org/chromium/base/PackageUtils.java",
-        "android/java/src/org/chromium/base/PathService.java",
-        "android/java/src/org/chromium/base/PathUtils.java",
-        "android/java/src/org/chromium/base/PiiElider.java",
-        "android/java/src/org/chromium/base/PostNativeFlag.java",
-        "android/java/src/org/chromium/base/PowerMonitor.java",
-        "android/java/src/org/chromium/base/PowerMonitorForQ.java",
-        "android/java/src/org/chromium/base/RadioUtils.java",
-        "android/java/src/org/chromium/base/RequiredCallback.java",
-        "android/java/src/org/chromium/base/TimezoneUtils.java",
-        "android/java/src/org/chromium/base/Token.java",
-        "android/java/src/org/chromium/base/TokenBase.java",
-        "android/java/src/org/chromium/base/UnguessableToken.java",
-        "android/java/src/org/chromium/base/UserData.java",
-        "android/java/src/org/chromium/base/UserDataHost.java",
-        "android/java/src/org/chromium/base/ValueChangedCallback.java",
-        "android/java/src/org/chromium/base/WrappedClassLoader.java",
-        "test/android/javatests/src/stub/org/chromium/base/test/ClangProfiler.java",
-    ],
     static_libs: [
         "jsr305",
         "tot_cronet_base_activity_state_java",
+        "tot_cronet_base_android_info_java",
+        "tot_cronet_base_base_java__process_device",
+        "tot_cronet_base_base_jni_java",
+        "tot_cronet_base_base_minimal_jni_java",
         "tot_cronet_base_base_switches_java",
+        "tot_cronet_base_build_info_java",
         "tot_cronet_base_callback_java",
         "tot_cronet_base_command_line_java",
         "tot_cronet_base_jank_tracker_java",
@@ -2300,6 +2558,7 @@
         "tot_cronet_base_tasks_java",
         "tot_cronet_base_time_utils_java",
         "tot_cronet_base_unowned_user_data_java",
+        "tot_cronet_base_version_info_android_version_constants_java",
         "tot_cronet_build_android_build_java",
         "tot_cronet_third_party_jni_zero_jni_zero_java",
     ],
@@ -2318,22 +2577,20 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
-// GN: //base:base_java__testing
+// GN: //base:base_java__compile_java
 java_library {
-    name: "tot_cronet_base_base_java__testing",
+    name: "tot_cronet_base_base_java__compile_java",
     srcs: [
-        ":tot_cronet_base_base_android_java_enums_srcjar__testing",
-        ":tot_cronet_base_base_jni__action__testing__java",
-        ":tot_cronet_base_java_features_srcjar__testing",
+        ":tot_cronet_base_base_android_java_enums_srcjar",
+        ":tot_cronet_base_java_features_srcjar",
         "android/java/src/org/chromium/base/ApkAssets.java",
         "android/java/src/org/chromium/base/BaseFeatureMap.java",
         "android/java/src/org/chromium/base/BinderCallsListener.java",
-        "android/java/src/org/chromium/base/BuildInfo.java",
         "android/java/src/org/chromium/base/BundleUtils.java",
         "android/java/src/org/chromium/base/CallbackController.java",
+        "android/java/src/org/chromium/base/CancelableRunnable.java",
         "android/java/src/org/chromium/base/CollectionUtil.java",
         "android/java/src/org/chromium/base/CommandLineInitUtil.java",
         "android/java/src/org/chromium/base/CpuFeatures.java",
@@ -2341,6 +2598,7 @@
         "android/java/src/org/chromium/base/EventLog.java",
         "android/java/src/org/chromium/base/FeatureList.java",
         "android/java/src/org/chromium/base/FeatureMap.java",
+        "android/java/src/org/chromium/base/FeatureOverrides.java",
         "android/java/src/org/chromium/base/FeatureParam.java",
         "android/java/src/org/chromium/base/Features.java",
         "android/java/src/org/chromium/base/FieldTrialList.java",
@@ -2355,6 +2613,9 @@
         "android/java/src/org/chromium/base/JavaExceptionReporter.java",
         "android/java/src/org/chromium/base/JavaHandlerThread.java",
         "android/java/src/org/chromium/base/JniAndroid.java",
+        "android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "android/java/src/org/chromium/base/JniOnceCallback.java",
+        "android/java/src/org/chromium/base/JniRepeatingCallback.java",
         "android/java/src/org/chromium/base/LocaleUtils.java",
         "android/java/src/org/chromium/base/MathUtils.java",
         "android/java/src/org/chromium/base/MutableBooleanParamWithSafeDefault.java",
@@ -2362,7 +2623,6 @@
         "android/java/src/org/chromium/base/MutableIntParamWithSafeDefault.java",
         "android/java/src/org/chromium/base/MutableParamWithSafeDefault.java",
         "android/java/src/org/chromium/base/PackageManagerUtils.java",
-        "android/java/src/org/chromium/base/PackageUtils.java",
         "android/java/src/org/chromium/base/PathService.java",
         "android/java/src/org/chromium/base/PathUtils.java",
         "android/java/src/org/chromium/base/PiiElider.java",
@@ -2383,8 +2643,188 @@
     ],
     static_libs: [
         "jsr305",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java",
+        "tot_cronet_base_android_info_java__compile_java",
+        "tot_cronet_base_android_runtime_jni_headers_java",
+        "tot_cronet_base_base_jni_java__compile_java",
+        "tot_cronet_base_base_minimal_jni_java__compile_java",
+        "tot_cronet_base_base_switches_java__compile_java",
+        "tot_cronet_base_build_info_java__compile_java",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_base_command_line_java__compile_java",
+        "tot_cronet_base_command_line_jni_java__compile_java",
+        "tot_cronet_base_jank_tracker_java__compile_java",
+        "tot_cronet_base_library_loader_java__compile_java",
+        "tot_cronet_base_library_loader_jni_java__compile_java",
+        "tot_cronet_base_lifetime_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_memory_java__compile_java",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+        "tot_cronet_base_metrics_java__compile_java",
+        "tot_cronet_base_metrics_jni_java__compile_java",
+        "tot_cronet_base_promise_java__compile_java",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_base_stream_util_java__compile_java",
+        "tot_cronet_base_supplier_java__compile_java",
+        "tot_cronet_base_sys_utils_java__compile_java",
+        "tot_cronet_base_tasks_java__compile_java",
+        "tot_cronet_base_tasks_jni_java__compile_java",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java",
+        "tot_cronet_base_time_utils_java__compile_java",
+        "tot_cronet_base_unowned_user_data_java__compile_java",
+        "tot_cronet_base_version_info_android_channel_enum_java__compile_java",
+        "tot_cronet_base_version_info_android_version_constants_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_base_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_base_android_java_enums_srcjar__testing",
+        ":tot_cronet_base_java_features_srcjar__testing",
+        "android/java/src/org/chromium/base/ApkAssets.java",
+        "android/java/src/org/chromium/base/BaseFeatureMap.java",
+        "android/java/src/org/chromium/base/BinderCallsListener.java",
+        "android/java/src/org/chromium/base/BundleUtils.java",
+        "android/java/src/org/chromium/base/CallbackController.java",
+        "android/java/src/org/chromium/base/CancelableRunnable.java",
+        "android/java/src/org/chromium/base/CollectionUtil.java",
+        "android/java/src/org/chromium/base/CommandLineInitUtil.java",
+        "android/java/src/org/chromium/base/CpuFeatures.java",
+        "android/java/src/org/chromium/base/DiscardableReferencePool.java",
+        "android/java/src/org/chromium/base/EventLog.java",
+        "android/java/src/org/chromium/base/FeatureList.java",
+        "android/java/src/org/chromium/base/FeatureMap.java",
+        "android/java/src/org/chromium/base/FeatureOverrides.java",
+        "android/java/src/org/chromium/base/FeatureParam.java",
+        "android/java/src/org/chromium/base/Features.java",
+        "android/java/src/org/chromium/base/FieldTrialList.java",
+        "android/java/src/org/chromium/base/FileProviderUtils.java",
+        "android/java/src/org/chromium/base/FileUtils.java",
+        "android/java/src/org/chromium/base/Flag.java",
+        "android/java/src/org/chromium/base/ImportantFileWriterAndroid.java",
+        "android/java/src/org/chromium/base/InputHintChecker.java",
+        "android/java/src/org/chromium/base/IntStringCallback.java",
+        "android/java/src/org/chromium/base/IntentUtils.java",
+        "android/java/src/org/chromium/base/JNIUtils.java",
+        "android/java/src/org/chromium/base/JavaExceptionReporter.java",
+        "android/java/src/org/chromium/base/JavaHandlerThread.java",
+        "android/java/src/org/chromium/base/JniAndroid.java",
+        "android/java/src/org/chromium/base/JniCallbackUtils.java",
+        "android/java/src/org/chromium/base/JniOnceCallback.java",
+        "android/java/src/org/chromium/base/JniRepeatingCallback.java",
+        "android/java/src/org/chromium/base/LocaleUtils.java",
+        "android/java/src/org/chromium/base/MathUtils.java",
+        "android/java/src/org/chromium/base/MutableBooleanParamWithSafeDefault.java",
+        "android/java/src/org/chromium/base/MutableFlagWithSafeDefault.java",
+        "android/java/src/org/chromium/base/MutableIntParamWithSafeDefault.java",
+        "android/java/src/org/chromium/base/MutableParamWithSafeDefault.java",
+        "android/java/src/org/chromium/base/PackageManagerUtils.java",
+        "android/java/src/org/chromium/base/PathService.java",
+        "android/java/src/org/chromium/base/PathUtils.java",
+        "android/java/src/org/chromium/base/PiiElider.java",
+        "android/java/src/org/chromium/base/PostNativeFlag.java",
+        "android/java/src/org/chromium/base/PowerMonitor.java",
+        "android/java/src/org/chromium/base/PowerMonitorForQ.java",
+        "android/java/src/org/chromium/base/RadioUtils.java",
+        "android/java/src/org/chromium/base/RequiredCallback.java",
+        "android/java/src/org/chromium/base/TimezoneUtils.java",
+        "android/java/src/org/chromium/base/Token.java",
+        "android/java/src/org/chromium/base/TokenBase.java",
+        "android/java/src/org/chromium/base/UnguessableToken.java",
+        "android/java/src/org/chromium/base/UserData.java",
+        "android/java/src/org/chromium/base/UserDataHost.java",
+        "android/java/src/org/chromium/base/ValueChangedCallback.java",
+        "android/java/src/org/chromium/base/WrappedClassLoader.java",
+        "test/android/javatests/src/stub/org/chromium/base/test/ClangProfiler.java",
+    ],
+    static_libs: [
+        "jsr305",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_android_info_java__compile_java__testing",
+        "tot_cronet_base_android_runtime_jni_headers_java__testing",
+        "tot_cronet_base_base_jni_java__compile_java__testing",
+        "tot_cronet_base_base_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_build_info_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_jank_tracker_java__compile_java__testing",
+        "tot_cronet_base_library_loader_java__compile_java__testing",
+        "tot_cronet_base_library_loader_jni_java__compile_java__testing",
+        "tot_cronet_base_lifetime_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_memory_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_promise_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_stream_util_java__compile_java__testing",
+        "tot_cronet_base_supplier_java__compile_java__testing",
+        "tot_cronet_base_sys_utils_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_base_unowned_user_data_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_channel_enum_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_version_constants_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_java__testing
+java_library {
+    name: "tot_cronet_base_base_java__testing",
+    static_libs: [
+        "jsr305",
         "tot_cronet_base_activity_state_java__testing",
+        "tot_cronet_base_android_info_java__testing",
+        "tot_cronet_base_base_java__process_device__testing",
+        "tot_cronet_base_base_jni_java__testing",
+        "tot_cronet_base_base_minimal_jni_java__testing",
         "tot_cronet_base_base_switches_java__testing",
+        "tot_cronet_base_build_info_java__testing",
         "tot_cronet_base_callback_java__testing",
         "tot_cronet_base_command_line_java__testing",
         "tot_cronet_base_jank_tracker_java__testing",
@@ -2401,6 +2841,7 @@
         "tot_cronet_base_tasks_java__testing",
         "tot_cronet_base_time_utils_java__testing",
         "tot_cronet_base_unowned_user_data_java__testing",
+        "tot_cronet_base_version_info_android_version_constants_java__testing",
         "tot_cronet_build_android_build_java__testing",
         "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
     ],
@@ -2417,12 +2858,11 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
-// GN: //base:base_java_test_support__testing
+// GN: //base:base_java_test_support__compile_java__testing
 java_library {
-    name: "tot_cronet_base_base_java_test_support__testing",
+    name: "tot_cronet_base_base_java_test_support__compile_java__testing",
     srcs: [
         "test/android/javatests/src/org/chromium/base/test/ActivityFinisher.java",
         "test/android/javatests/src/org/chromium/base/test/BaseChromiumAndroidJUnitRunner.java",
@@ -2505,8 +2945,83 @@
         "hamcrest-library",
         "jsr305",
         "junit",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "android.test.mock.stubs",
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "androidx.core_core",
+        "androidx.test.monitor",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_android_info_java__compile_java__testing",
+        "tot_cronet_base_android_runtime_jni_headers_java__testing",
+        "tot_cronet_base_base_cached_flags_java__compile_java__testing",
+        "tot_cronet_base_base_java__compile_java__testing",
+        "tot_cronet_base_base_java_url_utils_for_test__compile_java__testing",
+        "tot_cronet_base_base_jni_java__compile_java__testing",
+        "tot_cronet_base_base_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_base_shared_preferences_java__compile_java__testing",
+        "tot_cronet_base_base_shared_preferences_jni_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_build_info_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_jank_tracker_java__compile_java__testing",
+        "tot_cronet_base_library_loader_java__compile_java__testing",
+        "tot_cronet_base_library_loader_jni_java__compile_java__testing",
+        "tot_cronet_base_lifetime_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_memory_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_promise_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_stream_util_java__compile_java__testing",
+        "tot_cronet_base_supplier_java__compile_java__testing",
+        "tot_cronet_base_sys_utils_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_base_unowned_user_data_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_channel_enum_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_version_constants_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_testing_android_instrumentation_test_runner_java__compile_java__testing",
+        "tot_cronet_testing_android_instrumentation_test_runner_permissions_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_java_test_support__testing
+java_library {
+    name: "tot_cronet_base_base_java_test_support__testing",
+    static_libs: [
+        "androidx.test.espresso.contrib",
+        "androidx.test.runner",
+        "androidx.test.uiautomator_uiautomator",
+        "guava",
+        "hamcrest",
+        "hamcrest-library",
+        "jsr305",
+        "junit",
         "tot_cronet_base_base_cached_flags_java__testing",
         "tot_cronet_base_base_java__testing",
+        "tot_cronet_base_base_java_test_support__process_device__testing",
         "tot_cronet_base_base_java_url_utils_for_test__testing",
         "tot_cronet_base_tasks_java__testing",
         "tot_cronet_build_android_build_java__testing",
@@ -2527,7 +3042,6 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
     errorprone: {
         javacflags: [
             "-Xep:ReturnValueIgnored:WARN",
@@ -2535,15 +3049,74 @@
     },
 }
 
-// GN: //base:base_java_url_utils_for_test__testing
+// GN: //base:base_java_url_utils_for_test__compile_java__testing
 java_library {
-    name: "tot_cronet_base_base_java_url_utils_for_test__testing",
+    name: "tot_cronet_base_base_java_url_utils_for_test__compile_java__testing",
     srcs: [
         "test/android/javatests/src/org/chromium/base/test/util/UrlUtils.java",
     ],
     static_libs: [
         "junit",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_android_info_java__compile_java__testing",
+        "tot_cronet_base_android_runtime_jni_headers_java__testing",
+        "tot_cronet_base_base_java__compile_java__testing",
+        "tot_cronet_base_base_jni_java__compile_java__testing",
+        "tot_cronet_base_base_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_build_info_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_jank_tracker_java__compile_java__testing",
+        "tot_cronet_base_library_loader_java__compile_java__testing",
+        "tot_cronet_base_library_loader_jni_java__compile_java__testing",
+        "tot_cronet_base_lifetime_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_memory_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_promise_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_stream_util_java__compile_java__testing",
+        "tot_cronet_base_supplier_java__compile_java__testing",
+        "tot_cronet_base_sys_utils_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_base_unowned_user_data_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_channel_enum_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_version_constants_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_java_url_utils_for_test__testing
+java_library {
+    name: "tot_cronet_base_base_java_url_utils_for_test__testing",
+    static_libs: [
+        "junit",
         "tot_cronet_base_base_java__testing",
+        "tot_cronet_base_base_java_url_utils_for_test__process_device__testing",
         "tot_cronet_build_android_build_java__testing",
         "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
     ],
@@ -2558,12 +3131,183 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
-// GN: //base:base_shared_preferences_java__testing
+// GN: //base:base_jni_java
 java_library {
-    name: "tot_cronet_base_base_shared_preferences_java__testing",
+    name: "tot_cronet_base_base_jni_java",
+    static_libs: [
+        "tot_cronet_base_android_runtime_jni_headers_java",
+        "tot_cronet_base_base_jni_java__process_device",
+        "tot_cronet_base_base_minimal_jni_java",
+        "tot_cronet_build_android_build_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_jni_java__compile_java
+java_library {
+    name: "tot_cronet_base_base_jni_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_base_jni__action__java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_base_android_runtime_jni_headers_java",
+        "tot_cronet_base_base_minimal_jni_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_jni_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_base_jni_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_base_jni__action__testing__java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_base_android_runtime_jni_headers_java__testing",
+        "tot_cronet_base_base_minimal_jni_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_jni_java__testing
+java_library {
+    name: "tot_cronet_base_base_jni_java__testing",
+    static_libs: [
+        "tot_cronet_base_android_runtime_jni_headers_java__testing",
+        "tot_cronet_base_base_jni_java__process_device__testing",
+        "tot_cronet_base_base_minimal_jni_java__testing",
+        "tot_cronet_build_android_build_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_minimal_jni_java
+java_library {
+    name: "tot_cronet_base_base_minimal_jni_java",
+    static_libs: [
+        "tot_cronet_base_android_runtime_jni_headers_java",
+        "tot_cronet_base_base_minimal_jni_java__process_device",
+        "tot_cronet_build_android_build_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_minimal_jni_java__compile_java
+java_library {
+    name: "tot_cronet_base_base_minimal_jni_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_base_minimal_jni__action__java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_base_android_runtime_jni_headers_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_minimal_jni_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_base_minimal_jni_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_base_minimal_jni__action__testing__java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_base_android_runtime_jni_headers_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_minimal_jni_java__testing
+java_library {
+    name: "tot_cronet_base_base_minimal_jni_java__testing",
+    static_libs: [
+        "tot_cronet_base_android_runtime_jni_headers_java__testing",
+        "tot_cronet_base_base_minimal_jni_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_shared_preferences_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_base_shared_preferences_java__compile_java__testing",
     srcs: [
         "android/java/src/org/chromium/base/shared_preferences/KeyPrefix.java",
         "android/java/src/org/chromium/base/shared_preferences/KnownPreferenceKeyRegistries.java",
@@ -2574,7 +3318,68 @@
     ],
     static_libs: [
         "guava",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_android_info_java__compile_java__testing",
+        "tot_cronet_base_android_runtime_jni_headers_java__testing",
+        "tot_cronet_base_base_java__compile_java__testing",
+        "tot_cronet_base_base_jni_java__compile_java__testing",
+        "tot_cronet_base_base_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_base_shared_preferences_jni_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_build_info_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_jank_tracker_java__compile_java__testing",
+        "tot_cronet_base_library_loader_java__compile_java__testing",
+        "tot_cronet_base_library_loader_jni_java__compile_java__testing",
+        "tot_cronet_base_lifetime_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_memory_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_promise_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_stream_util_java__compile_java__testing",
+        "tot_cronet_base_supplier_java__compile_java__testing",
+        "tot_cronet_base_sys_utils_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_base_unowned_user_data_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_channel_enum_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_version_constants_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_shared_preferences_java__testing
+java_library {
+    name: "tot_cronet_base_base_shared_preferences_java__testing",
+    static_libs: [
+        "guava",
         "tot_cronet_base_base_java__testing",
+        "tot_cronet_base_base_shared_preferences_java__process_device__testing",
+        "tot_cronet_base_base_shared_preferences_jni_java__testing",
         "tot_cronet_build_android_build_java__testing",
         "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
     ],
@@ -2589,7 +3394,44 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:base_shared_preferences_jni_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_base_shared_preferences_jni_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_base_shared_preferences_jni__action__testing__java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_shared_preferences_jni_java__testing
+java_library {
+    name: "tot_cronet_base_base_shared_preferences_jni_java__testing",
+    static_libs: [
+        "tot_cronet_base_base_shared_preferences_jni_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:base_static
@@ -2601,11 +3443,9 @@
     host_cross_supported: false,
     generated_headers: [
         "tot_cronet_base_fuzzing_buildflags",
-        "tot_cronet_build_chromeos_buildflags",
     ],
     export_generated_headers: [
         "tot_cronet_base_fuzzing_buildflags",
-        "tot_cronet_build_chromeos_buildflags",
     ],
     defaults: [
         "tot_cronet_cc_defaults",
@@ -2613,8 +3453,8 @@
     cflags: [
         "-DANDROID",
         "-DANDROID_NDK_VERSION_ROLL=r27_1",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DHAVE_SYS_UIO_H",
         "-DNDEBUG",
@@ -2690,18 +3530,16 @@
     host_cross_supported: false,
     generated_headers: [
         "tot_cronet_base_fuzzing_buildflags__testing",
-        "tot_cronet_build_chromeos_buildflags__testing",
     ],
     export_generated_headers: [
         "tot_cronet_base_fuzzing_buildflags__testing",
-        "tot_cronet_build_chromeos_buildflags__testing",
     ],
     defaults: [
         "tot_cronet_cc_defaults",
     ],
     cflags: [
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DNDEBUG",
         "-DNVALGRIND",
@@ -2788,7 +3626,7 @@
         },
         host: {
             cflags: [
-                "-DCR_SYSROOT_KEY=20230611T210420Z-2",
+                "-DCR_SYSROOT_KEY=20250129T203412Z-1",
                 "-DNO_UNWIND_TABLES",
                 "-DUSE_AURA=1",
                 "-DUSE_OZONE=1",
@@ -2808,8 +3646,9 @@
 // GN: //base:base_switches_java
 java_library {
     name: "tot_cronet_base_base_switches_java",
-    srcs: [
-        ":tot_cronet_base_java_switches_srcjar",
+    static_libs: [
+        "tot_cronet_base_base_switches_java__process_device",
+        "tot_cronet_build_android_build_java",
     ],
     defaults: [
         "tot_cronet_java_framework_defaults",
@@ -2821,14 +3660,54 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:base_switches_java__compile_java
+java_library {
+    name: "tot_cronet_base_base_switches_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_java_switches_srcjar",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:base_switches_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_base_switches_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_java_switches_srcjar__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:base_switches_java__testing
 java_library {
     name: "tot_cronet_base_base_switches_java__testing",
-    srcs: [
-        ":tot_cronet_base_java_switches_srcjar__testing",
+    static_libs: [
+        "tot_cronet_base_base_switches_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
     ],
     apex_available: [
         "com.android.tethering",
@@ -2838,18 +3717,177 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:build_info_java
+java_library {
+    name: "tot_cronet_base_build_info_java",
+    static_libs: [
+        "jsr305",
+        "tot_cronet_base_android_info_java",
+        "tot_cronet_base_base_switches_java",
+        "tot_cronet_base_build_info_java__process_device",
+        "tot_cronet_base_command_line_java",
+        "tot_cronet_base_log_java",
+        "tot_cronet_base_tasks_java",
+        "tot_cronet_base_version_info_android_version_constants_java",
+        "tot_cronet_build_android_build_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:build_info_java__compile_java
+java_library {
+    name: "tot_cronet_base_build_info_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_build_info_jni__action__java_proxy_only",
+        "android/java/src/org/chromium/base/ApkInfo.java",
+        "android/java/src/org/chromium/base/BuildInfo.java",
+        "android/java/src/org/chromium/base/DeviceInfo.java",
+        "android/java/src/org/chromium/base/PackageUtils.java",
+    ],
+    static_libs: [
+        "jsr305",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java",
+        "tot_cronet_base_android_info_java__compile_java",
+        "tot_cronet_base_base_switches_java__compile_java",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_base_command_line_java__compile_java",
+        "tot_cronet_base_command_line_jni_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+        "tot_cronet_base_metrics_java__compile_java",
+        "tot_cronet_base_metrics_jni_java__compile_java",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_base_tasks_java__compile_java",
+        "tot_cronet_base_tasks_jni_java__compile_java",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java",
+        "tot_cronet_base_time_utils_java__compile_java",
+        "tot_cronet_base_version_info_android_channel_enum_java__compile_java",
+        "tot_cronet_base_version_info_android_version_constants_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:build_info_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_build_info_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_build_info_jni__action__testing__java_proxy_only",
+        "android/java/src/org/chromium/base/ApkInfo.java",
+        "android/java/src/org/chromium/base/BuildInfo.java",
+        "android/java/src/org/chromium/base/DeviceInfo.java",
+        "android/java/src/org/chromium/base/PackageUtils.java",
+    ],
+    static_libs: [
+        "jsr305",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_android_info_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_channel_enum_java__compile_java__testing",
+        "tot_cronet_base_version_info_android_version_constants_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:build_info_java__testing
+java_library {
+    name: "tot_cronet_base_build_info_java__testing",
+    static_libs: [
+        "jsr305",
+        "tot_cronet_base_android_info_java__testing",
+        "tot_cronet_base_base_switches_java__testing",
+        "tot_cronet_base_build_info_java__process_device__testing",
+        "tot_cronet_base_command_line_java__testing",
+        "tot_cronet_base_log_java__testing",
+        "tot_cronet_base_tasks_java__testing",
+        "tot_cronet_base_version_info_android_version_constants_java__testing",
+        "tot_cronet_build_android_build_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:callback_java
 java_library {
     name: "tot_cronet_base_callback_java",
-    srcs: [
-        "android/java/src/org/chromium/base/Callback.java",
-        "android/java/src/org/chromium/base/CallbackUtils.java",
-    ],
     static_libs: [
         "jsr305",
+        "tot_cronet_base_callback_java__process_device",
+        "tot_cronet_base_callback_jni_java",
         "tot_cronet_build_android_build_java",
         "tot_cronet_third_party_jni_zero_jni_zero_java",
     ],
@@ -2868,18 +3906,77 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
-// GN: //base:callback_java__testing
+// GN: //base:callback_java__compile_java
 java_library {
-    name: "tot_cronet_base_callback_java__testing",
+    name: "tot_cronet_base_callback_java__compile_java",
     srcs: [
         "android/java/src/org/chromium/base/Callback.java",
         "android/java/src/org/chromium/base/CallbackUtils.java",
     ],
     static_libs: [
         "jsr305",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:callback_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_callback_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/Callback.java",
+        "android/java/src/org/chromium/base/CallbackUtils.java",
+    ],
+    static_libs: [
+        "jsr305",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:callback_java__testing
+java_library {
+    name: "tot_cronet_base_callback_java__testing",
+    static_libs: [
+        "jsr305",
+        "tot_cronet_base_callback_java__process_device__testing",
+        "tot_cronet_base_callback_jni_java__testing",
         "tot_cronet_build_android_build_java__testing",
         "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
     ],
@@ -2896,7 +3993,86 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:callback_jni_java
+java_library {
+    name: "tot_cronet_base_callback_jni_java",
+    static_libs: [
+        "tot_cronet_base_callback_jni_java__process_device",
+        "tot_cronet_build_android_build_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:callback_jni_java__compile_java
+java_library {
+    name: "tot_cronet_base_callback_jni_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_callback_jni__action__java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:callback_jni_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_callback_jni_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_callback_jni__action__testing__java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:callback_jni_java__testing
+java_library {
+    name: "tot_cronet_base_callback_jni_java__testing",
+    static_libs: [
+        "tot_cronet_base_callback_jni_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:check_version_internal
@@ -2915,8 +4091,8 @@
     cflags: [
         "-DANDROID",
         "-DANDROID_NDK_VERSION_ROLL=r27_1",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DHAVE_SYS_UIO_H",
         "-DNDEBUG",
@@ -2998,8 +4174,8 @@
         "tot_cronet_cc_defaults",
     ],
     cflags: [
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DNDEBUG",
         "-DNVALGRIND",
@@ -3087,7 +4263,7 @@
         },
         host: {
             cflags: [
-                "-DCR_SYSROOT_KEY=20230611T210420Z-2",
+                "-DCR_SYSROOT_KEY=20250129T203412Z-1",
                 "-DNO_UNWIND_TABLES",
                 "-DUSE_AURA=1",
                 "-DUSE_OZONE=1",
@@ -3108,13 +4284,12 @@
 // GN: //base:command_line_java
 java_library {
     name: "tot_cronet_base_command_line_java",
-    srcs: [
-        ":tot_cronet_base_command_line_jni__action__java",
-        "android/java/src/org/chromium/base/CommandLine.java",
-    ],
     static_libs: [
+        "tot_cronet_base_command_line_java__process_device",
+        "tot_cronet_base_command_line_jni_java",
         "tot_cronet_base_log_java",
         "tot_cronet_base_resetters_java",
+        "tot_cronet_build_android_build_java",
         "tot_cronet_third_party_jni_zero_jni_zero_java",
     ],
     defaults: [
@@ -3131,19 +4306,73 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:command_line_java__compile_java
+java_library {
+    name: "tot_cronet_base_command_line_java__compile_java",
+    srcs: [
+        "android/java/src/org/chromium/base/CommandLine.java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "tot_cronet_base_command_line_jni_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:command_line_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_command_line_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/CommandLine.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:command_line_java__testing
 java_library {
     name: "tot_cronet_base_command_line_java__testing",
-    srcs: [
-        ":tot_cronet_base_command_line_jni__action__testing__java",
-        "android/java/src/org/chromium/base/CommandLine.java",
-    ],
     static_libs: [
+        "tot_cronet_base_command_line_java__process_device__testing",
+        "tot_cronet_base_command_line_jni_java__testing",
         "tot_cronet_base_log_java__testing",
         "tot_cronet_base_resetters_java__testing",
+        "tot_cronet_build_android_build_java__testing",
         "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
     ],
     apex_available: [
@@ -3158,7 +4387,86 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:command_line_jni_java
+java_library {
+    name: "tot_cronet_base_command_line_jni_java",
+    static_libs: [
+        "tot_cronet_base_command_line_jni_java__process_device",
+        "tot_cronet_build_android_build_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:command_line_jni_java__compile_java
+java_library {
+    name: "tot_cronet_base_command_line_jni_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_command_line_jni__action__java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:command_line_jni_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_command_line_jni_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_command_line_jni__action__testing__java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:command_line_jni_java__testing
+java_library {
+    name: "tot_cronet_base_command_line_jni_java__testing",
+    static_libs: [
+        "tot_cronet_base_command_line_jni_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:debugging_buildflags__testing
@@ -3192,6 +4500,82 @@
     ],
 }
 
+// GN: //base:flagged_apis_java
+java_library {
+    name: "tot_cronet_base_flagged_apis_java",
+    static_libs: [
+        "tot_cronet_base_flagged_apis_java__process_device",
+        "tot_cronet_build_android_build_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:flagged_apis_java__compile_java
+java_library {
+    name: "tot_cronet_base_flagged_apis_java__compile_java",
+    srcs: [
+        "android/java/src/org/chromium/base/AconfigFlaggedApiDelegate.java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:flagged_apis_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_flagged_apis_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/AconfigFlaggedApiDelegate.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:flagged_apis_java__testing
+java_library {
+    name: "tot_cronet_base_flagged_apis_java__testing",
+    static_libs: [
+        "tot_cronet_base_flagged_apis_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:i18n__testing
 cc_library_static {
     name: "tot_cronet_base_i18n__testing",
@@ -3214,6 +4598,7 @@
         "i18n/string_search.cc",
         "i18n/time_formatting.cc",
         "i18n/timezone.cc",
+        "i18n/transliterator.cc",
         "i18n/utf8_validator_tables.cc",
     ],
     shared_libs: [
@@ -3289,9 +4674,9 @@
         "-DANDROID",
         "-DANDROID_NDK_VERSION_ROLL=r27_1",
         "-DBASE_I18N_IMPLEMENTATION",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.130/include/cxx.h\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.146/include/cxx.h\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DHAVE_SYS_UIO_H",
         "-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE",
@@ -3374,24 +4759,9 @@
 // GN: //base:jank_tracker_java
 java_library {
     name: "tot_cronet_base_jank_tracker_java",
-    srcs: [
-        ":tot_cronet_base_jank_tracker_jni__action__java",
-        "android/java/src/org/chromium/base/jank_tracker/FrameMetricsListener.java",
-        "android/java/src/org/chromium/base/jank_tracker/FrameMetricsStore.java",
-        "android/java/src/org/chromium/base/jank_tracker/JankActivityTracker.java",
-        "android/java/src/org/chromium/base/jank_tracker/JankEndScenarioTime.java",
-        "android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java",
-        "android/java/src/org/chromium/base/jank_tracker/JankMetrics.java",
-        "android/java/src/org/chromium/base/jank_tracker/JankReportingRunnable.java",
-        "android/java/src/org/chromium/base/jank_tracker/JankReportingScheduler.java",
-        "android/java/src/org/chromium/base/jank_tracker/JankScenario.java",
-        "android/java/src/org/chromium/base/jank_tracker/JankTracker.java",
-        "android/java/src/org/chromium/base/jank_tracker/JankTrackerImpl.java",
-        "android/java/src/org/chromium/base/jank_tracker/JankTrackerStateController.java",
-        "android/java/src/org/chromium/base/jank_tracker/PlaceholderJankTracker.java",
-    ],
     static_libs: [
         "tot_cronet_base_activity_state_java",
+        "tot_cronet_base_jank_tracker_java__process_device",
         "tot_cronet_base_lifetime_java",
         "tot_cronet_base_log_java",
         "tot_cronet_base_tasks_java",
@@ -3412,14 +4782,13 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
-// GN: //base:jank_tracker_java__testing
+// GN: //base:jank_tracker_java__compile_java
 java_library {
-    name: "tot_cronet_base_jank_tracker_java__testing",
+    name: "tot_cronet_base_jank_tracker_java__compile_java",
     srcs: [
-        ":tot_cronet_base_jank_tracker_jni__action__testing__java",
+        ":tot_cronet_base_jank_tracker_jni__action__java_proxy_only",
         "android/java/src/org/chromium/base/jank_tracker/FrameMetricsListener.java",
         "android/java/src/org/chromium/base/jank_tracker/FrameMetricsStore.java",
         "android/java/src/org/chromium/base/jank_tracker/JankActivityTracker.java",
@@ -3434,8 +4803,103 @@
         "android/java/src/org/chromium/base/jank_tracker/JankTrackerStateController.java",
         "android/java/src/org/chromium/base/jank_tracker/PlaceholderJankTracker.java",
     ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java",
+        "tot_cronet_base_base_switches_java__compile_java",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_base_command_line_java__compile_java",
+        "tot_cronet_base_command_line_jni_java__compile_java",
+        "tot_cronet_base_lifetime_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+        "tot_cronet_base_metrics_java__compile_java",
+        "tot_cronet_base_metrics_jni_java__compile_java",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_base_tasks_java__compile_java",
+        "tot_cronet_base_tasks_jni_java__compile_java",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java",
+        "tot_cronet_base_time_utils_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:jank_tracker_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_jank_tracker_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_jank_tracker_jni__action__testing__java_proxy_only",
+        "android/java/src/org/chromium/base/jank_tracker/FrameMetricsListener.java",
+        "android/java/src/org/chromium/base/jank_tracker/FrameMetricsStore.java",
+        "android/java/src/org/chromium/base/jank_tracker/JankActivityTracker.java",
+        "android/java/src/org/chromium/base/jank_tracker/JankEndScenarioTime.java",
+        "android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java",
+        "android/java/src/org/chromium/base/jank_tracker/JankMetrics.java",
+        "android/java/src/org/chromium/base/jank_tracker/JankReportingRunnable.java",
+        "android/java/src/org/chromium/base/jank_tracker/JankReportingScheduler.java",
+        "android/java/src/org/chromium/base/jank_tracker/JankScenario.java",
+        "android/java/src/org/chromium/base/jank_tracker/JankTracker.java",
+        "android/java/src/org/chromium/base/jank_tracker/JankTrackerImpl.java",
+        "android/java/src/org/chromium/base/jank_tracker/JankTrackerStateController.java",
+        "android/java/src/org/chromium/base/jank_tracker/PlaceholderJankTracker.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_lifetime_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:jank_tracker_java__testing
+java_library {
+    name: "tot_cronet_base_jank_tracker_java__testing",
     static_libs: [
         "tot_cronet_base_activity_state_java__testing",
+        "tot_cronet_base_jank_tracker_java__process_device__testing",
         "tot_cronet_base_lifetime_java__testing",
         "tot_cronet_base_log_java__testing",
         "tot_cronet_base_tasks_java__testing",
@@ -3454,28 +4918,18 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
 // GN: //base:library_loader_java
 java_library {
     name: "tot_cronet_base_library_loader_java",
-    srcs: [
-        ":tot_cronet_base_library_loader_java_enums_srcjar",
-        ":tot_cronet_base_library_loader_jni__action__java",
-        "android/java/src/org/chromium/base/library_loader/LibraryLoader.java",
-        "android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java",
-        "android/java/src/org/chromium/base/library_loader/Linker.java",
-        "android/java/src/org/chromium/base/library_loader/LinkerJni.java",
-        "android/java/src/org/chromium/base/library_loader/LoaderErrors.java",
-        "android/java/src/org/chromium/base/library_loader/NativeLibraryPreloader.java",
-        "android/java/src/org/chromium/base/library_loader/ProcessInitException.java",
-    ],
     static_libs: [
         "jsr305",
         "tot_cronet_base_base_switches_java",
         "tot_cronet_base_callback_java",
         "tot_cronet_base_command_line_java",
+        "tot_cronet_base_library_loader_java__process_device",
+        "tot_cronet_base_library_loader_jni_java",
         "tot_cronet_base_log_java",
         "tot_cronet_base_metrics_java",
         "tot_cronet_base_resetters_java",
@@ -3501,15 +4955,13 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
-// GN: //base:library_loader_java__testing
+// GN: //base:library_loader_java__compile_java
 java_library {
-    name: "tot_cronet_base_library_loader_java__testing",
+    name: "tot_cronet_base_library_loader_java__compile_java",
     srcs: [
-        ":tot_cronet_base_library_loader_java_enums_srcjar__testing",
-        ":tot_cronet_base_library_loader_jni__action__testing__java",
+        ":tot_cronet_base_library_loader_java_enums_srcjar",
         "android/java/src/org/chromium/base/library_loader/LibraryLoader.java",
         "android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java",
         "android/java/src/org/chromium/base/library_loader/Linker.java",
@@ -3520,9 +4972,109 @@
     ],
     static_libs: [
         "jsr305",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java",
+        "tot_cronet_base_base_switches_java__compile_java",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_base_command_line_java__compile_java",
+        "tot_cronet_base_command_line_jni_java__compile_java",
+        "tot_cronet_base_library_loader_jni_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+        "tot_cronet_base_metrics_java__compile_java",
+        "tot_cronet_base_metrics_jni_java__compile_java",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_base_stream_util_java__compile_java",
+        "tot_cronet_base_sys_utils_java__compile_java",
+        "tot_cronet_base_tasks_java__compile_java",
+        "tot_cronet_base_tasks_jni_java__compile_java",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java",
+        "tot_cronet_base_time_utils_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:library_loader_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_library_loader_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_library_loader_java_enums_srcjar__testing",
+        "android/java/src/org/chromium/base/library_loader/LibraryLoader.java",
+        "android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java",
+        "android/java/src/org/chromium/base/library_loader/Linker.java",
+        "android/java/src/org/chromium/base/library_loader/LinkerJni.java",
+        "android/java/src/org/chromium/base/library_loader/LoaderErrors.java",
+        "android/java/src/org/chromium/base/library_loader/NativeLibraryPreloader.java",
+        "android/java/src/org/chromium/base/library_loader/ProcessInitException.java",
+    ],
+    static_libs: [
+        "jsr305",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_library_loader_jni_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_stream_util_java__compile_java__testing",
+        "tot_cronet_base_sys_utils_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:library_loader_java__testing
+java_library {
+    name: "tot_cronet_base_library_loader_java__testing",
+    static_libs: [
+        "jsr305",
         "tot_cronet_base_base_switches_java__testing",
         "tot_cronet_base_callback_java__testing",
         "tot_cronet_base_command_line_java__testing",
+        "tot_cronet_base_library_loader_java__process_device__testing",
+        "tot_cronet_base_library_loader_jni_java__testing",
         "tot_cronet_base_log_java__testing",
         "tot_cronet_base_metrics_java__testing",
         "tot_cronet_base_resetters_java__testing",
@@ -3546,18 +5098,93 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:library_loader_jni_java
+java_library {
+    name: "tot_cronet_base_library_loader_jni_java",
+    static_libs: [
+        "tot_cronet_base_library_loader_jni_java__process_device",
+        "tot_cronet_build_android_build_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:library_loader_jni_java__compile_java
+java_library {
+    name: "tot_cronet_base_library_loader_jni_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_library_loader_jni__action__java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:library_loader_jni_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_library_loader_jni_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_library_loader_jni__action__testing__java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:library_loader_jni_java__testing
+java_library {
+    name: "tot_cronet_base_library_loader_jni_java__testing",
+    static_libs: [
+        "tot_cronet_base_library_loader_jni_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:lifetime_java
 java_library {
     name: "tot_cronet_base_lifetime_java",
-    srcs: [
-        "android/java/src/org/chromium/base/LifetimeAssert.java",
-        "android/java/src/org/chromium/base/lifetime/DestroyChecker.java",
-        "android/java/src/org/chromium/base/lifetime/Destroyable.java",
-    ],
     static_libs: [
+        "tot_cronet_base_lifetime_java__process_device",
         "tot_cronet_base_tasks_java",
         "tot_cronet_build_android_build_java",
     ],
@@ -3574,18 +5201,99 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
-// GN: //base:lifetime_java__testing
+// GN: //base:lifetime_java__compile_java
 java_library {
-    name: "tot_cronet_base_lifetime_java__testing",
+    name: "tot_cronet_base_lifetime_java__compile_java",
     srcs: [
         "android/java/src/org/chromium/base/LifetimeAssert.java",
         "android/java/src/org/chromium/base/lifetime/DestroyChecker.java",
         "android/java/src/org/chromium/base/lifetime/Destroyable.java",
     ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java",
+        "tot_cronet_base_base_switches_java__compile_java",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_base_command_line_java__compile_java",
+        "tot_cronet_base_command_line_jni_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+        "tot_cronet_base_metrics_java__compile_java",
+        "tot_cronet_base_metrics_jni_java__compile_java",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_base_tasks_java__compile_java",
+        "tot_cronet_base_tasks_jni_java__compile_java",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java",
+        "tot_cronet_base_time_utils_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:lifetime_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_lifetime_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/LifetimeAssert.java",
+        "android/java/src/org/chromium/base/lifetime/DestroyChecker.java",
+        "android/java/src/org/chromium/base/lifetime/Destroyable.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:lifetime_java__testing
+java_library {
+    name: "tot_cronet_base_lifetime_java__testing",
     static_libs: [
+        "tot_cronet_base_lifetime_java__process_device__testing",
         "tot_cronet_base_tasks_java__testing",
         "tot_cronet_build_android_build_java__testing",
     ],
@@ -3600,17 +5308,13 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
 // GN: //base:log_java
 java_library {
     name: "tot_cronet_base_log_java",
-    srcs: [
-        "android/java/src/org/chromium/base/JavaUtils.java",
-        "android/java/src/org/chromium/base/Log.java",
-    ],
     static_libs: [
+        "tot_cronet_base_log_java__process_device",
         "tot_cronet_build_android_build_java",
     ],
     defaults: [
@@ -3626,17 +5330,57 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:log_java__compile_java
+java_library {
+    name: "tot_cronet_base_log_java__compile_java",
+    srcs: [
+        "android/java/src/org/chromium/base/JavaUtils.java",
+        "android/java/src/org/chromium/base/Log.java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "tot_cronet_build_android_build_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:log_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_log_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/JavaUtils.java",
+        "android/java/src/org/chromium/base/Log.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:log_java__testing
 java_library {
     name: "tot_cronet_base_log_java__testing",
-    srcs: [
-        "android/java/src/org/chromium/base/JavaUtils.java",
-        "android/java/src/org/chromium/base/Log.java",
-    ],
     static_libs: [
+        "tot_cronet_base_log_java__process_device__testing",
         "tot_cronet_build_android_build_java__testing",
     ],
     apex_available: [
@@ -3650,14 +5394,43 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
 // GN: //base:memory_java
 java_library {
     name: "tot_cronet_base_memory_java",
+    static_libs: [
+        "tot_cronet_base_library_loader_java",
+        "tot_cronet_base_log_java",
+        "tot_cronet_base_memory_java__process_device",
+        "tot_cronet_base_metrics_java",
+        "tot_cronet_base_resetters_java",
+        "tot_cronet_base_supplier_java",
+        "tot_cronet_base_tasks_java",
+        "tot_cronet_base_time_utils_java",
+        "tot_cronet_build_android_build_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:memory_java__compile_java
+java_library {
+    name: "tot_cronet_base_memory_java__compile_java",
     srcs: [
-        ":tot_cronet_base_memory_jni__action__java",
+        ":tot_cronet_base_memory_jni__action__java_proxy_only",
         ":tot_cronet_base_memory_pressure_level_enum_srcjar",
         "android/java/src/org/chromium/base/MemoryPressureListener.java",
         "android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java",
@@ -3668,16 +5441,6 @@
         "android/java/src/org/chromium/base/memory/MemoryPurgeManager.java",
         "android/java/src/org/chromium/base/memory/SelfFreezeCallback.java",
     ],
-    static_libs: [
-        "tot_cronet_base_library_loader_java",
-        "tot_cronet_base_log_java",
-        "tot_cronet_base_metrics_java",
-        "tot_cronet_base_resetters_java",
-        "tot_cronet_base_supplier_java",
-        "tot_cronet_base_tasks_java",
-        "tot_cronet_base_time_utils_java",
-        "tot_cronet_third_party_jni_zero_jni_zero_java",
-    ],
     defaults: [
         "tot_cronet_java_framework_defaults",
     ],
@@ -3687,18 +5450,46 @@
     min_sdk_version: "30",
     libs: [
         "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java",
+        "tot_cronet_base_base_switches_java__compile_java",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_base_command_line_java__compile_java",
+        "tot_cronet_base_command_line_jni_java__compile_java",
+        "tot_cronet_base_library_loader_java__compile_java",
+        "tot_cronet_base_library_loader_jni_java__compile_java",
+        "tot_cronet_base_lifetime_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+        "tot_cronet_base_metrics_java__compile_java",
+        "tot_cronet_base_metrics_jni_java__compile_java",
+        "tot_cronet_base_promise_java__compile_java",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_base_stream_util_java__compile_java",
+        "tot_cronet_base_supplier_java__compile_java",
+        "tot_cronet_base_sys_utils_java__compile_java",
+        "tot_cronet_base_tasks_java__compile_java",
+        "tot_cronet_base_tasks_jni_java__compile_java",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java",
+        "tot_cronet_base_time_utils_java__compile_java",
+        "tot_cronet_base_unowned_user_data_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
     ],
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
-// GN: //base:memory_java__testing
+// GN: //base:memory_java__compile_java__testing
 java_library {
-    name: "tot_cronet_base_memory_java__testing",
+    name: "tot_cronet_base_memory_java__compile_java__testing",
     srcs: [
-        ":tot_cronet_base_memory_jni__action__testing__java",
+        ":tot_cronet_base_memory_jni__action__testing__java_proxy_only",
         ":tot_cronet_base_memory_pressure_level_enum_srcjar__testing",
         "android/java/src/org/chromium/base/MemoryPressureListener.java",
         "android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java",
@@ -3709,14 +5500,61 @@
         "android/java/src/org/chromium/base/memory/MemoryPurgeManager.java",
         "android/java/src/org/chromium/base/memory/SelfFreezeCallback.java",
     ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_library_loader_java__compile_java__testing",
+        "tot_cronet_base_library_loader_jni_java__compile_java__testing",
+        "tot_cronet_base_lifetime_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_promise_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_stream_util_java__compile_java__testing",
+        "tot_cronet_base_supplier_java__compile_java__testing",
+        "tot_cronet_base_sys_utils_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_base_unowned_user_data_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:memory_java__testing
+java_library {
+    name: "tot_cronet_base_memory_java__testing",
     static_libs: [
         "tot_cronet_base_library_loader_java__testing",
         "tot_cronet_base_log_java__testing",
+        "tot_cronet_base_memory_java__process_device__testing",
         "tot_cronet_base_metrics_java__testing",
         "tot_cronet_base_resetters_java__testing",
         "tot_cronet_base_supplier_java__testing",
         "tot_cronet_base_tasks_java__testing",
         "tot_cronet_base_time_utils_java__testing",
+        "tot_cronet_build_android_build_java__testing",
         "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
     ],
     apex_available: [
@@ -3730,14 +5568,14 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
 // GN: //base:metrics_ScopedSysTraceEvent_java
 java_library {
     name: "tot_cronet_base_metrics_ScopedSysTraceEvent_java",
-    srcs: [
-        "android/java/src/org/chromium/base/metrics/ScopedSysTraceEvent.java",
+    static_libs: [
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__process_device",
+        "tot_cronet_build_android_build_java",
     ],
     defaults: [
         "tot_cronet_java_framework_defaults",
@@ -3749,14 +5587,54 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:metrics_ScopedSysTraceEvent_java__compile_java
+java_library {
+    name: "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+    srcs: [
+        "android/java/src/org/chromium/base/metrics/ScopedSysTraceEvent.java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:metrics_ScopedSysTraceEvent_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/metrics/ScopedSysTraceEvent.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:metrics_ScopedSysTraceEvent_java__testing
 java_library {
     name: "tot_cronet_base_metrics_ScopedSysTraceEvent_java__testing",
-    srcs: [
-        "android/java/src/org/chromium/base/metrics/ScopedSysTraceEvent.java",
+    static_libs: [
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
     ],
     apex_available: [
         "com.android.tethering",
@@ -3766,31 +5644,18 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
 // GN: //base:metrics_java
 java_library {
     name: "tot_cronet_base_metrics_java",
-    srcs: [
-        ":tot_cronet_base_metrics_enum_srcjar",
-        ":tot_cronet_base_metrics_jni__action__java",
-        "android/java/src/org/chromium/base/metrics/CachingUmaRecorder.java",
-        "android/java/src/org/chromium/base/metrics/HistogramBucket.java",
-        "android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java",
-        "android/java/src/org/chromium/base/metrics/NoopUmaRecorder.java",
-        "android/java/src/org/chromium/base/metrics/RecordHistogram.java",
-        "android/java/src/org/chromium/base/metrics/RecordUserAction.java",
-        "android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java",
-        "android/java/src/org/chromium/base/metrics/TimingMetric.java",
-        "android/java/src/org/chromium/base/metrics/UmaRecorder.java",
-        "android/java/src/org/chromium/base/metrics/UmaRecorderHolder.java",
-    ],
     static_libs: [
         "jsr305",
         "tot_cronet_base_callback_java",
         "tot_cronet_base_log_java",
         "tot_cronet_base_metrics_ScopedSysTraceEvent_java",
+        "tot_cronet_base_metrics_java__process_device",
+        "tot_cronet_base_metrics_jni_java",
         "tot_cronet_base_time_utils_java",
         "tot_cronet_build_android_build_java",
         "tot_cronet_third_party_jni_zero_jni_zero_java",
@@ -3809,15 +5674,13 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
-// GN: //base:metrics_java__testing
+// GN: //base:metrics_java__compile_java
 java_library {
-    name: "tot_cronet_base_metrics_java__testing",
+    name: "tot_cronet_base_metrics_java__compile_java",
     srcs: [
-        ":tot_cronet_base_metrics_enum_srcjar__testing",
-        ":tot_cronet_base_metrics_jni__action__testing__java",
+        ":tot_cronet_base_metrics_enum_srcjar",
         "android/java/src/org/chromium/base/metrics/CachingUmaRecorder.java",
         "android/java/src/org/chromium/base/metrics/HistogramBucket.java",
         "android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java",
@@ -3831,9 +5694,88 @@
     ],
     static_libs: [
         "jsr305",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+        "tot_cronet_base_metrics_jni_java__compile_java",
+        "tot_cronet_base_time_utils_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:metrics_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_metrics_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_metrics_enum_srcjar__testing",
+        "android/java/src/org/chromium/base/metrics/CachingUmaRecorder.java",
+        "android/java/src/org/chromium/base/metrics/HistogramBucket.java",
+        "android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java",
+        "android/java/src/org/chromium/base/metrics/NoopUmaRecorder.java",
+        "android/java/src/org/chromium/base/metrics/RecordHistogram.java",
+        "android/java/src/org/chromium/base/metrics/RecordUserAction.java",
+        "android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java",
+        "android/java/src/org/chromium/base/metrics/TimingMetric.java",
+        "android/java/src/org/chromium/base/metrics/UmaRecorder.java",
+        "android/java/src/org/chromium/base/metrics/UmaRecorderHolder.java",
+    ],
+    static_libs: [
+        "jsr305",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:metrics_java__testing
+java_library {
+    name: "tot_cronet_base_metrics_java__testing",
+    static_libs: [
+        "jsr305",
         "tot_cronet_base_callback_java__testing",
         "tot_cronet_base_log_java__testing",
         "tot_cronet_base_metrics_ScopedSysTraceEvent_java__testing",
+        "tot_cronet_base_metrics_java__process_device__testing",
+        "tot_cronet_base_metrics_jni_java__testing",
         "tot_cronet_base_time_utils_java__testing",
         "tot_cronet_build_android_build_java__testing",
         "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
@@ -3850,17 +5792,95 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:metrics_jni_java
+java_library {
+    name: "tot_cronet_base_metrics_jni_java",
+    static_libs: [
+        "tot_cronet_base_metrics_jni_java__process_device",
+        "tot_cronet_build_android_build_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:metrics_jni_java__compile_java
+java_library {
+    name: "tot_cronet_base_metrics_jni_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_metrics_jni__action__java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:metrics_jni_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_metrics_jni_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_metrics_jni__action__testing__java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:metrics_jni_java__testing
+java_library {
+    name: "tot_cronet_base_metrics_jni_java__testing",
+    static_libs: [
+        "tot_cronet_base_metrics_jni_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:promise_java
 java_library {
     name: "tot_cronet_base_promise_java",
-    srcs: [
-        "android/java/src/org/chromium/base/Promise.java",
-    ],
     static_libs: [
         "tot_cronet_base_callback_java",
+        "tot_cronet_base_promise_java__process_device",
+        "tot_cronet_build_android_build_java",
     ],
     defaults: [
         "tot_cronet_java_framework_defaults",
@@ -3875,17 +5895,71 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:promise_java__compile_java
+java_library {
+    name: "tot_cronet_base_promise_java__compile_java",
+    srcs: [
+        "android/java/src/org/chromium/base/Promise.java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:promise_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_promise_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/Promise.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:promise_java__testing
 java_library {
     name: "tot_cronet_base_promise_java__testing",
-    srcs: [
-        "android/java/src/org/chromium/base/Promise.java",
-    ],
     static_libs: [
         "tot_cronet_base_callback_java__testing",
+        "tot_cronet_base_promise_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
     ],
     apex_available: [
         "com.android.tethering",
@@ -3898,16 +5972,13 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
 // GN: //base:resetters_java
 java_library {
     name: "tot_cronet_base_resetters_java",
-    srcs: [
-        "android/java/src/org/chromium/base/ResettersForTesting.java",
-    ],
     static_libs: [
+        "tot_cronet_base_resetters_java__process_device",
         "tot_cronet_build_android_build_java",
     ],
     defaults: [
@@ -3924,16 +5995,57 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:resetters_java__compile_java
+java_library {
+    name: "tot_cronet_base_resetters_java__compile_java",
+    srcs: [
+        "android/java/src/org/chromium/base/ResettersForTesting.java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "tot_cronet_build_android_build_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:resetters_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_resetters_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/ResettersForTesting.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:resetters_java__testing
 java_library {
     name: "tot_cronet_base_resetters_java__testing",
-    srcs: [
-        "android/java/src/org/chromium/base/ResettersForTesting.java",
-    ],
     static_libs: [
+        "tot_cronet_base_resetters_java__process_device__testing",
         "tot_cronet_build_android_build_java__testing",
     ],
     apex_available: [
@@ -3948,7 +6060,6 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
 // GN: //base:rust_logger_cxx_generated
@@ -3970,9 +6081,9 @@
     cflags: [
         "-DANDROID",
         "-DANDROID_NDK_VERSION_ROLL=r27_1",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.130/include/cxx.h\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.146/include/cxx.h\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DHAVE_SYS_UIO_H",
         "-DNDEBUG",
@@ -4057,9 +6168,9 @@
         "tot_cronet_cc_defaults",
     ],
     cflags: [
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.130/include/cxx.h\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_CXX_INCLUDE=\"third_party/rust/chromium_crates_io/vendor/cxx-1.0.146/include/cxx.h\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DNDEBUG",
         "-DNVALGRIND",
@@ -4147,7 +6258,7 @@
         },
         host: {
             cflags: [
-                "-DCR_SYSROOT_KEY=20230611T210420Z-2",
+                "-DCR_SYSROOT_KEY=20250129T203412Z-1",
                 "-DNO_UNWIND_TABLES",
                 "-DUSE_AURA=1",
                 "-DUSE_OZONE=1",
@@ -4165,11 +6276,102 @@
     },
 }
 
+// GN: //base:service_loader_java
+java_library {
+    name: "tot_cronet_base_service_loader_java",
+    static_libs: [
+        "tot_cronet_base_resetters_java",
+        "tot_cronet_base_service_loader_java__process_device",
+        "tot_cronet_build_android_build_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:service_loader_java__compile_java
+java_library {
+    name: "tot_cronet_base_service_loader_java__compile_java",
+    srcs: [
+        "android/java/src/org/chromium/base/ServiceLoaderUtil.java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:service_loader_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_service_loader_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/ServiceLoaderUtil.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:service_loader_java__testing
+java_library {
+    name: "tot_cronet_base_service_loader_java__testing",
+    static_libs: [
+        "tot_cronet_base_resetters_java__testing",
+        "tot_cronet_base_service_loader_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
 // GN: //base:stream_util_java
 java_library {
     name: "tot_cronet_base_stream_util_java",
-    srcs: [
-        "android/java/src/org/chromium/base/StreamUtil.java",
+    static_libs: [
+        "tot_cronet_base_stream_util_java__process_device",
+        "tot_cronet_build_android_build_java",
     ],
     defaults: [
         "tot_cronet_java_framework_defaults",
@@ -4181,14 +6383,54 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:stream_util_java__compile_java
+java_library {
+    name: "tot_cronet_base_stream_util_java__compile_java",
+    srcs: [
+        "android/java/src/org/chromium/base/StreamUtil.java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:stream_util_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_stream_util_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/StreamUtil.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:stream_util_java__testing
 java_library {
     name: "tot_cronet_base_stream_util_java__testing",
-    srcs: [
-        "android/java/src/org/chromium/base/StreamUtil.java",
+    static_libs: [
+        "tot_cronet_base_stream_util_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
     ],
     apex_available: [
         "com.android.tethering",
@@ -4198,36 +6440,20 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
 // GN: //base:supplier_java
 java_library {
     name: "tot_cronet_base_supplier_java",
-    srcs: [
-        "android/java/src/org/chromium/base/supplier/DestroyableObservableSupplier.java",
-        "android/java/src/org/chromium/base/supplier/LazyOneshotSupplier.java",
-        "android/java/src/org/chromium/base/supplier/LazyOneshotSupplierImpl.java",
-        "android/java/src/org/chromium/base/supplier/ObservableSupplier.java",
-        "android/java/src/org/chromium/base/supplier/ObservableSupplierImpl.java",
-        "android/java/src/org/chromium/base/supplier/OneShotCallback.java",
-        "android/java/src/org/chromium/base/supplier/OneshotSupplier.java",
-        "android/java/src/org/chromium/base/supplier/OneshotSupplierImpl.java",
-        "android/java/src/org/chromium/base/supplier/Supplier.java",
-        "android/java/src/org/chromium/base/supplier/SupplierUtils.java",
-        "android/java/src/org/chromium/base/supplier/SyncOneshotSupplier.java",
-        "android/java/src/org/chromium/base/supplier/SyncOneshotSupplierImpl.java",
-        "android/java/src/org/chromium/base/supplier/TransitiveObservableSupplier.java",
-        "android/java/src/org/chromium/base/supplier/UnownedUserDataSupplier.java",
-        "android/java/src/org/chromium/base/supplier/UnwrapObservableSupplier.java",
-    ],
     static_libs: [
         "tot_cronet_base_callback_java",
         "tot_cronet_base_lifetime_java",
         "tot_cronet_base_promise_java",
         "tot_cronet_base_resetters_java",
+        "tot_cronet_base_supplier_java__process_device",
         "tot_cronet_base_tasks_java",
         "tot_cronet_base_unowned_user_data_java",
+        "tot_cronet_build_android_build_java",
     ],
     defaults: [
         "tot_cronet_java_framework_defaults",
@@ -4242,12 +6468,11 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
-// GN: //base:supplier_java__testing
+// GN: //base:supplier_java__compile_java
 java_library {
-    name: "tot_cronet_base_supplier_java__testing",
+    name: "tot_cronet_base_supplier_java__compile_java",
     srcs: [
         "android/java/src/org/chromium/base/supplier/DestroyableObservableSupplier.java",
         "android/java/src/org/chromium/base/supplier/LazyOneshotSupplier.java",
@@ -4265,13 +6490,114 @@
         "android/java/src/org/chromium/base/supplier/UnownedUserDataSupplier.java",
         "android/java/src/org/chromium/base/supplier/UnwrapObservableSupplier.java",
     ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java",
+        "tot_cronet_base_base_switches_java__compile_java",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_base_command_line_java__compile_java",
+        "tot_cronet_base_command_line_jni_java__compile_java",
+        "tot_cronet_base_lifetime_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+        "tot_cronet_base_metrics_java__compile_java",
+        "tot_cronet_base_metrics_jni_java__compile_java",
+        "tot_cronet_base_promise_java__compile_java",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_base_tasks_java__compile_java",
+        "tot_cronet_base_tasks_jni_java__compile_java",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java",
+        "tot_cronet_base_time_utils_java__compile_java",
+        "tot_cronet_base_unowned_user_data_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:supplier_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_supplier_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/supplier/DestroyableObservableSupplier.java",
+        "android/java/src/org/chromium/base/supplier/LazyOneshotSupplier.java",
+        "android/java/src/org/chromium/base/supplier/LazyOneshotSupplierImpl.java",
+        "android/java/src/org/chromium/base/supplier/ObservableSupplier.java",
+        "android/java/src/org/chromium/base/supplier/ObservableSupplierImpl.java",
+        "android/java/src/org/chromium/base/supplier/OneShotCallback.java",
+        "android/java/src/org/chromium/base/supplier/OneshotSupplier.java",
+        "android/java/src/org/chromium/base/supplier/OneshotSupplierImpl.java",
+        "android/java/src/org/chromium/base/supplier/Supplier.java",
+        "android/java/src/org/chromium/base/supplier/SupplierUtils.java",
+        "android/java/src/org/chromium/base/supplier/SyncOneshotSupplier.java",
+        "android/java/src/org/chromium/base/supplier/SyncOneshotSupplierImpl.java",
+        "android/java/src/org/chromium/base/supplier/TransitiveObservableSupplier.java",
+        "android/java/src/org/chromium/base/supplier/UnownedUserDataSupplier.java",
+        "android/java/src/org/chromium/base/supplier/UnwrapObservableSupplier.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_lifetime_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_promise_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_base_unowned_user_data_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:supplier_java__testing
+java_library {
+    name: "tot_cronet_base_supplier_java__testing",
     static_libs: [
         "tot_cronet_base_callback_java__testing",
         "tot_cronet_base_lifetime_java__testing",
         "tot_cronet_base_promise_java__testing",
         "tot_cronet_base_resetters_java__testing",
+        "tot_cronet_base_supplier_java__process_device__testing",
         "tot_cronet_base_tasks_java__testing",
         "tot_cronet_base_unowned_user_data_java__testing",
+        "tot_cronet_build_android_build_java__testing",
     ],
     apex_available: [
         "com.android.tethering",
@@ -4284,18 +6610,16 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
 // GN: //base:sys_utils_java
 java_library {
     name: "tot_cronet_base_sys_utils_java",
-    srcs: [
-        ":tot_cronet_base_sys_utils_enum_srcjar",
-        ":tot_cronet_base_sys_utils_jni__action__java",
-        "android/java/src/org/chromium/base/SysUtils.java",
-    ],
     static_libs: [
+        "tot_cronet_base_base_switches_java",
+        "tot_cronet_base_command_line_java",
+        "tot_cronet_base_log_java",
+        "tot_cronet_base_sys_utils_java__process_device",
         "tot_cronet_base_tasks_java",
         "tot_cronet_build_android_build_java",
         "tot_cronet_third_party_jni_zero_jni_zero_java",
@@ -4313,18 +6637,102 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:sys_utils_java__compile_java
+java_library {
+    name: "tot_cronet_base_sys_utils_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_sys_utils_enum_srcjar",
+        ":tot_cronet_base_sys_utils_jni__action__java_proxy_only",
+        "android/java/src/org/chromium/base/SysUtils.java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java",
+        "tot_cronet_base_base_switches_java__compile_java",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_base_command_line_java__compile_java",
+        "tot_cronet_base_command_line_jni_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+        "tot_cronet_base_metrics_java__compile_java",
+        "tot_cronet_base_metrics_jni_java__compile_java",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_base_tasks_java__compile_java",
+        "tot_cronet_base_tasks_jni_java__compile_java",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java",
+        "tot_cronet_base_time_utils_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:sys_utils_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_sys_utils_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_sys_utils_enum_srcjar__testing",
+        ":tot_cronet_base_sys_utils_jni__action__testing__java_proxy_only",
+        "android/java/src/org/chromium/base/SysUtils.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:sys_utils_java__testing
 java_library {
     name: "tot_cronet_base_sys_utils_java__testing",
-    srcs: [
-        ":tot_cronet_base_sys_utils_enum_srcjar__testing",
-        ":tot_cronet_base_sys_utils_jni__action__testing__java",
-        "android/java/src/org/chromium/base/SysUtils.java",
-    ],
     static_libs: [
+        "tot_cronet_base_base_switches_java__testing",
+        "tot_cronet_base_command_line_java__testing",
+        "tot_cronet_base_log_java__testing",
+        "tot_cronet_base_sys_utils_java__process_device__testing",
         "tot_cronet_base_tasks_java__testing",
         "tot_cronet_build_android_build_java__testing",
         "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
@@ -4340,36 +6748,11 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
 // GN: //base:tasks_java
 java_library {
     name: "tot_cronet_base_tasks_java",
-    srcs: [
-        ":tot_cronet_base_task_trait_enum_srcjar",
-        ":tot_cronet_base_tasks_jni__action__java",
-        "android/java/src/org/chromium/base/ApiCompatibilityUtils.java",
-        "android/java/src/org/chromium/base/ApplicationStatus.java",
-        "android/java/src/org/chromium/base/ContextUtils.java",
-        "android/java/src/org/chromium/base/EarlyTraceEvent.java",
-        "android/java/src/org/chromium/base/ObserverList.java",
-        "android/java/src/org/chromium/base/StrictModeContext.java",
-        "android/java/src/org/chromium/base/ThreadUtils.java",
-        "android/java/src/org/chromium/base/TraceEvent.java",
-        "android/java/src/org/chromium/base/task/AsyncTask.java",
-        "android/java/src/org/chromium/base/task/BackgroundOnlyAsyncTask.java",
-        "android/java/src/org/chromium/base/task/ChainedTasks.java",
-        "android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java",
-        "android/java/src/org/chromium/base/task/PostTask.java",
-        "android/java/src/org/chromium/base/task/SequencedTaskRunner.java",
-        "android/java/src/org/chromium/base/task/SequencedTaskRunnerImpl.java",
-        "android/java/src/org/chromium/base/task/SerialExecutor.java",
-        "android/java/src/org/chromium/base/task/TaskOriginException.java",
-        "android/java/src/org/chromium/base/task/TaskRunner.java",
-        "android/java/src/org/chromium/base/task/TaskRunnerImpl.java",
-        "android/java/src/org/chromium/base/task/UiThreadTaskRunnerImpl.java",
-    ],
     static_libs: [
         "jsr305",
         "tot_cronet_base_activity_state_java",
@@ -4378,6 +6761,9 @@
         "tot_cronet_base_log_java",
         "tot_cronet_base_metrics_java",
         "tot_cronet_base_resetters_java",
+        "tot_cronet_base_tasks_java__process_device",
+        "tot_cronet_base_tasks_jni_java",
+        "tot_cronet_base_tasks_minimal_jni_java",
         "tot_cronet_base_time_utils_java",
         "tot_cronet_build_android_build_java",
         "tot_cronet_third_party_jni_zero_jni_zero_java",
@@ -4395,15 +6781,13 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
-// GN: //base:tasks_java__testing
+// GN: //base:tasks_java__compile_java
 java_library {
-    name: "tot_cronet_base_tasks_java__testing",
+    name: "tot_cronet_base_tasks_java__compile_java",
     srcs: [
-        ":tot_cronet_base_task_trait_enum_srcjar__testing",
-        ":tot_cronet_base_tasks_jni__action__testing__java",
+        ":tot_cronet_base_task_trait_enum_srcjar",
         "android/java/src/org/chromium/base/ApiCompatibilityUtils.java",
         "android/java/src/org/chromium/base/ApplicationStatus.java",
         "android/java/src/org/chromium/base/ContextUtils.java",
@@ -4427,12 +6811,118 @@
     ],
     static_libs: [
         "jsr305",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java",
+        "tot_cronet_base_base_switches_java__compile_java",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_base_command_line_java__compile_java",
+        "tot_cronet_base_command_line_jni_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+        "tot_cronet_base_metrics_java__compile_java",
+        "tot_cronet_base_metrics_jni_java__compile_java",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_base_tasks_jni_java__compile_java",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java",
+        "tot_cronet_base_time_utils_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_tasks_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_task_trait_enum_srcjar__testing",
+        "android/java/src/org/chromium/base/ApiCompatibilityUtils.java",
+        "android/java/src/org/chromium/base/ApplicationStatus.java",
+        "android/java/src/org/chromium/base/ContextUtils.java",
+        "android/java/src/org/chromium/base/EarlyTraceEvent.java",
+        "android/java/src/org/chromium/base/ObserverList.java",
+        "android/java/src/org/chromium/base/StrictModeContext.java",
+        "android/java/src/org/chromium/base/ThreadUtils.java",
+        "android/java/src/org/chromium/base/TraceEvent.java",
+        "android/java/src/org/chromium/base/task/AsyncTask.java",
+        "android/java/src/org/chromium/base/task/BackgroundOnlyAsyncTask.java",
+        "android/java/src/org/chromium/base/task/ChainedTasks.java",
+        "android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java",
+        "android/java/src/org/chromium/base/task/PostTask.java",
+        "android/java/src/org/chromium/base/task/SequencedTaskRunner.java",
+        "android/java/src/org/chromium/base/task/SequencedTaskRunnerImpl.java",
+        "android/java/src/org/chromium/base/task/SerialExecutor.java",
+        "android/java/src/org/chromium/base/task/TaskOriginException.java",
+        "android/java/src/org/chromium/base/task/TaskRunner.java",
+        "android/java/src/org/chromium/base/task/TaskRunnerImpl.java",
+        "android/java/src/org/chromium/base/task/UiThreadTaskRunnerImpl.java",
+    ],
+    static_libs: [
+        "jsr305",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_java__testing
+java_library {
+    name: "tot_cronet_base_tasks_java__testing",
+    static_libs: [
+        "jsr305",
         "tot_cronet_base_activity_state_java__testing",
         "tot_cronet_base_base_switches_java__testing",
         "tot_cronet_base_command_line_java__testing",
         "tot_cronet_base_log_java__testing",
         "tot_cronet_base_metrics_java__testing",
         "tot_cronet_base_resetters_java__testing",
+        "tot_cronet_base_tasks_java__process_device__testing",
+        "tot_cronet_base_tasks_jni_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__testing",
         "tot_cronet_base_time_utils_java__testing",
         "tot_cronet_build_android_build_java__testing",
         "tot_cronet_third_party_jni_zero_jni_zero_java__testing",
@@ -4448,16 +6938,173 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:tasks_jni_java
+java_library {
+    name: "tot_cronet_base_tasks_jni_java",
+    static_libs: [
+        "tot_cronet_base_tasks_jni_java__process_device",
+        "tot_cronet_build_android_build_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_jni_java__compile_java
+java_library {
+    name: "tot_cronet_base_tasks_jni_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_tasks_jni__action__java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_jni_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_tasks_jni_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_tasks_jni__action__testing__java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_jni_java__testing
+java_library {
+    name: "tot_cronet_base_tasks_jni_java__testing",
+    static_libs: [
+        "tot_cronet_base_tasks_jni_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_minimal_jni_java
+java_library {
+    name: "tot_cronet_base_tasks_minimal_jni_java",
+    static_libs: [
+        "tot_cronet_base_tasks_minimal_jni_java__process_device",
+        "tot_cronet_build_android_build_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_minimal_jni_java__compile_java
+java_library {
+    name: "tot_cronet_base_tasks_minimal_jni_java__compile_java",
+    srcs: [
+        ":tot_cronet_base_tasks_minimal_jni__action__java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_minimal_jni_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+    srcs: [
+        ":tot_cronet_base_tasks_minimal_jni__action__testing__java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:tasks_minimal_jni_java__testing
+java_library {
+    name: "tot_cronet_base_tasks_minimal_jni_java__testing",
+    static_libs: [
+        "tot_cronet_base_tasks_minimal_jni_java__process_device__testing",
+        "tot_cronet_build_android_build_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__testing",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:time_utils_java
 java_library {
     name: "tot_cronet_base_time_utils_java",
-    srcs: [
-        "android/java/src/org/chromium/base/TimeUtils.java",
-    ],
     static_libs: [
+        "tot_cronet_base_time_utils_java__process_device",
         "tot_cronet_build_android_build_java",
     ],
     defaults: [
@@ -4470,16 +7117,53 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
+}
+
+// GN: //base:time_utils_java__compile_java
+java_library {
+    name: "tot_cronet_base_time_utils_java__compile_java",
+    srcs: [
+        "android/java/src/org/chromium/base/TimeUtils.java",
+    ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:time_utils_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_time_utils_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/TimeUtils.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "tot_cronet_build_android_build_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
 }
 
 // GN: //base:time_utils_java__testing
 java_library {
     name: "tot_cronet_base_time_utils_java__testing",
-    srcs: [
-        "android/java/src/org/chromium/base/TimeUtils.java",
-    ],
     static_libs: [
+        "tot_cronet_base_time_utils_java__process_device__testing",
         "tot_cronet_build_android_build_java__testing",
     ],
     apex_available: [
@@ -4490,20 +7174,15 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
 // GN: //base:unowned_user_data_java
 java_library {
     name: "tot_cronet_base_unowned_user_data_java",
-    srcs: [
-        "android/java/src/org/chromium/base/UnownedUserData.java",
-        "android/java/src/org/chromium/base/UnownedUserDataHost.java",
-        "android/java/src/org/chromium/base/UnownedUserDataKey.java",
-    ],
     static_libs: [
         "tot_cronet_base_lifetime_java",
         "tot_cronet_base_tasks_java",
+        "tot_cronet_base_unowned_user_data_java__process_device",
         "tot_cronet_build_android_build_java",
     ],
     defaults: [
@@ -4519,20 +7198,103 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
 
-// GN: //base:unowned_user_data_java__testing
+// GN: //base:unowned_user_data_java__compile_java
 java_library {
-    name: "tot_cronet_base_unowned_user_data_java__testing",
+    name: "tot_cronet_base_unowned_user_data_java__compile_java",
     srcs: [
         "android/java/src/org/chromium/base/UnownedUserData.java",
         "android/java/src/org/chromium/base/UnownedUserDataHost.java",
         "android/java/src/org/chromium/base/UnownedUserDataKey.java",
     ],
+    defaults: [
+        "tot_cronet_java_framework_defaults",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java",
+        "tot_cronet_base_base_switches_java__compile_java",
+        "tot_cronet_base_callback_java__compile_java",
+        "tot_cronet_base_callback_jni_java__compile_java",
+        "tot_cronet_base_command_line_java__compile_java",
+        "tot_cronet_base_command_line_jni_java__compile_java",
+        "tot_cronet_base_lifetime_java__compile_java",
+        "tot_cronet_base_log_java__compile_java",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java",
+        "tot_cronet_base_metrics_java__compile_java",
+        "tot_cronet_base_metrics_jni_java__compile_java",
+        "tot_cronet_base_resetters_java__compile_java",
+        "tot_cronet_base_tasks_java__compile_java",
+        "tot_cronet_base_tasks_jni_java__compile_java",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java",
+        "tot_cronet_base_time_utils_java__compile_java",
+        "tot_cronet_build_android_build_java__compile_java",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java",
+    ],
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:unowned_user_data_java__compile_java__testing
+java_library {
+    name: "tot_cronet_base_unowned_user_data_java__compile_java__testing",
+    srcs: [
+        "android/java/src/org/chromium/base/UnownedUserData.java",
+        "android/java/src/org/chromium/base/UnownedUserDataHost.java",
+        "android/java/src/org/chromium/base/UnownedUserDataKey.java",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+    min_sdk_version: "30",
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.annotation_annotation-experimental",
+        "error_prone_annotations",
+        "tot_cronet_base_activity_state_java__compile_java__testing",
+        "tot_cronet_base_base_switches_java__compile_java__testing",
+        "tot_cronet_base_callback_java__compile_java__testing",
+        "tot_cronet_base_callback_jni_java__compile_java__testing",
+        "tot_cronet_base_command_line_java__compile_java__testing",
+        "tot_cronet_base_command_line_jni_java__compile_java__testing",
+        "tot_cronet_base_lifetime_java__compile_java__testing",
+        "tot_cronet_base_log_java__compile_java__testing",
+        "tot_cronet_base_metrics_ScopedSysTraceEvent_java__compile_java__testing",
+        "tot_cronet_base_metrics_java__compile_java__testing",
+        "tot_cronet_base_metrics_jni_java__compile_java__testing",
+        "tot_cronet_base_resetters_java__compile_java__testing",
+        "tot_cronet_base_tasks_java__compile_java__testing",
+        "tot_cronet_base_tasks_jni_java__compile_java__testing",
+        "tot_cronet_base_tasks_minimal_jni_java__compile_java__testing",
+        "tot_cronet_base_time_utils_java__compile_java__testing",
+        "tot_cronet_build_android_build_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_gendeps_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_generate_jni_java__compile_java__testing",
+        "tot_cronet_third_party_jni_zero_jni_zero_java__compile_java__testing",
+    ],
+    sdk_version: "current",
+    visibility: [
+        "//external/cronet:__subpackages__",
+    ],
+}
+
+// GN: //base:unowned_user_data_java__testing
+java_library {
+    name: "tot_cronet_base_unowned_user_data_java__testing",
     static_libs: [
         "tot_cronet_base_lifetime_java__testing",
         "tot_cronet_base_tasks_java__testing",
+        "tot_cronet_base_unowned_user_data_java__process_device__testing",
         "tot_cronet_build_android_build_java__testing",
     ],
     apex_available: [
@@ -4546,5 +7308,4 @@
     visibility: [
         "//external/cronet:__subpackages__",
     ],
-    jarjar_rules: ":remove_gen_jni_jarjar_rules",
 }
diff --git a/tot/base/allocator/dispatcher/configuration.h b/tot/base/allocator/dispatcher/configuration.h
index 34c3791..4488cf8 100644
--- a/tot/base/allocator/dispatcher/configuration.h
+++ b/tot/base/allocator/dispatcher/configuration.h
@@ -21,4 +21,4 @@
 
 }  // namespace base::allocator::dispatcher::configuration
 
-#endif  // BASE_ALLOCATOR_DISPATCHER_CONFIGURATION_H_
\ No newline at end of file
+#endif  // BASE_ALLOCATOR_DISPATCHER_CONFIGURATION_H_
diff --git a/tot/base/allocator/dispatcher/dispatcher.h b/tot/base/allocator/dispatcher/dispatcher.h
index b8fc677..ef46c79 100644
--- a/tot/base/allocator/dispatcher/dispatcher.h
+++ b/tot/base/allocator/dispatcher/dispatcher.h
@@ -5,11 +5,11 @@
 #ifndef BASE_ALLOCATOR_DISPATCHER_DISPATCHER_H_
 #define BASE_ALLOCATOR_DISPATCHER_DISPATCHER_H_
 
+#include <memory>
+
 #include "base/allocator/dispatcher/internal/dispatcher_internal.h"
 #include "base/base_export.h"
 
-#include <memory>
-
 namespace base::allocator::dispatcher {
 
 namespace internal {
diff --git a/tot/base/allocator/dispatcher/dispatcher_unittest.cc b/tot/base/allocator/dispatcher/dispatcher_unittest.cc
index 9fa9e64..9557d0e 100644
--- a/tot/base/allocator/dispatcher/dispatcher_unittest.cc
+++ b/tot/base/allocator/dispatcher/dispatcher_unittest.cc
@@ -135,7 +135,8 @@
   VerifyNotificationUsingAllocatorShim
 #endif
 
-TEST_F(BaseAllocatorDispatcherTest, MAYBE_VerifyNotificationUsingAllocatorShim) {
+TEST_F(BaseAllocatorDispatcherTest,
+       MAYBE_VerifyNotificationUsingAllocatorShim) {
   AllocatorShimAllocator allocator;
   DoBasicTest(allocator);
 }
diff --git a/tot/base/allocator/dispatcher/initializer.h b/tot/base/allocator/dispatcher/initializer.h
index d911463..a01646c 100644
--- a/tot/base/allocator/dispatcher/initializer.h
+++ b/tot/base/allocator/dispatcher/initializer.h
@@ -5,13 +5,13 @@
 #ifndef BASE_ALLOCATOR_DISPATCHER_INITIALIZER_H_
 #define BASE_ALLOCATOR_DISPATCHER_INITIALIZER_H_
 
+#include <tuple>
+#include <utility>
+
 #include "base/allocator/dispatcher/configuration.h"
 #include "base/allocator/dispatcher/dispatcher.h"
 #include "base/allocator/dispatcher/internal/tools.h"
 
-#include <tuple>
-#include <utility>
-
 namespace base::allocator::dispatcher {
 namespace internal {
 
diff --git a/tot/base/allocator/dispatcher/initializer_unittest.cc b/tot/base/allocator/dispatcher/initializer_unittest.cc
index 9adcd48..f15d3e6 100644
--- a/tot/base/allocator/dispatcher/initializer_unittest.cc
+++ b/tot/base/allocator/dispatcher/initializer_unittest.cc
@@ -2,17 +2,17 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "testing/gtest/include/gtest/gtest.h"
-
-#include "base/allocator/dispatcher/configuration.h"
 #include "base/allocator/dispatcher/initializer.h"
-#include "base/allocator/dispatcher/testing/observer_mock.h"
-#include "base/allocator/dispatcher/testing/tools.h"
 
 #include <functional>
 #include <map>
 #include <tuple>
 
+#include "base/allocator/dispatcher/configuration.h"
+#include "base/allocator/dispatcher/testing/observer_mock.h"
+#include "base/allocator/dispatcher/testing/tools.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
 namespace base::allocator::dispatcher {
 namespace testing {
 
diff --git a/tot/base/allocator/dispatcher/subsystem.h b/tot/base/allocator/dispatcher/subsystem.h
index 163961e..f9500bd 100644
--- a/tot/base/allocator/dispatcher/subsystem.h
+++ b/tot/base/allocator/dispatcher/subsystem.h
@@ -24,4 +24,4 @@
 };
 }  // namespace base::allocator::dispatcher
 
-#endif  // BASE_ALLOCATOR_DISPATCHER_SUBSYSTEM_H_
\ No newline at end of file
+#endif  // BASE_ALLOCATOR_DISPATCHER_SUBSYSTEM_H_
diff --git a/tot/base/allocator/dispatcher/testing/dispatcher_test.cc b/tot/base/allocator/dispatcher/testing/dispatcher_test.cc
index 9efa5c5..cc12f67 100644
--- a/tot/base/allocator/dispatcher/testing/dispatcher_test.cc
+++ b/tot/base/allocator/dispatcher/testing/dispatcher_test.cc
@@ -3,6 +3,7 @@
 // found in the LICENSE file.
 
 #include "base/allocator/dispatcher/testing/dispatcher_test.h"
+
 #include "base/allocator/dispatcher/reentry_guard.h"
 
 namespace base::allocator::dispatcher::testing {
@@ -13,4 +14,4 @@
 
 DispatcherTest::~DispatcherTest() = default;
 
-}  // namespace base::allocator::dispatcher::testing
\ No newline at end of file
+}  // namespace base::allocator::dispatcher::testing
diff --git a/tot/base/allocator/dispatcher/testing/dispatcher_test.h b/tot/base/allocator/dispatcher/testing/dispatcher_test.h
index 21fbd1a..9cc232e 100644
--- a/tot/base/allocator/dispatcher/testing/dispatcher_test.h
+++ b/tot/base/allocator/dispatcher/testing/dispatcher_test.h
@@ -24,4 +24,4 @@
 
 }  // namespace base::allocator::dispatcher::testing
 
-#endif  // BASE_ALLOCATOR_DISPATCHER_TESTING_DISPATCHER_TEST_H_
\ No newline at end of file
+#endif  // BASE_ALLOCATOR_DISPATCHER_TESTING_DISPATCHER_TEST_H_
diff --git a/tot/base/allocator/dispatcher/testing/observer_mock.h b/tot/base/allocator/dispatcher/testing/observer_mock.h
index 43ca6cb..a29ea7d 100644
--- a/tot/base/allocator/dispatcher/testing/observer_mock.h
+++ b/tot/base/allocator/dispatcher/testing/observer_mock.h
@@ -30,4 +30,4 @@
 }  // namespace testing
 }  // namespace base::allocator::dispatcher
 
-#endif  // BASE_ALLOCATOR_DISPATCHER_TESTING_OBSERVER_MOCK_H_
\ No newline at end of file
+#endif  // BASE_ALLOCATOR_DISPATCHER_TESTING_OBSERVER_MOCK_H_
diff --git a/tot/base/allocator/dispatcher/tls.cc b/tot/base/allocator/dispatcher/tls.cc
index 08e2995..18cdcaf 100644
--- a/tot/base/allocator/dispatcher/tls.cc
+++ b/tot/base/allocator/dispatcher/tls.cc
@@ -8,14 +8,14 @@
 
 #if USE_LOCAL_TLS_EMULATION()
 
+#include <sys/mman.h>
+
 #include "base/check.h"
 #include "base/dcheck_is_on.h"
 #include "base/debug/crash_logging.h"
 #include "base/immediate_crash.h"
 #include "build/build_config.h"
 
-#include <sys/mman.h>
-
 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX)
 #include <sys/prctl.h>
 #endif
diff --git a/tot/base/allocator/dispatcher/tls.h b/tot/base/allocator/dispatcher/tls.h
index 4a61136..483d4c5 100644
--- a/tot/base/allocator/dispatcher/tls.h
+++ b/tot/base/allocator/dispatcher/tls.h
@@ -17,8 +17,11 @@
 #endif
 
 #if USE_LOCAL_TLS_EMULATION()
+#include <pthread.h>
+
 #include <algorithm>
 #include <atomic>
+#include <functional>
 #include <memory>
 #include <mutex>
 
@@ -30,8 +33,6 @@
 #include "partition_alloc/partition_alloc_constants.h"  // nogncheck
 #endif
 
-#include <pthread.h>
-
 #if HAS_FEATURE(thread_sanitizer)
 #define DISABLE_TSAN_INSTRUMENTATION __attribute__((no_sanitize("thread")))
 #else
diff --git a/tot/base/allocator/partition_alloc_features.cc b/tot/base/allocator/partition_alloc_features.cc
index 233504e..1b79c3b 100644
--- a/tot/base/allocator/partition_alloc_features.cc
+++ b/tot/base/allocator/partition_alloc_features.cc
@@ -12,7 +12,6 @@
 #include "base/time/time.h"
 #include "build/build_config.h"
 #include "build/chromecast_buildflags.h"
-#include "build/chromeos_buildflags.h"
 #include "partition_alloc/buildflags.h"
 #include "partition_alloc/partition_alloc_base/time/time.h"
 #include "partition_alloc/partition_alloc_constants.h"
@@ -20,8 +19,7 @@
 #include "partition_alloc/shim/allocator_shim_dispatch_to_noop_on_free.h"
 #include "partition_alloc/thread_cache.h"
 
-namespace base {
-namespace features {
+namespace base::features {
 
 namespace {
 
@@ -48,7 +46,8 @@
         {UnretainedDanglingPtrMode::kDumpWithoutCrashing,
          "dump_without_crashing"},
 };
-const base::FeatureParam<UnretainedDanglingPtrMode>
+// Note: Do not use the prepared macro as of no need for a local cache.
+constinit const FeatureParam<UnretainedDanglingPtrMode>
     kUnretainedDanglingPtrModeParam = {
         &kPartitionAllocUnretainedDanglingPtr,
         "mode",
@@ -73,7 +72,8 @@
     {DanglingPtrMode::kCrash, "crash"},
     {DanglingPtrMode::kLogOnly, "log_only"},
 };
-const base::FeatureParam<DanglingPtrMode> kDanglingPtrModeParam{
+// Note: Do not use the prepared macro as of no need for a local cache.
+constinit const FeatureParam<DanglingPtrMode> kDanglingPtrModeParam{
     &kPartitionAllocDanglingPtr,
     "mode",
     DanglingPtrMode::kCrash,
@@ -83,7 +83,8 @@
     {DanglingPtrType::kAll, "all"},
     {DanglingPtrType::kCrossTask, "cross_task"},
 };
-const base::FeatureParam<DanglingPtrType> kDanglingPtrTypeParam{
+// Note: Do not use the prepared macro as of no need for a local cache.
+constinit const FeatureParam<DanglingPtrType> kDanglingPtrTypeParam{
     &kPartitionAllocDanglingPtr,
     "type",
     DanglingPtrType::kAll,
@@ -109,7 +110,7 @@
 
 BASE_FEATURE(kPartitionAllocLargeEmptySlotSpanRing,
              "PartitionAllocLargeEmptySlotSpanRing",
-#if BUILDFLAG(IS_MAC)
+#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
              FEATURE_ENABLED_BY_DEFAULT);
 #else
              FEATURE_DISABLED_BY_DEFAULT);
@@ -128,7 +129,8 @@
          kNonRendererStr},
         {PartitionAllocWithAdvancedChecksEnabledProcesses::kAllProcesses,
          kAllProcessesStr}};
-const base::FeatureParam<PartitionAllocWithAdvancedChecksEnabledProcesses>
+// Note: Do not use the prepared macro as of no need for a local cache.
+constinit const FeatureParam<PartitionAllocWithAdvancedChecksEnabledProcesses>
     kPartitionAllocWithAdvancedChecksEnabledProcessesParam{
         &kPartitionAllocWithAdvancedChecks, kPAFeatureEnabledProcessesStr,
         PartitionAllocWithAdvancedChecksEnabledProcesses::kBrowserOnly,
@@ -138,10 +140,17 @@
              "PartitionAllocSchedulerLoopQuarantine",
              FEATURE_DISABLED_BY_DEFAULT);
 // Scheduler Loop Quarantine's per-branch capacity in bytes.
-const base::FeatureParam<int>
+// Note: Do not use the prepared macro as of no need for a local cache.
+constinit const FeatureParam<int>
     kPartitionAllocSchedulerLoopQuarantineBranchCapacity{
         &kPartitionAllocSchedulerLoopQuarantine,
         "PartitionAllocSchedulerLoopQuarantineBranchCapacity", 0};
+// Scheduler Loop Quarantine's capacity for the UI thread in bytes.
+BASE_FEATURE_PARAM(int,
+                   kPartitionAllocSchedulerLoopQuarantineBrowserUICapacity,
+                   &kPartitionAllocSchedulerLoopQuarantine,
+                   "PartitionAllocSchedulerLoopQuarantineBrowserUICapacity",
+                   0);
 
 BASE_FEATURE(kPartitionAllocZappingByFreeFlags,
              "PartitionAllocZappingByFreeFlags",
@@ -150,6 +159,10 @@
 BASE_FEATURE(kPartitionAllocEventuallyZeroFreedMemory,
              "PartitionAllocEventuallyZeroFreedMemory",
              FEATURE_DISABLED_BY_DEFAULT);
+
+BASE_FEATURE(kPartitionAllocFewerMemoryRegions,
+             "PartitionAllocFewerMemoryRegions",
+             FEATURE_DISABLED_BY_DEFAULT);
 #endif  // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
 
 BASE_FEATURE(kPartitionAllocBackupRefPtr,
@@ -169,24 +182,31 @@
         {BackupRefPtrEnabledProcesses::kNonRenderer, kNonRendererStr},
         {BackupRefPtrEnabledProcesses::kAllProcesses, kAllProcessesStr}};
 
-const base::FeatureParam<BackupRefPtrEnabledProcesses>
-    kBackupRefPtrEnabledProcessesParam{
-        &kPartitionAllocBackupRefPtr, kPAFeatureEnabledProcessesStr,
+BASE_FEATURE_ENUM_PARAM(BackupRefPtrEnabledProcesses,
+                        kBackupRefPtrEnabledProcessesParam,
+                        &kPartitionAllocBackupRefPtr,
+                        kPAFeatureEnabledProcessesStr,
 #if PA_BUILDFLAG(IS_MAC) && PA_BUILDFLAG(PA_ARCH_CPU_ARM64)
-        BackupRefPtrEnabledProcesses::kNonRenderer,
+                        BackupRefPtrEnabledProcesses::kNonRenderer,
 #else
-        BackupRefPtrEnabledProcesses::kAllProcesses,
+                        BackupRefPtrEnabledProcesses::kAllProcesses,
 #endif
-        &kBackupRefPtrEnabledProcessesOptions};
+                        &kBackupRefPtrEnabledProcessesOptions);
 
 constexpr FeatureParam<BackupRefPtrMode>::Option kBackupRefPtrModeOptions[] = {
     {BackupRefPtrMode::kDisabled, "disabled"},
     {BackupRefPtrMode::kEnabled, "enabled"},
 };
 
-const base::FeatureParam<BackupRefPtrMode> kBackupRefPtrModeParam{
-    &kPartitionAllocBackupRefPtr, "brp-mode", BackupRefPtrMode::kEnabled,
-    &kBackupRefPtrModeOptions};
+BASE_FEATURE_ENUM_PARAM(BackupRefPtrMode,
+                        kBackupRefPtrModeParam,
+                        &kPartitionAllocBackupRefPtr,
+                        "brp-mode",
+                        BackupRefPtrMode::kEnabled,
+                        &kBackupRefPtrModeOptions);
+// Note: Do not use the prepared macro as of no need for a local cache.
+constinit const FeatureParam<int> kBackupRefPtrExtraExtrasSizeParam{
+    &kPartitionAllocBackupRefPtr, "brp-extra-extras-size", 0};
 
 BASE_FEATURE(kPartitionAllocMemoryTagging,
              "PartitionAllocMemoryTagging",
@@ -201,7 +221,8 @@
     {MemtagMode::kSync, "sync"},
     {MemtagMode::kAsync, "async"}};
 
-const base::FeatureParam<MemtagMode> kMemtagModeParam{
+// Note: Do not use the prepared macro as of no need for a local cache.
+constinit const FeatureParam<MemtagMode> kMemtagModeParam{
     &kPartitionAllocMemoryTagging, "memtag-mode",
 #if PA_BUILDFLAG(USE_FULL_MTE)
     MemtagMode::kSync,
@@ -215,7 +236,8 @@
     {RetagMode::kRandom, "random"},
 };
 
-const base::FeatureParam<RetagMode> kRetagModeParam{
+// Note: Do not use the prepared macro as of no need for a local cache.
+constinit const FeatureParam<RetagMode> kRetagModeParam{
     &kPartitionAllocMemoryTagging, "retag-mode", RetagMode::kIncrement,
     &kRetagModeOptions};
 
@@ -225,7 +247,8 @@
         {MemoryTaggingEnabledProcesses::kNonRenderer, kNonRendererStr},
         {MemoryTaggingEnabledProcesses::kAllProcesses, kAllProcessesStr}};
 
-const base::FeatureParam<MemoryTaggingEnabledProcesses>
+// Note: Do not use the prepared macro as of no need for a local cache.
+constinit const FeatureParam<MemoryTaggingEnabledProcesses>
     kMemoryTaggingEnabledProcessesParam{
         &kPartitionAllocMemoryTagging, kPAFeatureEnabledProcessesStr,
 #if PA_BUILDFLAG(USE_FULL_MTE)
@@ -250,13 +273,15 @@
 #endif
 );
 
-const base::FeatureParam<bool> kBackupRefPtrAsanEnableDereferenceCheckParam{
-    &kPartitionAllocBackupRefPtr, "asan-enable-dereference-check", true};
-const base::FeatureParam<bool> kBackupRefPtrAsanEnableExtractionCheckParam{
-    &kPartitionAllocBackupRefPtr, "asan-enable-extraction-check",
-    false};  // Not much noise at the moment to enable by default.
-const base::FeatureParam<bool> kBackupRefPtrAsanEnableInstantiationCheckParam{
-    &kPartitionAllocBackupRefPtr, "asan-enable-instantiation-check", true};
+BASE_FEATURE(kAsanBrpDereferenceCheck,
+             "AsanBrpDereferenceCheck",
+             FEATURE_ENABLED_BY_DEFAULT);
+BASE_FEATURE(kAsanBrpExtractionCheck,
+             "AsanBrpExtractionCheck",      // Not much noise at the moment to
+             FEATURE_DISABLED_BY_DEFAULT);  // enable by default.
+BASE_FEATURE(kAsanBrpInstantiationCheck,
+             "AsanBrpInstantiationCheck",
+             FEATURE_ENABLED_BY_DEFAULT);
 
 // If enabled, switches the bucket distribution to a denser one.
 //
@@ -270,29 +295,31 @@
              FEATURE_ENABLED_BY_DEFAULT
 #endif  // BUILDFLAG(IS_ANDROID) && defined(ARCH_CPU_32_BITS)
 );
-const base::FeatureParam<BucketDistributionMode>::Option
+const FeatureParam<BucketDistributionMode>::Option
     kPartitionAllocBucketDistributionOption[] = {
         {BucketDistributionMode::kDefault, "default"},
         {BucketDistributionMode::kDenser, "denser"},
 };
-const base::FeatureParam<BucketDistributionMode>
-    kPartitionAllocBucketDistributionParam {
-  &kPartitionAllocUseDenserDistribution, "mode",
+// Note: Do not use the prepared macro as of no need for a local cache.
+constinit const FeatureParam<BucketDistributionMode>
+    kPartitionAllocBucketDistributionParam{
+        &kPartitionAllocUseDenserDistribution, "mode",
 #if BUILDFLAG(IS_ANDROID) && defined(ARCH_CPU_32_BITS)
-      BucketDistributionMode::kDefault,
+        BucketDistributionMode::kDefault,
 #else
-      BucketDistributionMode::kDenser,
+        BucketDistributionMode::kDenser,
 #endif  // BUILDFLAG(IS_ANDROID) && defined(ARCH_CPU_32_BITS)
-      &kPartitionAllocBucketDistributionOption
-};
+        &kPartitionAllocBucketDistributionOption};
 
 BASE_FEATURE(kPartitionAllocMemoryReclaimer,
              "PartitionAllocMemoryReclaimer",
              FEATURE_ENABLED_BY_DEFAULT);
-const base::FeatureParam<TimeDelta> kPartitionAllocMemoryReclaimerInterval = {
-    &kPartitionAllocMemoryReclaimer, "interval",
-    TimeDelta(),  // Defaults to zero.
-};
+BASE_FEATURE_PARAM(TimeDelta,
+                   kPartitionAllocMemoryReclaimerInterval,
+                   &kPartitionAllocMemoryReclaimer,
+                   "interval",
+                   TimeDelta()  // Defaults to zero.
+);
 
 // Configures whether we set a lower limit for renderers that do not have a main
 // frame, similar to the limit that is already done for backgrounded renderers.
@@ -305,16 +332,17 @@
 BASE_FEATURE(kPartitionAllocStraightenLargerSlotSpanFreeLists,
              "PartitionAllocStraightenLargerSlotSpanFreeLists",
              FEATURE_ENABLED_BY_DEFAULT);
-const base::FeatureParam<
-    partition_alloc::StraightenLargerSlotSpanFreeListsMode>::Option
-    kPartitionAllocStraightenLargerSlotSpanFreeListsModeOption[] = {
+const FeatureParam<partition_alloc::StraightenLargerSlotSpanFreeListsMode>::
+    Option kPartitionAllocStraightenLargerSlotSpanFreeListsModeOption[] = {
         {partition_alloc::StraightenLargerSlotSpanFreeListsMode::
              kOnlyWhenUnprovisioning,
          "only-when-unprovisioning"},
         {partition_alloc::StraightenLargerSlotSpanFreeListsMode::kAlways,
          "always"},
 };
-const base::FeatureParam<partition_alloc::StraightenLargerSlotSpanFreeListsMode>
+// Note: Do not use the prepared macro as of no need for a local cache.
+constinit const FeatureParam<
+    partition_alloc::StraightenLargerSlotSpanFreeListsMode>
     kPartitionAllocStraightenLargerSlotSpanFreeListsMode = {
         &kPartitionAllocStraightenLargerSlotSpanFreeLists,
         "mode",
@@ -347,9 +375,11 @@
 // The feature: kPartialLowEndModeOnMidRangeDevices is defined in
 // //base/features.cc. Since the following feature param is related to
 // PartitionAlloc, define the param here.
-const FeatureParam<bool> kPartialLowEndModeExcludePartitionAllocSupport{
-    &kPartialLowEndModeOnMidRangeDevices, "exclude-partition-alloc-support",
-    false};
+BASE_FEATURE_PARAM(bool,
+                   kPartialLowEndModeExcludePartitionAllocSupport,
+                   &kPartialLowEndModeOnMidRangeDevices,
+                   "exclude-partition-alloc-support",
+                   false);
 #endif
 
 BASE_FEATURE(kEnableConfigurableThreadCacheMultiplier,
@@ -367,19 +397,19 @@
                              1.)
 
 constexpr partition_alloc::internal::base::TimeDelta ToPartitionAllocTimeDelta(
-    base::TimeDelta time_delta) {
+    TimeDelta time_delta) {
   return partition_alloc::internal::base::Microseconds(
       time_delta.InMicroseconds());
 }
 
-constexpr base::TimeDelta FromPartitionAllocTimeDelta(
+constexpr TimeDelta FromPartitionAllocTimeDelta(
     partition_alloc::internal::base::TimeDelta time_delta) {
-  return base::Microseconds(time_delta.InMicroseconds());
+  return Microseconds(time_delta.InMicroseconds());
 }
 
 BASE_FEATURE(kEnableConfigurableThreadCachePurgeInterval,
              "EnableConfigurableThreadCachePurgeInterval",
-             base::FEATURE_DISABLED_BY_DEFAULT);
+             FEATURE_DISABLED_BY_DEFAULT);
 
 MIRACLE_PARAMETER_FOR_TIME_DELTA(
     GetThreadCacheMinPurgeIntervalValue,
@@ -416,7 +446,7 @@
 
 BASE_FEATURE(kEnableConfigurableThreadCacheMinCachedMemoryForPurging,
              "EnableConfigurableThreadCacheMinCachedMemoryForPurging",
-             base::FEATURE_DISABLED_BY_DEFAULT);
+             FEATURE_DISABLED_BY_DEFAULT);
 
 MIRACLE_PARAMETER_FOR_INT(
     GetThreadCacheMinCachedMemoryForPurgingBytes,
@@ -436,20 +466,9 @@
              "PartitionAllocDisableBRPInBufferPartition",
              FEATURE_DISABLED_BY_DEFAULT);
 
-#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER)
-BASE_FEATURE(kUsePoolOffsetFreelists,
-             "PartitionAllocUsePoolOffsetFreelists",
-#if BUILDFLAG(IS_ANDROID)
-             base::FEATURE_DISABLED_BY_DEFAULT
-#else
-             base::FEATURE_ENABLED_BY_DEFAULT
-#endif
-);
-#endif
-
 BASE_FEATURE(kPartitionAllocAdjustSizeWhenInForeground,
              "PartitionAllocAdjustSizeWhenInForeground",
-#if BUILDFLAG(IS_MAC)
+#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
              FEATURE_ENABLED_BY_DEFAULT);
 #else
              FEATURE_DISABLED_BY_DEFAULT);
@@ -457,12 +476,12 @@
 
 BASE_FEATURE(kPartitionAllocUseSmallSingleSlotSpans,
              "PartitionAllocUseSmallSingleSlotSpans",
-             base::FEATURE_DISABLED_BY_DEFAULT);
+             FEATURE_ENABLED_BY_DEFAULT);
 
 #if PA_CONFIG(ENABLE_SHADOW_METADATA)
 BASE_FEATURE(kPartitionAllocShadowMetadata,
              "PartitionAllocShadowMetadata",
-             base::FEATURE_DISABLED_BY_DEFAULT);
+             FEATURE_DISABLED_BY_DEFAULT);
 
 constexpr FeatureParam<ShadowMetadataEnabledProcesses>::Option
     kShadowMetadataEnabledProcessesOptions[] = {
@@ -470,12 +489,12 @@
         {ShadowMetadataEnabledProcesses::kAllChildProcesses,
          kAllChildProcessesStr}};
 
-const base::FeatureParam<ShadowMetadataEnabledProcesses>
+// Note: Do not use the prepared macro as of no need for a local cache.
+constinit const FeatureParam<ShadowMetadataEnabledProcesses>
     kShadowMetadataEnabledProcessesParam{
         &kPartitionAllocShadowMetadata, kPAFeatureEnabledProcessesStr,
         ShadowMetadataEnabledProcesses::kRendererOnly,
         &kShadowMetadataEnabledProcessesOptions};
 #endif  // PA_CONFIG(ENABLE_SHADOW_METADATA)
 
-}  // namespace features
-}  // namespace base
+}  // namespace base::features
diff --git a/tot/base/allocator/partition_alloc_features.h b/tot/base/allocator/partition_alloc_features.h
index 619392d..61ef1f3 100644
--- a/tot/base/allocator/partition_alloc_features.h
+++ b/tot/base/allocator/partition_alloc_features.h
@@ -15,8 +15,7 @@
 #include "partition_alloc/partition_alloc_base/time/time.h"
 #include "partition_alloc/partition_root.h"
 
-namespace base {
-namespace features {
+namespace base::features {
 
 namespace internal {
 
@@ -37,13 +36,13 @@
 
 }  // namespace internal
 
-extern const BASE_EXPORT Feature kPartitionAllocUnretainedDanglingPtr;
+BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocUnretainedDanglingPtr);
 enum class UnretainedDanglingPtrMode {
   kCrash,
   kDumpWithoutCrashing,
 };
-extern const BASE_EXPORT base::FeatureParam<UnretainedDanglingPtrMode>
-    kUnretainedDanglingPtrModeParam;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(UnretainedDanglingPtrMode,
+                                       kUnretainedDanglingPtrModeParam);
 
 // See /docs/dangling_ptr.md
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocDanglingPtr);
@@ -62,8 +61,7 @@
 
   // Note: This will be extended with a single shot DumpWithoutCrashing.
 };
-extern const BASE_EXPORT base::FeatureParam<DanglingPtrMode>
-    kDanglingPtrModeParam;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(DanglingPtrMode, kDanglingPtrModeParam);
 enum class DanglingPtrType {
   // Act on any dangling raw_ptr released after being freed.
   kAll,  // (default)
@@ -74,8 +72,7 @@
 
   // Note: This will be extended with LongLived
 };
-extern const BASE_EXPORT base::FeatureParam<DanglingPtrType>
-    kDanglingPtrTypeParam;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(DanglingPtrType, kDanglingPtrTypeParam);
 
 using PartitionAllocWithAdvancedChecksEnabledProcesses =
     internal::PAFeatureEnabledProcesses;
@@ -88,13 +85,19 @@
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocLargeEmptySlotSpanRing);
 
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocWithAdvancedChecks);
-extern const BASE_EXPORT
-    base::FeatureParam<PartitionAllocWithAdvancedChecksEnabledProcesses>
-        kPartitionAllocWithAdvancedChecksEnabledProcessesParam;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(
+    PartitionAllocWithAdvancedChecksEnabledProcesses,
+    kPartitionAllocWithAdvancedChecksEnabledProcessesParam);
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocSchedulerLoopQuarantine);
 // Scheduler Loop Quarantine's per-thread capacity in bytes.
-extern const BASE_EXPORT base::FeatureParam<int>
-    kPartitionAllocSchedulerLoopQuarantineBranchCapacity;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(
+    int,
+    kPartitionAllocSchedulerLoopQuarantineBranchCapacity);
+// Scheduler Loop Quarantine's capacity for the UI thread in bytes.
+// TODO(https://crbug.com/387470567): Support more thread types.
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(
+    int,
+    kPartitionAllocSchedulerLoopQuarantineBrowserUICapacity);
 
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocZappingByFreeFlags);
 
@@ -102,6 +105,11 @@
 // security guarantee, but to increase the compression ratio of PartitionAlloc's
 // fragmented super pages.
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocEventuallyZeroFreedMemory);
+
+// Whether to make PartitionAlloc use fewer memory regions. This matters on
+// Linux-based systems, where there is a per-process limit that we hit in some
+// cases. See the comment in PartitionBucket::SlotSpanCOmmitedSize() for detail.
+BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocFewerMemoryRegions);
 #endif  // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
 
 using BackupRefPtrEnabledProcesses = internal::PAFeatureEnabledProcesses;
@@ -139,39 +147,38 @@
 };
 
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocBackupRefPtr);
-extern const BASE_EXPORT base::FeatureParam<BackupRefPtrEnabledProcesses>
-    kBackupRefPtrEnabledProcessesParam;
-extern const BASE_EXPORT base::FeatureParam<BackupRefPtrMode>
-    kBackupRefPtrModeParam;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(BackupRefPtrEnabledProcesses,
+                                       kBackupRefPtrEnabledProcessesParam);
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(BackupRefPtrMode,
+                                       kBackupRefPtrModeParam);
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(int,
+                                       kBackupRefPtrExtraExtrasSizeParam);
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocMemoryTagging);
-extern const BASE_EXPORT base::FeatureParam<MemtagMode> kMemtagModeParam;
-extern const BASE_EXPORT base::FeatureParam<RetagMode> kRetagModeParam;
-extern const BASE_EXPORT base::FeatureParam<MemoryTaggingEnabledProcesses>
-    kMemoryTaggingEnabledProcessesParam;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(MemtagMode, kMemtagModeParam);
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(RetagMode, kRetagModeParam);
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(MemoryTaggingEnabledProcesses,
+                                       kMemoryTaggingEnabledProcessesParam);
 // Kill switch for memory tagging. Skips any code related to memory tagging when
 // enabled.
 BASE_EXPORT BASE_DECLARE_FEATURE(kKillPartitionAllocMemoryTagging);
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocPermissiveMte);
-extern const BASE_EXPORT base::FeatureParam<bool>
-    kBackupRefPtrAsanEnableDereferenceCheckParam;
-extern const BASE_EXPORT base::FeatureParam<bool>
-    kBackupRefPtrAsanEnableExtractionCheckParam;
-extern const BASE_EXPORT base::FeatureParam<bool>
-    kBackupRefPtrAsanEnableInstantiationCheckParam;
-extern const BASE_EXPORT base::FeatureParam<BucketDistributionMode>
-    kPartitionAllocBucketDistributionParam;
+BASE_EXPORT BASE_DECLARE_FEATURE(kAsanBrpDereferenceCheck);
+BASE_EXPORT BASE_DECLARE_FEATURE(kAsanBrpExtractionCheck);
+BASE_EXPORT BASE_DECLARE_FEATURE(kAsanBrpInstantiationCheck);
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(BucketDistributionMode,
+                                       kPartitionAllocBucketDistributionParam);
 
 BASE_EXPORT BASE_DECLARE_FEATURE(kLowerPAMemoryLimitForNonMainRenderers);
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocUseDenserDistribution);
 
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocMemoryReclaimer);
-extern const BASE_EXPORT base::FeatureParam<TimeDelta>
-    kPartitionAllocMemoryReclaimerInterval;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(TimeDelta,
+                                       kPartitionAllocMemoryReclaimerInterval);
 BASE_EXPORT BASE_DECLARE_FEATURE(
     kPartitionAllocStraightenLargerSlotSpanFreeLists);
-extern const BASE_EXPORT
-    base::FeatureParam<partition_alloc::StraightenLargerSlotSpanFreeListsMode>
-        kPartitionAllocStraightenLargerSlotSpanFreeListsMode;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(
+    partition_alloc::StraightenLargerSlotSpanFreeListsMode,
+    kPartitionAllocStraightenLargerSlotSpanFreeListsMode);
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocSortSmallerSlotSpanFreeLists);
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocSortActiveSlotSpans);
 
@@ -180,8 +187,9 @@
 #endif
 
 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
-extern const base::FeatureParam<bool>
-    kPartialLowEndModeExcludePartitionAllocSupport;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(
+    bool,
+    kPartialLowEndModeExcludePartitionAllocSupport);
 #endif
 
 BASE_EXPORT BASE_DECLARE_FEATURE(kEnableConfigurableThreadCacheMultiplier);
@@ -202,13 +210,6 @@
 
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocDisableBRPInBufferPartition);
 
-// This feature is additionally gated behind a buildflag because
-// pool offset freelists cannot be represented when PartitionAlloc uses
-// 32-bit pointers.
-#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER)
-BASE_EXPORT BASE_DECLARE_FEATURE(kUsePoolOffsetFreelists);
-#endif
-
 // When set, partitions use a larger ring buffer and free memory less
 // aggressively when in the foreground.
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocAdjustSizeWhenInForeground);
@@ -223,11 +224,10 @@
 using ShadowMetadataEnabledProcesses = internal::PAFeatureEnabledProcesses;
 
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartitionAllocShadowMetadata);
-extern const BASE_EXPORT base::FeatureParam<ShadowMetadataEnabledProcesses>
-    kShadowMetadataEnabledProcessesParam;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(ShadowMetadataEnabledProcesses,
+                                       kShadowMetadataEnabledProcessesParam);
 #endif  // PA_CONFIG(ENABLE_SHADOW_METADATA)
 
-}  // namespace features
-}  // namespace base
+}  // namespace base::features
 
 #endif  // BASE_ALLOCATOR_PARTITION_ALLOC_FEATURES_H_
diff --git a/tot/base/allocator/partition_alloc_support.cc b/tot/base/allocator/partition_alloc_support.cc
index 878a9f5..7023179 100644
--- a/tot/base/allocator/partition_alloc_support.cc
+++ b/tot/base/allocator/partition_alloc_support.cc
@@ -4,6 +4,7 @@
 
 #include "base/allocator/partition_alloc_support.h"
 
+#include <algorithm>
 #include <array>
 #include <cinttypes>
 #include <cstdint>
@@ -31,7 +32,6 @@
 #include "base/metrics/histogram_macros.h"
 #include "base/no_destructor.h"
 #include "base/pending_task.h"
-#include "base/ranges/algorithm.h"
 #include "base/strings/string_split.h"
 #include "base/strings/stringprintf.h"
 #include "base/system/sys_info.h"
@@ -107,12 +107,9 @@
 }
 #endif
 
-// When under this experiment avoid running periodic purging or reclaim for the
-// first minute after the first attempt. This is based on the insight that
-// processes often don't live paste this minute.
-static BASE_FEATURE(kDelayFirstPeriodicPAPurgeOrReclaim,
-                    "DelayFirstPeriodicPAPurgeOrReclaim",
-                    base::FEATURE_ENABLED_BY_DEFAULT);
+// Avoid running periodic purging or reclaim for the first minute after the
+// first attempt. This is based on the insight that processes often don't live
+// paste this minute.
 constexpr base::TimeDelta kFirstPAPurgeOrReclaimDelay = base::Minutes(1);
 
 // This is defined in content/public/common/content_switches.h, which is not
@@ -171,6 +168,8 @@
     return;
   }
 
+  task_runner_ = task_runner;
+
   // The caller of the API fully controls where running the reclaim.
   // However there are a few reasons to recommend that the caller runs
   // it on the main thread:
@@ -186,13 +185,7 @@
   // seconds is useful. Since this is meant to run during idle time only, it is
   // a reasonable starting point balancing effectivenes vs cost. See
   // crbug.com/942512 for details and experimental results.
-  TimeDelta delay;
-  if (base::FeatureList::IsEnabled(kDelayFirstPeriodicPAPurgeOrReclaim)) {
-    delay = std::max(delay, kFirstPAPurgeOrReclaimDelay);
-  }
-
-  task_runner_ = task_runner;
-  MaybeScheduleTask(delay);
+  MaybeScheduleTask(kFirstPAPurgeOrReclaimDelay);
 }
 
 void MemoryReclaimerSupport::SetForegrounded(bool in_foreground) {
@@ -253,12 +246,9 @@
 
 void StartThreadCachePeriodicPurge() {
   auto& instance = ::partition_alloc::ThreadCacheRegistry::Instance();
-  TimeDelta delay =
-      Microseconds(instance.GetPeriodicPurgeNextIntervalInMicroseconds());
-
-  if (base::FeatureList::IsEnabled(kDelayFirstPeriodicPAPurgeOrReclaim)) {
-    delay = std::max(delay, kFirstPAPurgeOrReclaimDelay);
-  }
+  TimeDelta delay = std::max(
+      Microseconds(instance.GetPeriodicPurgeNextIntervalInMicroseconds()),
+      kFirstPAPurgeOrReclaimDelay);
 
   SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
       FROM_HERE, BindOnce(RunThreadCachePeriodicPurge), delay);
@@ -465,7 +455,7 @@
   size_t caller_index = 0;
   for (size_t i = 0; i < lines.size(); ++i) {
     for (const auto& patterns : callee_patterns) {
-      if (ranges::all_of(patterns, [&](std::string_view pattern) {
+      if (std::ranges::all_of(patterns, [&](std::string_view pattern) {
             return lines[i].find(pattern) != std::string_view::npos;
           })) {
         caller_index = i + 1;
@@ -667,7 +657,7 @@
     std::vector<std::array<const void*, 32>> stack_traces =
         internal::InstanceTracer::GetStackTracesForDanglingRefs(entry->id);
     for (const auto& raw_stack_trace : stack_traces) {
-      CHECK(ranges::is_partitioned(raw_stack_trace, is_frame_ptr_not_null))
+      CHECK(std::ranges::is_partitioned(raw_stack_trace, is_frame_ptr_not_null))
           << "`raw_stack_trace` is expected to be partitioned: non-null values "
              "at the begining followed by `nullptr`s.";
       LOG(ERROR) << "Dangling reference from:\n";
@@ -675,8 +665,8 @@
                         // This call truncates the `nullptr` tail of the stack
                         // trace (see the `is_partitioned` CHECK above).
                         span(raw_stack_trace.begin(),
-                             ranges::partition_point(raw_stack_trace,
-                                                     is_frame_ptr_not_null)))
+                             std::ranges::partition_point(
+                                 raw_stack_trace, is_frame_ptr_not_null)))
                  << "\n";
     }
 #else
@@ -880,36 +870,28 @@
   // TODO(bartekn): Switch to DCHECK once confirmed there are no issues.
   CHECK(base::FeatureList::GetInstance());
 
-  bool process_affected_by_brp_flag = false;
-#if (PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) &&          \
-     PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) &&          \
-     !PA_BUILDFLAG(FORCE_DISABLE_BACKUP_REF_PTR_FEATURE)) || \
-    PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
-  if (base::FeatureList::IsEnabled(
-          base::features::kPartitionAllocBackupRefPtr)) {
-    // No specified process type means this is the Browser process.
-    process_affected_by_brp_flag = ShouldEnableFeatureOnProcess(
-        base::features::kBackupRefPtrEnabledProcessesParam.Get(), process_type);
-  }
-#endif  // (PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) &&
-        // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)&&
-        // !PA_BUILDFLAG(FORCE_DISABLE_BACKUP_REF_PTR_FEATURE)) ||
-        // PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
-
-  const bool enable_brp =
 #if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \
-    PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
-      // kDisabled is equivalent to !IsEnabled(kPartitionAllocBackupRefPtr).
-      process_affected_by_brp_flag &&
+    PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && \
+    !PA_BUILDFLAG(FORCE_DISABLE_BACKUP_REF_PTR_FEATURE)
+
+  if (base::FeatureList::IsEnabled(
+          base::features::kPartitionAllocBackupRefPtr) &&
       base::features::kBackupRefPtrModeParam.Get() !=
-          base::features::BackupRefPtrMode::kDisabled;
-#else
-      false;
+          base::features::BackupRefPtrMode::kDisabled &&
+      ShouldEnableFeatureOnProcess(
+          base::features::kBackupRefPtrEnabledProcessesParam.Get(),
+          process_type)) {
+    return {
+        .enable_brp = true,
+        .extra_extras_size = static_cast<size_t>(
+            base::features::kBackupRefPtrExtraExtrasSizeParam.Get()),
+    };
+  }
 #endif
 
   return {
-      enable_brp,
-      process_affected_by_brp_flag,
+      .enable_brp = false,
+      .extra_extras_size = 0,
   };
 }
 
@@ -1012,20 +994,26 @@
   [[maybe_unused]] BrpConfiguration brp_config =
       GetBrpConfiguration(process_type);
 
-#if PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
-  if (brp_config.process_affected_by_brp_flag) {
-    base::RawPtrAsanService::GetInstance().Configure(
-        base::EnableDereferenceCheck(
-            base::features::kBackupRefPtrAsanEnableDereferenceCheckParam.Get()),
-        base::EnableExtractionCheck(
-            base::features::kBackupRefPtrAsanEnableExtractionCheckParam.Get()),
-        base::EnableInstantiationCheck(
-            base::features::kBackupRefPtrAsanEnableInstantiationCheckParam
-                .Get()));
+  // Configure ASAN hooks to report the `MiraclePtr status`. This is enabled
+  // only if BackupRefPtr is normally enabled in the current process for the
+  // current platform. Note that CastOS and iOS aren't protected by BackupRefPtr
+  // a the moment, so they are excluded.
+#if PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) && !PA_BUILDFLAG(IS_CASTOS) && \
+    !PA_BUILDFLAG(IS_IOS)
+  if (ShouldEnableFeatureOnProcess(
+          base::features::kBackupRefPtrEnabledProcessesParam.Get(),
+          process_type)) {
+    RawPtrAsanService::GetInstance().Configure(
+        EnableDereferenceCheck(
+            FeatureList::IsEnabled(features::kAsanBrpDereferenceCheck)),
+        EnableExtractionCheck(
+            FeatureList::IsEnabled(features::kAsanBrpExtractionCheck)),
+        EnableInstantiationCheck(
+            FeatureList::IsEnabled(features::kAsanBrpInstantiationCheck)));
   } else {
-    base::RawPtrAsanService::GetInstance().Configure(
-        base::EnableDereferenceCheck(false), base::EnableExtractionCheck(false),
-        base::EnableInstantiationCheck(false));
+    RawPtrAsanService::GetInstance().Configure(EnableDereferenceCheck(false),
+                                               EnableExtractionCheck(false),
+                                               EnableInstantiationCheck(false));
   }
 #endif  // PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
 
@@ -1052,13 +1040,8 @@
       base::features::kPartitionAllocZappingByFreeFlags);
   const bool eventually_zero_freed_memory = base::FeatureList::IsEnabled(
       base::features::kPartitionAllocEventuallyZeroFreedMemory);
-
-#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER)
-  const bool use_pool_offset_freelists =
-      base::FeatureList::IsEnabled(base::features::kUsePoolOffsetFreelists);
-#else
-  const bool use_pool_offset_freelists = false;
-#endif  // PA_BUILDFLAG(USE_FREELIST_DISPATCHER)
+  const bool fewer_memory_regions = base::FeatureList::IsEnabled(
+      base::features::kPartitionAllocFewerMemoryRegions);
 
   bool enable_memory_tagging = false;
   partition_alloc::TagViolationReportingMode memory_tagging_reporting_mode =
@@ -1154,13 +1137,14 @@
 
   allocator_shim::ConfigurePartitions(
       allocator_shim::EnableBrp(brp_config.enable_brp),
+      brp_config.extra_extras_size,
       allocator_shim::EnableMemoryTagging(enable_memory_tagging),
       memory_tagging_reporting_mode, bucket_distribution,
       allocator_shim::SchedulerLoopQuarantine(scheduler_loop_quarantine),
       scheduler_loop_quarantine_branch_capacity_in_bytes,
       allocator_shim::ZappingByFreeFlags(zapping_by_free_flags),
       allocator_shim::EventuallyZeroFreedMemory(eventually_zero_freed_memory),
-      allocator_shim::UsePoolOffsetFreelists(use_pool_offset_freelists),
+      allocator_shim::FewerMemoryRegions(fewer_memory_regions),
       use_small_single_slot_spans);
 
   const uint32_t extras_size = allocator_shim::GetMainPartitionRootExtrasSize();
@@ -1182,6 +1166,18 @@
         ->EnableLargeEmptySlotSpanRing();
   }
 
+  if (process_type == "" &&
+      base::FeatureList::IsEnabled(
+          base::features::kPartitionAllocSchedulerLoopQuarantine)) {
+    // `ReconfigureAfterTaskRunnerInit()` is called on the UI thread.
+    const size_t capacity_in_bytes = static_cast<size_t>(
+        base::features::kPartitionAllocSchedulerLoopQuarantineBrowserUICapacity
+            .Get());
+    allocator_shim::internal::PartitionAllocMalloc::Allocator()
+        ->SetSchedulerLoopQuarantineThreadLocalBranchCapacity(
+            capacity_in_bytes);
+  }
+
 #if PA_BUILDFLAG( \
     ENABLE_ALLOCATOR_SHIM_PARTITION_ALLOC_DISPATCH_WITH_ADVANCED_CHECKS_SUPPORT)
   bool enable_pa_with_advanced_checks =
@@ -1307,7 +1303,8 @@
   if (ShouldEnableShadowMetadata(process_type)) {
     partition_alloc::PartitionRoot::EnableShadowMetadata(
         partition_alloc::internal::PoolHandleMask::kRegular |
-        partition_alloc::internal::PoolHandleMask::kBRP);
+        partition_alloc::internal::PoolHandleMask::kBRP |
+        partition_alloc::internal::PoolHandleMask::kConfigurable);
   }
 #endif  // PA_CONFIG(ENABLE_SHADOW_METADATA)
 }
diff --git a/tot/base/allocator/partition_alloc_support.h b/tot/base/allocator/partition_alloc_support.h
index 0fa5bae..337511a 100644
--- a/tot/base/allocator/partition_alloc_support.h
+++ b/tot/base/allocator/partition_alloc_support.h
@@ -49,7 +49,9 @@
  public:
   struct BrpConfiguration {
     bool enable_brp = false;
-    bool process_affected_by_brp_flag = false;
+
+    // TODO(https://crbug.com/371135823): Remove after the investigation.
+    size_t extra_extras_size = 0;
   };
 
   // Reconfigure* functions re-configure PartitionAlloc. It is impossible to
diff --git a/tot/base/allocator/partition_alloc_support_unittest.cc b/tot/base/allocator/partition_alloc_support_unittest.cc
index 27a3878..93791a7 100644
--- a/tot/base/allocator/partition_alloc_support_unittest.cc
+++ b/tot/base/allocator/partition_alloc_support_unittest.cc
@@ -50,7 +50,7 @@
     std::string mode = "crash";
     std::string type = "all";
   };
-  ScopedInstallDanglingRawPtrChecks(ConstructorParams params) {
+  explicit ScopedInstallDanglingRawPtrChecks(ConstructorParams params) {
     enabled_feature_list_.InitWithFeaturesAndParameters(
         {{features::kPartitionAllocDanglingPtr,
           {{"mode", params.mode}, {"type", params.type}}}},
diff --git a/tot/base/allocator/partition_allocator/PRESUBMIT.py b/tot/base/allocator/partition_allocator/PRESUBMIT.py
index dd07e3d..0ea7eee 100644
--- a/tot/base/allocator/partition_allocator/PRESUBMIT.py
+++ b/tot/base/allocator/partition_allocator/PRESUBMIT.py
@@ -230,3 +230,20 @@
                         '%s:%d\nPartitionAlloc disallows C++20 keywords: %s'
                         % (f.LocalPath(), line_number + 1, keyword)))
     return errors
+
+# Check `NDEBUG` is not used inside partition_alloc. We prefer to use the
+# buildflags `#if PA_BUILDFLAG(IS_DEBUG)` instead.
+def CheckNoNDebug(input_api, output_api):
+    sources = lambda affected_file: input_api.FilterSourceFile(
+        affected_file,
+        files_to_skip=[],
+        files_to_check=[_SOURCE_FILE_PATTERN])
+
+    errors = []
+    for f in input_api.AffectedSourceFiles(sources):
+        for line_number, line in f.ChangedContents():
+            if 'NDEBUG' in line:
+                errors.append(output_api.PresubmitError('%s:%d\nPartitionAlloc'
+                  % (f.LocalPath(), line_number + 1)
+                  + 'disallows NDEBUG, use PA_BUILDFLAG(IS_DEBUG) instead'))
+    return errors
diff --git a/tot/base/allocator/partition_allocator/gn/BUILDCONFIG.gn b/tot/base/allocator/partition_allocator/gn/BUILDCONFIG.gn
index abbb511..173fbfd 100644
--- a/tot/base/allocator/partition_allocator/gn/BUILDCONFIG.gn
+++ b/tot/base/allocator/partition_allocator/gn/BUILDCONFIG.gn
@@ -52,7 +52,6 @@
 is_win = current_os == "win" || current_os == "winuwp"
 is_cast_android = false
 is_castos = false
-is_chromeos_ash = false
 is_cronet_build = false
 enable_expensive_dchecks = false
 dcheck_is_configurable = false
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/Android.bp b/tot/base/allocator/partition_allocator/src/partition_alloc/Android.bp
index 7e5c759..3654eee 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/Android.bp
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/Android.bp
@@ -37,8 +37,8 @@
     cflags: [
         "-DANDROID",
         "-DANDROID_NDK_VERSION_ROLL=r27_1",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DHAVE_SYS_UIO_H",
         "-DNDEBUG",
@@ -121,8 +121,8 @@
         "tot_cronet_cc_defaults",
     ],
     cflags: [
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DNDEBUG",
         "-DNVALGRIND",
@@ -211,7 +211,7 @@
         },
         host: {
             cflags: [
-                "-DCR_SYSROOT_KEY=20230611T210420Z-2",
+                "-DCR_SYSROOT_KEY=20250129T203412Z-1",
                 "-DNO_UNWIND_TABLES",
                 "-DUSE_AURA=1",
                 "-DUSE_OZONE=1",
@@ -249,8 +249,8 @@
     cflags: [
         "-DANDROID",
         "-DANDROID_NDK_VERSION_ROLL=r27_1",
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DHAVE_SYS_UIO_H",
         "-DIS_RAW_PTR_IMPL",
@@ -337,8 +337,8 @@
         "tot_cronet_cc_defaults",
     ],
     cflags: [
-        "-DCR_CLANG_REVISION=\"llvmorg-20-init-13894-g8cb44859-1\"",
-        "-DCR_LIBCXX_REVISION=6a91009985a46122b061d36bb27f2c94f99126df",
+        "-DCR_CLANG_REVISION=\"llvmorg-21-init-5118-g52cd27e6-2\"",
+        "-DCR_LIBCXX_REVISION=4f05e20cbe1d02fa0871ac88b30eead9e38cab3a",
         "-DDYNAMIC_ANNOTATIONS_ENABLED=0",
         "-DIS_RAW_PTR_IMPL",
         "-DNDEBUG",
@@ -427,7 +427,7 @@
         },
         host: {
             cflags: [
-                "-DCR_SYSROOT_KEY=20230611T210420Z-2",
+                "-DCR_SYSROOT_KEY=20250129T203412Z-1",
                 "-DNO_UNWIND_TABLES",
                 "-DUSE_AURA=1",
                 "-DUSE_OZONE=1",
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/address_space_randomization.h b/tot/base/allocator/partition_allocator/src/partition_alloc/address_space_randomization.h
index 1484444..3059af1 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/address_space_randomization.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/address_space_randomization.h
@@ -292,7 +292,7 @@
 
 #endif  // PA_BUILDFLAG(PA_ARCH_CPU_32_BITS)
 
-    // clang-format on
+// clang-format on
 
 }  // namespace internal
 
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/allocation_guard.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/allocation_guard.cc
index c0bbd93..dda4730 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/allocation_guard.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/allocation_guard.cc
@@ -3,6 +3,7 @@
 // found in the LICENSE file.
 
 #include "partition_alloc/allocation_guard.h"
+
 #include "partition_alloc/partition_alloc_base/immediate_crash.h"
 #include "partition_alloc/partition_alloc_config.h"
 
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/extended_api.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/extended_api.cc
index e2898d7..61f08cd 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/extended_api.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/extended_api.cc
@@ -77,7 +77,17 @@
     // Replace ThreadCache's PartitionRoot.
     ThreadCache::SwapForTesting(root_);
   } else {
-    if (!regular_was_enabled_) {
+    bool regular_was_disabled = !regular_was_enabled_;
+#if PA_BUILDFLAG(IS_WIN)
+    // ThreadCache may be tombstone because of the previous test. In the
+    // case, we have to remove tombstone and re-create ThreadCache for
+    // a new test.
+    if (ThreadCache::IsTombstone(ThreadCache::Get())) {
+      ThreadCache::RemoveTombstoneForTesting();
+      regular_was_disabled = true;
+    }
+#endif
+    if (regular_was_disabled) {
       EnablePartitionAllocThreadCacheForRootIfDisabled(root_);
       ThreadCache::SwapForTesting(root_);
     }
@@ -89,6 +99,7 @@
 #endif  // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
 
   PA_CHECK(ThreadCache::Get());
+  PA_CHECK(!ThreadCache::IsTombstone(ThreadCache::Get()));
 }
 
 ThreadCacheProcessScopeForTesting::~ThreadCacheProcessScopeForTesting() {
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/internal_allocator.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/internal_allocator.cc
index 11c132b..849f68f 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/internal_allocator.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/internal_allocator.cc
@@ -37,8 +37,4 @@
   InternalAllocatorRoot().Free<FreeFlags::kNoHooks>(ptr);
 }
 
-// A deleter for `std::unique_ptr<T>`.
-void InternalPartitionDeleter::operator()(void* ptr) const {
-  InternalAllocatorRoot().Free<FreeFlags::kNoHooks>(ptr);
-}
 }  // namespace partition_alloc::internal
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/internal_allocator.h b/tot/base/allocator/partition_allocator/src/partition_alloc/internal_allocator.h
index e3e5f95..4e6ed30 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/internal_allocator.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/internal_allocator.h
@@ -48,8 +48,6 @@
 }
 
 // Destroy an object on heap in the internal partition.
-// TODO(crbug.com/40274826) This is an unused function. Start using it in tests
-// and/or in production code.
 template <typename T>
 void DestroyAtInternalPartition(T* ptr) {
   // Destroying an array is not supported.
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/internal_allocator_forward.h b/tot/base/allocator/partition_allocator/src/partition_alloc/internal_allocator_forward.h
index d2aadfa..759668c 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/internal_allocator_forward.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/internal_allocator_forward.h
@@ -67,14 +67,13 @@
 T* ConstructAtInternalPartition(Args&&... args);
 
 // Destroy an object on heap in the internal partition.
-// TODO(crbug.com/40274826) This is an unused function. Start using it in tests
-// and/or in production code.
 template <typename T>
 void DestroyAtInternalPartition(T* ptr);
 
 // A deleter for `std::unique_ptr<T>`.
-struct PA_COMPONENT_EXPORT(PARTITION_ALLOC) InternalPartitionDeleter final {
-  void operator()(void* ptr) const;
+template <typename T>
+struct InternalPartitionDeleter final {
+  void operator()(T* ptr) const { DestroyAtInternalPartition(ptr); }
 };
 
 }  // namespace partition_alloc::internal
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/lightweight_quarantine.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/lightweight_quarantine.cc
index 12be208..ef1a063 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/lightweight_quarantine.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/lightweight_quarantine.cc
@@ -19,7 +19,10 @@
  public:
   PA_ALWAYS_INLINE explicit CompileTimeConditionalScopedGuard(Lock& lock)
       PA_EXCLUSIVE_LOCK_FUNCTION(lock) {}
-  PA_ALWAYS_INLINE ~CompileTimeConditionalScopedGuard() PA_UNLOCK_FUNCTION() {}
+  // For some reason, defaulting this causes a thread safety annotation failure.
+  PA_ALWAYS_INLINE
+  ~CompileTimeConditionalScopedGuard()  // NOLINT(modernize-use-equals-default)
+      PA_UNLOCK_FUNCTION() {}
 };
 
 template <>
@@ -71,7 +74,12 @@
     const LightweightQuarantineBranchConfig& config)
     : root_(root),
       lock_required_(config.lock_required),
-      branch_capacity_in_bytes_(config.branch_capacity_in_bytes) {}
+      branch_capacity_in_bytes_(config.branch_capacity_in_bytes) {
+  if (lock_required_) {
+    to_be_freed_working_memory_ =
+        ConstructAtInternalPartition<ToBeFreedArray>();
+  }
+}
 
 LightweightQuarantineBranch::LightweightQuarantineBranch(
     LightweightQuarantineBranch&& b)
@@ -82,10 +90,19 @@
       branch_capacity_in_bytes_(
           b.branch_capacity_in_bytes_.load(std::memory_order_relaxed)) {
   b.branch_size_in_bytes_ = 0;
+  if (lock_required_) {
+    to_be_freed_working_memory_.store(b.to_be_freed_working_memory_.exchange(
+                                          nullptr, std::memory_order_relaxed),
+                                      std::memory_order_relaxed);
+  }
 }
 
 LightweightQuarantineBranch::~LightweightQuarantineBranch() {
   Purge();
+  if (lock_required_) {
+    DestroyAtInternalPartition(to_be_freed_working_memory_.exchange(
+        nullptr, std::memory_order_relaxed));
+  }
 }
 
 bool LightweightQuarantineBranch::IsQuarantinedForTesting(void* object) {
@@ -151,16 +168,26 @@
     const size_t random_index = random_.RandUint32() % slots_.size();
     std::swap(slots_[random_index], slots_.back());
   } else {
-    ToBeFreedArray to_be_freed;
+    std::unique_ptr<ToBeFreedArray, InternalPartitionDeleter<ToBeFreedArray>>
+        to_be_freed;
     size_t num_of_slots = 0;
 
     {
       CompileTimeConditionalScopedGuard<lock_required> guard(lock_);
 
+      // Borrow the reserved working memory from to_be_freed_working_memory_,
+      // and set nullptr to it indicating that it's in use.
+      to_be_freed.reset(to_be_freed_working_memory_.exchange(nullptr));
+      if (!to_be_freed) {
+        // When the reserved working memory has already been in use by another
+        // thread, fall back to allocate another chunk of working memory.
+        to_be_freed.reset(ConstructAtInternalPartition<ToBeFreedArray>());
+      }
+
       // Dequarantine some entries as required. Save the objects to be
       // deallocated into `to_be_freed`.
       PurgeInternalWithDefferedFree(capacity_in_bytes - usable_size,
-                                    to_be_freed, num_of_slots);
+                                    *to_be_freed, num_of_slots);
 
       // Put the entry onto the list.
       branch_size_in_bytes_ += usable_size;
@@ -173,7 +200,17 @@
     }
 
     // Actually deallocate the dequarantined objects.
-    BatchFree(to_be_freed, num_of_slots);
+    BatchFree(*to_be_freed, num_of_slots);
+
+    // Return the possibly-borrowed working memory to
+    // to_be_freed_working_memory_. It doesn't matter much if it's really
+    // borrowed or locally-allocated. The important facts are 1) to_be_freed is
+    // non-null, and 2) to_be_freed_working_memory_ may likely be null (because
+    // this or another thread has already borrowed it). It's simply good to make
+    // to_be_freed_working_memory_ non-null whenever possible. Maybe yet another
+    // thread would be about to borrow the working memory.
+    to_be_freed.reset(
+        to_be_freed_working_memory_.exchange(to_be_freed.release()));
   }
 
   // Update stats (not locked).
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/lightweight_quarantine.h b/tot/base/allocator/partition_allocator/src/partition_alloc/lightweight_quarantine.h
index 315b7e6..183fdf7 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/lightweight_quarantine.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/lightweight_quarantine.h
@@ -217,6 +217,17 @@
   // Using `std::atomic` here so that other threads can update this value.
   std::atomic_size_t branch_capacity_in_bytes_;
 
+  // This working memory is temporarily needed only while dequarantining
+  // objects in slots_ when lock_required_ is true. However, allocating this
+  // working memory on stack may cause stack overflow [1]. Plus, it's non-
+  // negligible perf penalty to allocate and deallocate this working memory on
+  // heap only while dequarantining. So, we reserve one chunk of working memory
+  // on heap during the entire lifetime of this branch object and try to reuse
+  // this working memory among threads. Only when thread contention occurs, we
+  // allocate and deallocate another chunk of working memory.
+  // [1] https://issues.chromium.org/issues/387508217
+  std::atomic<ToBeFreedArray*> to_be_freed_working_memory_ = nullptr;
+
   friend class LightweightQuarantineRoot;
 };
 
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/memory_reclaimer_unittest.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/memory_reclaimer_unittest.cc
index 58f2d18..4eeda27 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/memory_reclaimer_unittest.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/memory_reclaimer_unittest.cc
@@ -45,7 +45,6 @@
     MemoryReclaimer::Instance()->ResetForTesting();
 
     PartitionOptions opts;
-    opts.star_scan_quarantine = PartitionOptions::kAllowed;
     allocator_ = std::make_unique<PartitionAllocatorForTesting>(opts);
     allocator_->root()->UncapEmptySlotSpanMemoryForTesting();
     PartitionAllocGlobalInit(HandleOOM);
@@ -124,6 +123,9 @@
 
   auto* tcache = ThreadCache::Get();
   ASSERT_TRUE(tcache);
+  // ThreadCache must not be tomestone. If so, tcache->CacheMemory() will
+  // cause memory access violation.
+  ASSERT_TRUE(!ThreadCache::IsTombstone(tcache));
   size_t cached_size = tcache->CachedMemory();
 
   Reclaim();
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_constants.h b/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_constants.h
index 6516c20..4f38bdd 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_constants.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_constants.h
@@ -26,7 +26,7 @@
 #define PAGE_ALLOCATOR_CONSTANTS_DECLARE_CONSTEXPR __attribute__((const))
 
 #elif (PA_BUILDFLAG(IS_ANDROID) && PA_BUILDFLAG(PA_ARCH_CPU_64_BITS)) || \
-    (PA_BUILDFLAG(IS_LINUX) && PA_BUILDFLAG(PA_ARCH_CPU_ARM64)) || \
+    (PA_BUILDFLAG(IS_LINUX) && PA_BUILDFLAG(PA_ARCH_CPU_ARM64)) ||       \
     (PA_BUILDFLAG(IS_LINUX) && PA_BUILDFLAG(PA_ARCH_CPU_PPC64))
 // This should work for all POSIX (if needed), but currently all other
 // supported OS/architecture combinations use either hard-coded values
@@ -39,6 +39,7 @@
 #define PAGE_ALLOCATOR_CONSTANTS_DECLARE_CONSTEXPR __attribute__((const))
 
 #include <unistd.h>
+
 #include <atomic>
 
 namespace partition_alloc::internal {
@@ -69,9 +70,30 @@
 
 // Ability to name anonymous VMAs is available on some, but not all Linux-based
 // systems.
-#if PA_BUILDFLAG(IS_ANDROID) || PA_BUILDFLAG(IS_LINUX)
+#if PA_BUILDFLAG(IS_ANDROID) || PA_BUILDFLAG(IS_LINUX) || \
+    PA_BUILDFLAG(IS_CHROMEOS)
 #include <sys/prctl.h>
 
+#if (PA_BUILDFLAG(IS_LINUX) || PA_BUILDFLAG(IS_CHROMEOS)) && \
+    !(defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME))
+
+// The PR_SET_VMA* symbols are originally from
+// https://android.googlesource.com/platform/bionic/+/lollipop-release/libc/private/bionic_prctl.h
+// and were subsequently added to mainline Linux in Jan 2022, see
+// https://github.com/torvalds/linux/commit/9a10064f5625d5572c3626c1516e0bebc6c9fe9b.
+//
+// Define them to support compiling with older headers.
+#if !defined(PR_SET_VMA)
+#define PR_SET_VMA 0x53564d41
+#endif
+
+#if !defined(PR_SET_VMA_ANON_NAME)
+#define PR_SET_VMA_ANON_NAME 0
+#endif
+
+#endif  // (PA_BUILDFLAG(IS_LINUX) || PA_BUILDFLAG(IS_CHROMEOS)) &&
+        // !(defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME))
+
 #if defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
 #define LINUX_NAME_REGION 1
 #endif
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_posix.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_posix.cc
index 8511f72..51d0c9d 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_posix.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_posix.cc
@@ -150,7 +150,7 @@
       PA_NOTREACHED();
   }
 
-  // No error checking on purpose, testing only.
+  // No error checking on purpose, used for debugging only.
   prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, start, length, name);
 }
 
@@ -200,14 +200,7 @@
 }
 #elif PA_BUILDFLAG(IS_IOS)
 bool UseMapJit() {
-// Always enable MAP_JIT in simulator as it is supported unconditionally.
-#if TARGET_IPHONE_SIMULATOR
   return true;
-#else
-  // TODO(crbug.com/40255826): Fill this out when the API it is
-  // available.
-  return false;
-#endif  // TARGET_IPHONE_SIMULATOR
 }
 #endif  // PA_BUILDFLAG(IS_IOS)
 
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_posix.h b/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_posix.h
index 22cf799..5ef94a0 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_posix.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_posix.h
@@ -83,6 +83,13 @@
           PageAccessibilityConfiguration::kInaccessibleWillJitLater &&
       kUseMapJit) {
     map_flags |= MAP_JIT;
+    // iOS devices do not support toggling the page permissions after a MAP_JIT
+    // call, they must be set initially. iOS has per-thread W^X state that
+    // takes precedence over the mapping's permissions for MAP_JIT regions.
+    // See https://developer.apple.com/forums/thread/672804
+#if PA_BUILDFLAG(IS_IOS)
+    access_flag = PROT_READ | PROT_WRITE | PROT_EXEC;
+#endif
   }
 #endif
 
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_unittest.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_unittest.cc
index fbf6bf8..c136658 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_unittest.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/page_allocator_unittest.cc
@@ -265,8 +265,9 @@
       reinterpret_cast<BTITestFunction>(buffer + invalid_offset);
   EXPECT_EQ(bti_enabled_fn(15), 18);
   // Next, attempt to call the function without the entrypoint.
-  EXPECT_EXIT({ bti_invalid_fn(15); }, testing::KilledBySignal(SIGILL),
-              "");  // Should crash with SIGILL.
+  EXPECT_EXIT(
+      { bti_invalid_fn(15); }, testing::KilledBySignal(SIGILL),
+      "");  // Should crash with SIGILL.
   FreePages(buffer, PageAllocationGranularity());
 #else
   PA_NOTREACHED();
@@ -633,7 +634,17 @@
   }
 }
 
-TEST(PartitionAllocPageAllocatorTest, AllocInaccessibleWillJitLater) {
+#if PA_BUILDFLAG(IS_IOS)
+// MAP_JIT is not supported without the com.apple.developer.cs.allow-jit
+// entitlement which unittests do not have. To toggle W^X of pages
+// BrowserEngineKit library is needed which is not supported
+// until the 17.4 SDK.
+#define MAYBE_AllocInaccessibleWillJitLater \
+  DISABLED_AllocInaccessibleWillJitLater
+#else
+#define MAYBE_AllocInaccessibleWillJitLater AllocInaccessibleWillJitLater
+#endif  // PA_BUILDFLAG(IS_IOS)
+TEST(PartitionAllocPageAllocatorTest, MAYBE_AllocInaccessibleWillJitLater) {
   // Verify that kInaccessibleWillJitLater allows read/write, and read/execute
   // permissions to be set.
   uintptr_t buffer =
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.cc
index cf10236..0040a03 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.cc
@@ -19,6 +19,7 @@
 #include "partition_alloc/partition_alloc_base/bits.h"
 #include "partition_alloc/partition_alloc_base/compiler_specific.h"
 #include "partition_alloc/partition_alloc_base/debug/alias.h"
+#include "partition_alloc/partition_alloc_base/files/platform_file.h"
 #include "partition_alloc/partition_alloc_check.h"
 #include "partition_alloc/partition_alloc_config.h"
 #include "partition_alloc/partition_alloc_constants.h"
@@ -89,9 +90,12 @@
 std::ptrdiff_t PartitionAddressSpace::configurable_pool_shadow_offset_ = 0;
 
 // File descriptors for shared mappings.
-int PartitionAddressSpace::regular_pool_fd_ = -1;
-int PartitionAddressSpace::brp_pool_fd_ = -1;
-int PartitionAddressSpace::configurable_pool_fd_ = -1;
+base::PlatformFile PartitionAddressSpace::regular_pool_fd_ =
+    base::kInvalidPlatformFile;
+base::PlatformFile PartitionAddressSpace::brp_pool_fd_ =
+    base::kInvalidPlatformFile;
+base::PlatformFile PartitionAddressSpace::configurable_pool_fd_ =
+    base::kInvalidPlatformFile;
 
 uintptr_t PartitionAddressSpace::pool_shadow_address_ =
     PartitionAddressSpace::kUninitializedPoolBaseAddress;
@@ -152,9 +156,6 @@
 
   const size_t core_pool_size = CorePoolSize();
 
-  // TODO(crbug.com/40238514): Support PA_ENABLE_SHADOW_METADATA.
-  int pools_fd = -1;
-
   size_t glued_pool_sizes = core_pool_size * 2;
   // Note, BRP pool requires to be preceded by a "forbidden zone", which is
   // conveniently taken care of by the last guard page of the regular pool.
@@ -162,7 +163,7 @@
       AllocPages(glued_pool_sizes, glued_pool_sizes,
                  PageAccessibilityConfiguration(
                      PageAccessibilityConfiguration::kInaccessible),
-                 PageTag::kPartitionAlloc, pools_fd);
+                 PageTag::kPartitionAlloc);
 #if PA_BUILDFLAG(IS_ANDROID)
   // On Android, Adreno-GSL library fails to mmap if we snatch address
   // 0x400000000. Find a different address instead.
@@ -171,7 +172,7 @@
         AllocPages(glued_pool_sizes, glued_pool_sizes,
                    PageAccessibilityConfiguration(
                        PageAccessibilityConfiguration::kInaccessible),
-                   PageTag::kPartitionAlloc, pools_fd);
+                   PageTag::kPartitionAlloc);
     FreePages(setup_.regular_pool_base_address_, glued_pool_sizes);
     setup_.regular_pool_base_address_ = new_base_address;
   }
@@ -356,9 +357,10 @@
 
 namespace {
 
-int CreateAnonymousFileForMapping([[maybe_unused]] const char* name,
-                                  [[maybe_unused]] size_t size) {
-  int fd = -1;
+base::PlatformFile CreateAnonymousFileForMapping(
+    [[maybe_unused]] const char* name,
+    [[maybe_unused]] size_t size) {
+  base::PlatformFile fd = base::kInvalidPlatformFile;
 #if PA_BUILDFLAG(IS_LINUX) || PA_BUILDFLAG(IS_CHROMEOS)
   // TODO(crbug.com/40238514): if memfd_secret() is available, try
   // memfd_secret() first.
@@ -396,7 +398,7 @@
 
   // Set up a memory file for the given pool, and init |offset|.
   if (ContainsFlags(mask, PoolHandleMask::kConfigurable)) {
-    if (configurable_pool_fd_ == -1) {
+    if (configurable_pool_fd_ == base::kInvalidPlatformFile) {
       PA_DCHECK(pool_shadow_address_);
       PA_DCHECK(configurable_pool_shadow_offset_ == 0);
       configurable_pool_fd_ = CreateAnonymousFileForMapping(
@@ -407,7 +409,7 @@
     }
   }
   if (ContainsFlags(mask, PoolHandleMask::kBRP)) {
-    if (brp_pool_fd_ == -1) {
+    if (brp_pool_fd_ == base::kInvalidPlatformFile) {
       PA_DCHECK(pool_shadow_address_);
       PA_DCHECK(brp_pool_shadow_offset_ == 0);
       brp_pool_fd_ = CreateAnonymousFileForMapping("brp_pool_shadow",
@@ -418,7 +420,7 @@
     }
   }
   if (ContainsFlags(mask, PoolHandleMask::kRegular)) {
-    if (regular_pool_fd_ == -1) {
+    if (regular_pool_fd_ == base::kInvalidPlatformFile) {
       PA_DCHECK(pool_shadow_address_);
       PA_DCHECK(regular_pool_shadow_offset_ == 0);
       regular_pool_fd_ = CreateAnonymousFileForMapping("regular_pool_shadow",
@@ -437,7 +439,7 @@
   PA_DCHECK(pool_shadow_address_);
   PA_DCHECK(0u == (super_page & kSuperPageOffsetMask));
   std::ptrdiff_t offset;
-  int pool_fd = -1;
+  base::PlatformFile pool_fd = base::kInvalidPlatformFile;
   uintptr_t base_address;
 
   if (IsInRegularPool(super_page)) {
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h
index 25716db..f678c2a 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h
@@ -15,6 +15,7 @@
 #include "partition_alloc/partition_alloc_base/bits.h"
 #include "partition_alloc/partition_alloc_base/compiler_specific.h"
 #include "partition_alloc/partition_alloc_base/component_export.h"
+#include "partition_alloc/partition_alloc_base/files/platform_file.h"
 #include "partition_alloc/partition_alloc_base/notreached.h"
 #include "partition_alloc/partition_alloc_check.h"
 #include "partition_alloc/partition_alloc_config.h"
@@ -221,15 +222,15 @@
 
 #if PA_CONFIG(ENABLE_SHADOW_METADATA)
   PA_ALWAYS_INLINE static bool IsShadowMetadataEnabledOnRegularPool() {
-    return regular_pool_fd_ != -1;
+    return regular_pool_fd_ != base::kInvalidPlatformFile;
   }
 
   PA_ALWAYS_INLINE static bool IsShadowMetadataEnabledOnBRPPool() {
-    return brp_pool_fd_ != -1;
+    return brp_pool_fd_ != base::kInvalidPlatformFile;
   }
 
   PA_ALWAYS_INLINE static bool IsShadowMetadataEnabledOnConfigurablePool() {
-    return configurable_pool_fd_ != -1;
+    return configurable_pool_fd_ != base::kInvalidPlatformFile;
   }
 
   PA_ALWAYS_INLINE static bool IsShadowMetadataEnabled(pool_handle pool) {
@@ -454,10 +455,9 @@
   static std::ptrdiff_t regular_pool_shadow_offset_;
   static std::ptrdiff_t brp_pool_shadow_offset_;
   static std::ptrdiff_t configurable_pool_shadow_offset_;
-  // TODO(crbug.com/40238514): Use platform file handles instead of |int|.
-  static int regular_pool_fd_;
-  static int brp_pool_fd_;
-  static int configurable_pool_fd_;
+  static base::PlatformFile regular_pool_fd_;
+  static base::PlatformFile brp_pool_fd_;
+  static base::PlatformFile configurable_pool_fd_;
   static uintptr_t pool_shadow_address_;
 #endif  // PA_CONFIG(ENABLE_SHADOW_METADATA)
 
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc-inl.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc-inl.h
index 214b7fb..5ca83f0 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc-inl.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc-inl.h
@@ -65,7 +65,7 @@
   // faster. Note that for direct-mapped allocations, memory is decomitted at
   // free() time, so freed memory usage cannot happen.
 
-#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION)
+#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) && PA_BUILDFLAG(ENABLE_PKEYS)
   LiftThreadIsolationScope lift_thread_isolation_restrictions;
 #endif
   size_t size_to_memset = std::min(size, size_t{1} << 19);
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/check.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/check.h
index 409a280..5f93b1e 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/check.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/check.h
@@ -20,11 +20,12 @@
 // This header defines the CHECK, DCHECK, and DPCHECK macros.
 //
 // CHECK dies with a fatal error if its condition is not true. It is not
-// controlled by NDEBUG, so the check will be executed regardless of compilation
-// mode.
+// controlled by PA_BUILDFLAG(IS_DEBUG), so the check will be executed
+// regardless of compilation mode.
 //
-// DCHECK, the "debug mode" check, is enabled depending on NDEBUG and
-// DCHECK_ALWAYS_ON, and its severity depends on DCHECK_IS_CONFIGURABLE.
+// DCHECK, the "debug mode" check, is enabled depending on
+// PA_BUILDFLAG(IS_DEBUG) and PA_BUILDFLAG(DCHECK_ALWAYS_ON), and its severity
+// depends on PA_BUILDFLAG(DCHECK_IS_CONFIGURABLE).
 //
 // (D)PCHECK is like (D)CHECK, but includes the system error code (c.f.
 // perror(3)).
@@ -141,9 +142,9 @@
 
 }  // namespace check_error
 
-#if defined(OFFICIAL_BUILD) && !defined(NDEBUG)
+#if defined(OFFICIAL_BUILD) && PA_BUILDFLAG(IS_DEBUG)
 #error "Debug builds are not expected to be optimized as official builds."
-#endif  // defined(OFFICIAL_BUILD) && !defined(NDEBUG)
+#endif  // defined(OFFICIAL_BUILD) && BUILDFLAG(IS_DEBUG)
 
 #if defined(OFFICIAL_BUILD) && !PA_BUILDFLAG(DCHECKS_ARE_ON)
 
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/compiler_specific.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/compiler_specific.h
index ffeb439..f37494f 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/compiler_specific.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/compiler_specific.h
@@ -6,6 +6,7 @@
 #define PARTITION_ALLOC_PARTITION_ALLOC_BASE_COMPILER_SPECIFIC_H_
 
 #include "partition_alloc/build_config.h"
+#include "partition_alloc/buildflags.h"
 
 // A wrapper around `__has_cpp_attribute()`, which is in C++20 and thus not yet
 // available for all targets PA supports (since PA's minimum C++ version is 17).
@@ -87,7 +88,7 @@
 //
 // Since `ALWAYS_INLINE` is performance-oriented but can hamper debugging,
 // ignore it in debug mode.
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
 #if PA_HAS_CPP_ATTRIBUTE(clang::always_inline)
 #define PA_ALWAYS_INLINE [[clang::always_inline]] inline
 #elif PA_HAS_CPP_ATTRIBUTE(gnu::always_inline)
@@ -95,7 +96,7 @@
 #elif defined(PA_COMPILER_MSVC)
 #define PA_ALWAYS_INLINE __forceinline
 #endif
-#endif
+#endif  // !PA_BUILDFLAG(IS_DEBUG)
 #if !defined(PA_ALWAYS_INLINE)
 #define PA_ALWAYS_INLINE inline
 #endif
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/cpu.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/cpu.cc
index 10da0ee..a959fc3 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/cpu.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/cpu.cc
@@ -97,7 +97,7 @@
 
 void CPU::Initialize() {
 #if PA_BUILDFLAG(PA_ARCH_CPU_X86_FAMILY)
-  int cpu_info[4] = {-1};
+  int cpu_info[4] = {-1, 0, 0, 0};
 
   // __cpuid with an InfoType argument of 0 returns the number of
   // valid Ids in CPUInfo[0] and the CPU identification string in
@@ -112,7 +112,7 @@
 
   // Interpret CPU feature information.
   if (num_ids > 0) {
-    int cpu_info7[4] = {0};
+    int cpu_info7[4] = {};
     __cpuid(cpu_info, 1);
     if (num_ids >= 7) {
       __cpuid(cpu_info7, 7);
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/files/file_path_pa_unittest.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/files/file_path_pa_unittest.cc
index 6ce0baf..c48a029 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/files/file_path_pa_unittest.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/files/file_path_pa_unittest.cc
@@ -44,70 +44,70 @@
 
 TEST(PartitionAllocBaseFilePathTest, Append) {
   const struct BinaryTestData cases[] = {
-    {{FPL(""), FPL("cc")}, FPL("cc")},
-    {{FPL("."), FPL("ff")}, FPL("ff")},
-    {{FPL("."), FPL("")}, FPL(".")},
-    {{FPL("/"), FPL("cc")}, FPL("/cc")},
-    {{FPL("/aa"), FPL("")}, FPL("/aa")},
-    {{FPL("/aa/"), FPL("")}, FPL("/aa")},
-    {{FPL("//aa"), FPL("")}, FPL("//aa")},
-    {{FPL("//aa/"), FPL("")}, FPL("//aa")},
-    {{FPL("//"), FPL("aa")}, FPL("//aa")},
+      {{FPL(""), FPL("cc")}, FPL("cc")},
+      {{FPL("."), FPL("ff")}, FPL("ff")},
+      {{FPL("."), FPL("")}, FPL(".")},
+      {{FPL("/"), FPL("cc")}, FPL("/cc")},
+      {{FPL("/aa"), FPL("")}, FPL("/aa")},
+      {{FPL("/aa/"), FPL("")}, FPL("/aa")},
+      {{FPL("//aa"), FPL("")}, FPL("//aa")},
+      {{FPL("//aa/"), FPL("")}, FPL("//aa")},
+      {{FPL("//"), FPL("aa")}, FPL("//aa")},
 #if defined(PA_FILE_PATH_USES_DRIVE_LETTERS)
-    {{FPL("c:"), FPL("a")}, FPL("c:a")},
-    {{FPL("c:"), FPL("")}, FPL("c:")},
-    {{FPL("c:/"), FPL("a")}, FPL("c:/a")},
-    {{FPL("c://"), FPL("a")}, FPL("c://a")},
-    {{FPL("c:///"), FPL("a")}, FPL("c:/a")},
+      {{FPL("c:"), FPL("a")}, FPL("c:a")},
+      {{FPL("c:"), FPL("")}, FPL("c:")},
+      {{FPL("c:/"), FPL("a")}, FPL("c:/a")},
+      {{FPL("c://"), FPL("a")}, FPL("c://a")},
+      {{FPL("c:///"), FPL("a")}, FPL("c:/a")},
 #endif  // PA_FILE_PATH_USES_DRIVE_LETTERS
 #if defined(PA_FILE_PATH_USES_WIN_SEPARATORS)
-    // Append introduces the default separator character, so these test cases
-    // need to be defined with different expected results on platforms that use
-    // different default separator characters.
-    {{FPL("\\"), FPL("cc")}, FPL("\\cc")},
-    {{FPL("\\aa"), FPL("")}, FPL("\\aa")},
-    {{FPL("\\aa\\"), FPL("")}, FPL("\\aa")},
-    {{FPL("\\\\aa"), FPL("")}, FPL("\\\\aa")},
-    {{FPL("\\\\aa\\"), FPL("")}, FPL("\\\\aa")},
-    {{FPL("\\\\"), FPL("aa")}, FPL("\\\\aa")},
-    {{FPL("/aa/bb"), FPL("cc")}, FPL("/aa/bb\\cc")},
-    {{FPL("/aa/bb/"), FPL("cc")}, FPL("/aa/bb\\cc")},
-    {{FPL("aa/bb/"), FPL("cc")}, FPL("aa/bb\\cc")},
-    {{FPL("aa/bb"), FPL("cc")}, FPL("aa/bb\\cc")},
-    {{FPL("a/b"), FPL("c")}, FPL("a/b\\c")},
-    {{FPL("a/b/"), FPL("c")}, FPL("a/b\\c")},
-    {{FPL("//aa"), FPL("bb")}, FPL("//aa\\bb")},
-    {{FPL("//aa/"), FPL("bb")}, FPL("//aa\\bb")},
-    {{FPL("\\aa\\bb"), FPL("cc")}, FPL("\\aa\\bb\\cc")},
-    {{FPL("\\aa\\bb\\"), FPL("cc")}, FPL("\\aa\\bb\\cc")},
-    {{FPL("aa\\bb\\"), FPL("cc")}, FPL("aa\\bb\\cc")},
-    {{FPL("aa\\bb"), FPL("cc")}, FPL("aa\\bb\\cc")},
-    {{FPL("a\\b"), FPL("c")}, FPL("a\\b\\c")},
-    {{FPL("a\\b\\"), FPL("c")}, FPL("a\\b\\c")},
-    {{FPL("\\\\aa"), FPL("bb")}, FPL("\\\\aa\\bb")},
-    {{FPL("\\\\aa\\"), FPL("bb")}, FPL("\\\\aa\\bb")},
+      // Append introduces the default separator character, so these test cases
+      // need to be defined with different expected results on platforms that
+      // use different default separator characters.
+      {{FPL("\\"), FPL("cc")}, FPL("\\cc")},
+      {{FPL("\\aa"), FPL("")}, FPL("\\aa")},
+      {{FPL("\\aa\\"), FPL("")}, FPL("\\aa")},
+      {{FPL("\\\\aa"), FPL("")}, FPL("\\\\aa")},
+      {{FPL("\\\\aa\\"), FPL("")}, FPL("\\\\aa")},
+      {{FPL("\\\\"), FPL("aa")}, FPL("\\\\aa")},
+      {{FPL("/aa/bb"), FPL("cc")}, FPL("/aa/bb\\cc")},
+      {{FPL("/aa/bb/"), FPL("cc")}, FPL("/aa/bb\\cc")},
+      {{FPL("aa/bb/"), FPL("cc")}, FPL("aa/bb\\cc")},
+      {{FPL("aa/bb"), FPL("cc")}, FPL("aa/bb\\cc")},
+      {{FPL("a/b"), FPL("c")}, FPL("a/b\\c")},
+      {{FPL("a/b/"), FPL("c")}, FPL("a/b\\c")},
+      {{FPL("//aa"), FPL("bb")}, FPL("//aa\\bb")},
+      {{FPL("//aa/"), FPL("bb")}, FPL("//aa\\bb")},
+      {{FPL("\\aa\\bb"), FPL("cc")}, FPL("\\aa\\bb\\cc")},
+      {{FPL("\\aa\\bb\\"), FPL("cc")}, FPL("\\aa\\bb\\cc")},
+      {{FPL("aa\\bb\\"), FPL("cc")}, FPL("aa\\bb\\cc")},
+      {{FPL("aa\\bb"), FPL("cc")}, FPL("aa\\bb\\cc")},
+      {{FPL("a\\b"), FPL("c")}, FPL("a\\b\\c")},
+      {{FPL("a\\b\\"), FPL("c")}, FPL("a\\b\\c")},
+      {{FPL("\\\\aa"), FPL("bb")}, FPL("\\\\aa\\bb")},
+      {{FPL("\\\\aa\\"), FPL("bb")}, FPL("\\\\aa\\bb")},
 #if defined(PA_FILE_PATH_USES_DRIVE_LETTERS)
-    {{FPL("c:\\"), FPL("a")}, FPL("c:\\a")},
-    {{FPL("c:\\\\"), FPL("a")}, FPL("c:\\\\a")},
-    {{FPL("c:\\\\\\"), FPL("a")}, FPL("c:\\a")},
-    {{FPL("c:\\"), FPL("")}, FPL("c:\\")},
-    {{FPL("c:\\a"), FPL("b")}, FPL("c:\\a\\b")},
-    {{FPL("c:\\a\\"), FPL("b")}, FPL("c:\\a\\b")},
+      {{FPL("c:\\"), FPL("a")}, FPL("c:\\a")},
+      {{FPL("c:\\\\"), FPL("a")}, FPL("c:\\\\a")},
+      {{FPL("c:\\\\\\"), FPL("a")}, FPL("c:\\a")},
+      {{FPL("c:\\"), FPL("")}, FPL("c:\\")},
+      {{FPL("c:\\a"), FPL("b")}, FPL("c:\\a\\b")},
+      {{FPL("c:\\a\\"), FPL("b")}, FPL("c:\\a\\b")},
 #endif  // PA_FILE_PATH_USES_DRIVE_LETTERS
 #else   // PA_FILE_PATH_USES_WIN_SEPARATORS
-    {{FPL("/aa/bb"), FPL("cc")}, FPL("/aa/bb/cc")},
-    {{FPL("/aa/bb/"), FPL("cc")}, FPL("/aa/bb/cc")},
-    {{FPL("aa/bb/"), FPL("cc")}, FPL("aa/bb/cc")},
-    {{FPL("aa/bb"), FPL("cc")}, FPL("aa/bb/cc")},
-    {{FPL("a/b"), FPL("c")}, FPL("a/b/c")},
-    {{FPL("a/b/"), FPL("c")}, FPL("a/b/c")},
-    {{FPL("//aa"), FPL("bb")}, FPL("//aa/bb")},
-    {{FPL("//aa/"), FPL("bb")}, FPL("//aa/bb")},
+      {{FPL("/aa/bb"), FPL("cc")}, FPL("/aa/bb/cc")},
+      {{FPL("/aa/bb/"), FPL("cc")}, FPL("/aa/bb/cc")},
+      {{FPL("aa/bb/"), FPL("cc")}, FPL("aa/bb/cc")},
+      {{FPL("aa/bb"), FPL("cc")}, FPL("aa/bb/cc")},
+      {{FPL("a/b"), FPL("c")}, FPL("a/b/c")},
+      {{FPL("a/b/"), FPL("c")}, FPL("a/b/c")},
+      {{FPL("//aa"), FPL("bb")}, FPL("//aa/bb")},
+      {{FPL("//aa/"), FPL("bb")}, FPL("//aa/bb")},
 #if defined(PA_FILE_PATH_USES_DRIVE_LETTERS)
-    {{FPL("c:/"), FPL("a")}, FPL("c:/a")},
-    {{FPL("c:/"), FPL("")}, FPL("c:/")},
-    {{FPL("c:/a"), FPL("b")}, FPL("c:/a/b")},
-    {{FPL("c:/a/"), FPL("b")}, FPL("c:/a/b")},
+      {{FPL("c:/"), FPL("a")}, FPL("c:/a")},
+      {{FPL("c:/"), FPL("")}, FPL("c:/")},
+      {{FPL("c:/a"), FPL("b")}, FPL("c:/a/b")},
+      {{FPL("c:/a/"), FPL("b")}, FPL("c:/a/b")},
 #endif  // PA_FILE_PATH_USES_DRIVE_LETTERS
 #endif  // PA_FILE_PATH_USES_WIN_SEPARATORS
   };
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/files/platform_file.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/files/platform_file.h
new file mode 100644
index 0000000..cd7c161
--- /dev/null
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/files/platform_file.h
@@ -0,0 +1,39 @@
+// Copyright 2017 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef PARTITION_ALLOC_PARTITION_ALLOC_BASE_FILES_PLATFORM_FILE_H_
+#define PARTITION_ALLOC_PARTITION_ALLOC_BASE_FILES_PLATFORM_FILE_H_
+
+#include "partition_alloc/build_config.h"
+
+#if PA_BUILDFLAG(IS_WIN)
+#include "partition_alloc/partition_alloc_base/win/windows_types.h"
+#endif
+
+// This file defines platform-independent types for dealing with
+// platform-dependent files. If possible, use the higher-level base::File class
+// rather than these primitives.
+
+namespace partition_alloc::internal::base {
+
+#if PA_BUILDFLAG(IS_WIN)
+
+using PlatformFile = HANDLE;
+
+// It would be nice to make this constexpr but INVALID_HANDLE_VALUE is a
+// ((void*)(-1)) which Clang rejects since reinterpret_cast is technically
+// disallowed in constexpr. Visual Studio accepts this, however.
+const PlatformFile kInvalidPlatformFile = INVALID_HANDLE_VALUE;
+
+#elif PA_BUILDFLAG(IS_POSIX) || PA_BUILDFLAG(IS_FUCHSIA)
+
+using PlatformFile = int;
+
+inline constexpr PlatformFile kInvalidPlatformFile = -1;
+
+#endif
+
+}  // namespace partition_alloc::internal::base
+
+#endif  // PARTITION_ALLOC_PARTITION_ALLOC_BASE_FILES_PLATFORM_FILE_H_
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/native_library_pa_unittest.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/native_library_pa_unittest.cc
index 82d28c1..89ed1fd 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/native_library_pa_unittest.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/native_library_pa_unittest.cc
@@ -2,9 +2,8 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "partition_alloc/partition_alloc_base/native_library.h"
-
 #include "partition_alloc/partition_alloc_base/files/file_path.h"
+#include "partition_alloc/partition_alloc_base/native_library.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace partition_alloc::internal::base {
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/numerics/safe_conversions_impl.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/numerics/safe_conversions_impl.h
index 6b8fc54..4c5ab0f 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/numerics/safe_conversions_impl.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/numerics/safe_conversions_impl.h
@@ -9,6 +9,8 @@
 #include <limits>
 #include <type_traits>
 
+#include "partition_alloc/buildflags.h"
+
 namespace partition_alloc::internal::base::internal {
 
 // The std library doesn't provide a binary max_exponent for integers, however
@@ -83,10 +85,10 @@
 // TODO(jschuh): Debug builds don't reliably propagate constants, so we restrict
 // some accelerated runtime paths to release builds until this can be forced
 // with consteval support in C++20 or C++23.
-#if defined(NDEBUG)
-constexpr bool kEnableAsmCode = true;
+#if PA_BUILDFLAG(IS_DEBUG)
+inline constexpr bool kEnableAsmCode = false;
 #else
-constexpr bool kEnableAsmCode = false;
+inline constexpr bool kEnableAsmCode = true;
 #endif
 
 // Forces a crash, like a NOTREACHED(). Used for numeric boundary errors.
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/posix/eintr_wrapper.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/posix/eintr_wrapper.h
index 8996fa5..35d4f45 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/posix/eintr_wrapper.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/posix/eintr_wrapper.h
@@ -18,6 +18,7 @@
 #define PARTITION_ALLOC_PARTITION_ALLOC_BASE_POSIX_EINTR_WRAPPER_H_
 
 #include "partition_alloc/build_config.h"
+#include "partition_alloc/buildflags.h"
 
 #if PA_BUILDFLAG(IS_POSIX)
 #include <cerrno>
@@ -31,7 +32,7 @@
 inline auto WrapEINTR(Fn fn) {
   return [fn](auto&&... args) {
     int out = -1;
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
     while (true)
 #else
     for (int retry_count = 0; retry_count < 100; ++retry_count)
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/cstring_builder.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/cstring_builder.h
index bad430d..e6987da 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/cstring_builder.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/cstring_builder.h
@@ -7,13 +7,8 @@
 
 #include <cstddef>
 
-#include "partition_alloc/build_config.h"
 #include "partition_alloc/partition_alloc_base/component_export.h"
 
-#if !PA_BUILDFLAG(IS_WIN)
-#include <unistd.h>
-#endif
-
 namespace partition_alloc::internal::base::strings {
 
 // Similar to std::ostringstream, but creates a C string, i.e. nul-terminated
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/safe_sprintf.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/safe_sprintf.cc
index 16bf541..6d128ee 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/safe_sprintf.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/safe_sprintf.cc
@@ -10,8 +10,9 @@
 #include <limits>
 
 #include "partition_alloc/build_config.h"
+#include "partition_alloc/buildflags.h"
 
-#if !defined(NDEBUG)
+#if PA_BUILDFLAG(IS_DEBUG)
 // In debug builds, we use RAW_CHECK() to print useful error messages, if
 // SafeSPrintf() is called with broken arguments.
 // As our contract promises that SafeSPrintf() can be called from any
@@ -41,7 +42,7 @@
     if (x) {           \
     }                  \
   } while (0)
-#endif
+#endif  // PA_BUILDFLAG(IS_DEBUG)
 
 namespace partition_alloc::internal::base::strings {
 
@@ -74,7 +75,7 @@
 const char kDownCaseHexDigits[] = "0123456789abcdef";
 }  // namespace
 
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
 // We would like to define kSSizeMax as std::numeric_limits<ssize_t>::max(),
 // but C++ doesn't allow us to do that for constants. Instead, we have to
 // use careful casting and shifting. We later use a static_assert to
@@ -82,7 +83,7 @@
 namespace {
 const size_t kSSizeMax = kSSizeMaxConst;
 }
-#else   // defined(NDEBUG)
+#else   // !PA_BUILDFLAG(IS_DEBUG)
 // For efficiency, we really need kSSizeMax to be a constant. But for unit
 // tests, it should be adjustable. This allows us to verify edge cases without
 // having to fill the entire available address space. As a compromise, we make
@@ -101,7 +102,7 @@
   return kSSizeMax;
 }
 }  // namespace internal
-#endif  // defined(NDEBUG)
+#endif  // !PA_BUILDFLAG(IS_DEBUG)
 
 namespace {
 class Buffer {
@@ -111,10 +112,7 @@
   // to ensure that the buffer is at least one byte in size, so that it fits
   // the trailing NUL that will be added by the destructor. The buffer also
   // must be smaller or equal to kSSizeMax in size.
-  Buffer(char* buffer, size_t size)
-      : buffer_(buffer),
-        size_(size - 1),  // Account for trailing NUL byte
-        count_(0) {
+  Buffer(char* buffer, size_t size) : buffer_(buffer), size_(size - 1) {
 // MSVS2013's standard library doesn't mark max() as constexpr yet. cl.exe
 // supports static_cast but doesn't really implement constexpr yet so it doesn't
 // complain, but clang does.
@@ -276,7 +274,7 @@
   // Number of bytes that would have been emitted to the buffer, if the buffer
   // was sufficiently big. This number always excludes the trailing NUL byte
   // and it is guaranteed to never grow bigger than kSSizeMax-1.
-  size_t count_;
+  size_t count_ = 0;
 };
 
 bool Buffer::IToASCII(bool sign,
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/safe_sprintf_pa_unittest.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/safe_sprintf_pa_unittest.cc
index 95e5ae5..cc931c2 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/safe_sprintf_pa_unittest.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/safe_sprintf_pa_unittest.cc
@@ -11,6 +11,7 @@
 #include <vector>
 
 #include "partition_alloc/build_config.h"
+#include "partition_alloc/buildflags.h"
 #include "partition_alloc/partition_alloc_base/check.h"
 #include "partition_alloc/partition_alloc_base/strings/safe_sprintf.h"
 #include "partition_alloc/partition_alloc_config.h"
@@ -109,7 +110,7 @@
   EXPECT_EQ(2, SafeSPrintf(buf, "%%%%"));
   EXPECT_EQ(2, SafeSPrintf(buf, "%%X"));
   EXPECT_EQ(3, SafeSPrintf(buf, "%%%%X"));
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
   EXPECT_EQ(1, SafeSPrintf(buf, "%"));
   EXPECT_EQ(2, SafeSPrintf(buf, "%%%"));
   EXPECT_EQ(2, SafeSPrintf(buf, "%X"));
@@ -177,7 +178,7 @@
   EXPECT_EQ(2, SafeSPrintf(buf, "%%Y", 0));
   EXPECT_EQ(3, SafeSPrintf(buf, "%%%Y", 0));
   EXPECT_EQ(3, SafeSPrintf(buf, "%%%%Y", 0));
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
   EXPECT_EQ(1, SafeSPrintf(buf, "%", 0));
   EXPECT_EQ(2, SafeSPrintf(buf, "%%%", 0));
 #elif defined(ALLOW_DEATH_TEST)
@@ -187,7 +188,7 @@
 }
 
 TEST(SafeSPrintfTestPA, MissingArg) {
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
   char buf[20];
   EXPECT_EQ(3, SafeSPrintf(buf, "%c%c", 'A'));
   EXPECT_EQ("A%c", std::string(buf));
@@ -385,7 +386,7 @@
   for (std::vector<char> perfect_buf;;) {
     size_t needed =
         SafeSNPrintf(out, out_sz,
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
                      "A%2cong %s: %d %010X %d %p%7s", 'l', "string", "",
 #else
                      "A%2cong %s: %%d %010X %d %p%7s", 'l', "string",
@@ -443,10 +444,10 @@
                reinterpret_cast<uintptr_t>(PrintLongString)));
   ref[sz - 1] = '\000';
 
-#if defined(NDEBUG)
-  const size_t kSSizeMax = std::numeric_limits<ssize_t>::max();
-#else
+#if PA_BUILDFLAG(IS_DEBUG)
   const size_t kSSizeMax = internal::GetSafeSPrintfSSizeMaxForTest();
+#else
+  const size_t kSSizeMax = std::numeric_limits<ssize_t>::max();
 #endif
 
   // Compare the output from SafeSPrintf() to the one from snprintf().
@@ -458,10 +459,10 @@
   memcpy(buf, tmp.data(), len + 1);
 }
 
-#if !defined(NDEBUG)
+#if PA_BUILDFLAG(IS_DEBUG)
 class ScopedSafeSPrintfSSizeMaxSetter {
  public:
-  ScopedSafeSPrintfSSizeMaxSetter(size_t sz) {
+  explicit ScopedSafeSPrintfSSizeMaxSetter(size_t sz) {
     old_ssize_max_ = internal::GetSafeSPrintfSSizeMaxForTest();
     internal::SetSafeSPrintfSSizeMaxForTest(sz);
   }
@@ -478,7 +479,7 @@
  private:
   size_t old_ssize_max_;
 };
-#endif
+#endif  // PA_BUILDFLAG(IS_DEBUG)
 
 }  // anonymous namespace
 
@@ -501,7 +502,7 @@
   // write to the buffer, even if the caller claimed a bigger buffer size.
   // Repeat the truncation test and verify that this other code path in
   // SafeSPrintf() works correctly, too.
-#if !defined(NDEBUG)
+#if PA_BUILDFLAG(IS_DEBUG)
   for (size_t i = strlen(ref) + 1; i > 1; --i) {
     ScopedSafeSPrintfSSizeMaxSetter ssize_max_setter(i);
     char buf[sizeof(ref)];
@@ -520,7 +521,7 @@
   EXPECT_DEATH(SafeSPrintf(buf, "%100c", ' '), "padding <= max_padding");
 #endif
   EXPECT_EQ(0, *buf);
-#endif
+#endif  // PA_BUILDFLAG(IS_DEBUG)
 }
 
 TEST(SafeSPrintfTestPA, Padding) {
@@ -540,7 +541,7 @@
             SafeSPrintf(buf, fmt, 'A'));
   SafeSPrintf(fmt, "%%%dc",
               static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
   EXPECT_EQ(2, SafeSPrintf(buf, fmt, 'A'));
   EXPECT_EQ("%c", std::string(buf));
 #elif defined(ALLOW_DEATH_TEST)
@@ -576,7 +577,7 @@
   EXPECT_EQ("000", std::string(buf));
   SafeSPrintf(fmt, "%%%do",
               static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
   EXPECT_EQ(2, SafeSPrintf(buf, fmt, 1));
   EXPECT_EQ("%o", std::string(buf));
 #elif defined(ALLOW_DEATH_TEST)
@@ -610,7 +611,7 @@
   EXPECT_EQ("000", std::string(buf));
   SafeSPrintf(fmt, "%%%dd",
               static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
   EXPECT_EQ(2, SafeSPrintf(buf, fmt, 1));
   EXPECT_EQ("%d", std::string(buf));
 #elif defined(ALLOW_DEATH_TEST)
@@ -646,7 +647,7 @@
   EXPECT_EQ("000", std::string(buf));
   SafeSPrintf(fmt, "%%%dX",
               static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
   EXPECT_EQ(2, SafeSPrintf(buf, fmt, 1));
   EXPECT_EQ("%X", std::string(buf));
 #elif defined(ALLOW_DEATH_TEST)
@@ -674,7 +675,7 @@
   EXPECT_EQ("0x0", std::string(buf));
   SafeSPrintf(fmt, "%%%dp",
               static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
   EXPECT_EQ(2, SafeSPrintf(buf, fmt, 1));
   EXPECT_EQ("%p", std::string(buf));
 #elif defined(ALLOW_DEATH_TEST)
@@ -702,7 +703,7 @@
   EXPECT_EQ("   ", std::string(buf));
   SafeSPrintf(fmt, "%%%ds",
               static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
   EXPECT_EQ(2, SafeSPrintf(buf, fmt, "A"));
   EXPECT_EQ("%s", std::string(buf));
 #elif defined(ALLOW_DEATH_TEST)
@@ -722,7 +723,7 @@
   // code paths depending on whether we are actually passing arguments. If
   // we don't have any arguments, we are running in the fast-path code, that
   // looks (almost) like a strncpy().
-#if defined(NDEBUG)
+#if !PA_BUILDFLAG(IS_DEBUG)
   EXPECT_EQ(2, SafeSPrintf(buf, "%%%"));
   EXPECT_EQ("%%", std::string(buf));
   EXPECT_EQ(2, SafeSPrintf(buf, "%%%", 0));
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/thread_annotations_pa_unittest.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/thread_annotations_pa_unittest.cc
index 798d363..3e5198c 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/thread_annotations_pa_unittest.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/thread_annotations_pa_unittest.cc
@@ -3,7 +3,6 @@
 // found in the LICENSE file.
 
 #include "partition_alloc/partition_alloc_base/thread_annotations.h"
-
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace {
@@ -16,7 +15,7 @@
 
 class PA_SCOPED_LOCKABLE AutoLock {
  public:
-  AutoLock(Lock& lock) PA_EXCLUSIVE_LOCK_FUNCTION(lock) : lock_(lock) {
+  explicit AutoLock(Lock& lock) PA_EXCLUSIVE_LOCK_FUNCTION(lock) : lock_(lock) {
     lock.Acquire();
   }
   ~AutoLock() PA_UNLOCK_FUNCTION() { lock_.Release(); }
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_posix.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_posix.cc
index 4f79382..ccb4119 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_posix.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_posix.cc
@@ -115,6 +115,8 @@
   return gettid();
 #elif PA_BUILDFLAG(IS_FUCHSIA)
   return zx_thread_self();
+#elif PA_BUILDFLAG(IS_ASMJS)
+  return pthread_self();
 #elif PA_BUILDFLAG(IS_SOLARIS) || PA_BUILDFLAG(IS_QNX)
   return pthread_self();
 #elif PA_BUILDFLAG(IS_POSIX) && PA_BUILDFLAG(IS_AIX)
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/win/windows_types.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/win/windows_types.h
index 7fb2205..649a3b7 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/win/windows_types.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/win/windows_types.h
@@ -10,6 +10,7 @@
 
 // Needed for function prototypes.
 #include <specstrings.h>
+
 #include <cstdint>
 
 #ifdef __cplusplus
@@ -41,6 +42,11 @@
 typedef unsigned short WORD;
 typedef WORD UWORD;
 typedef WORD ATOM;
+#if defined(_WIN64)
+typedef int64_t PA_LONG_PTR, *PA_PLONG_PTR;
+#else
+typedef int32_t PA_LONG_PTR, *PA_PLONG_PTR;
+#endif
 
 // Forward declare some Windows struct/typedef sets.
 
@@ -53,6 +59,16 @@
   PVOID Ptr;
 };
 
+// Define some commonly used Windows constants. Note that the layout of these
+// macros - including internal spacing - must be 100% consistent with windows.h.
+
+// clang-format off
+
+#ifndef INVALID_HANDLE_VALUE
+// Work around there being two slightly different definitions in the SDK.
+#define INVALID_HANDLE_VALUE ((HANDLE)(PA_LONG_PTR)-1)
+#endif
+
 // The trailing white-spaces after this macro are required, for compatibility
 // with the definition in winnt.h.
 // clang-format off
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_check.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_check.h
index 42f66a2..8156bac 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_check.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_check.h
@@ -61,11 +61,11 @@
 
 // Expensive dchecks that run within *Scan. These checks are only enabled in
 // debug builds with dchecks enabled.
-#if !defined(NDEBUG)
+#if PA_BUILDFLAG(IS_DEBUG)
 #define PA_SCAN_DCHECK_IS_ON() PA_BUILDFLAG(DCHECKS_ARE_ON)
 #else
 #define PA_SCAN_DCHECK_IS_ON() 0
-#endif
+#endif  // PA_BUILDFLAG(IS_DEBUG)
 
 #if PA_SCAN_DCHECK_IS_ON()
 #define PA_SCAN_DCHECK(expr) PA_DCHECK(expr)
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_constants.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_constants.h
index 31f03bd..11b94f8 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_constants.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_constants.h
@@ -63,9 +63,7 @@
   kNoHooks = 1 << 1,  // Internal.
   // Quarantine for a while to ensure no UaF from on-stack pointers.
   kSchedulerLoopQuarantine = 1 << 2,
-  // Zap the object region on `Free()`.
-  kZap = 1 << 3,
-  kMaxValue = kZap,
+  kMaxValue = kSchedulerLoopQuarantine,
 };
 PA_DEFINE_OPERATORS_FOR_FLAGS(FreeFlags);
 }  // namespace internal
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_unittest.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_unittest.cc
index 7203788..f30ded9 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_unittest.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_unittest.cc
@@ -93,6 +93,12 @@
 #include <unistd.h>
 #endif
 
+#if PA_BUILDFLAG(IS_LINUX) || PA_BUILDFLAG(IS_ANDROID) || \
+    PA_BUILDFLAG(IS_CHROMEOS)
+#include "partition_alloc/partition_alloc_base/debug/proc_maps_linux.h"
+#endif  // PA_BUILDFLAG(IS_LINUX) || PA_BUILDFLAG(IS_ANDROID) ||
+        // PA_BUILDFLAG(IS_CHROMEOS)
+
 // In the MTE world, the upper bits of a pointer can be decorated with a tag,
 // thus allowing many versions of the same pointer to exist. These macros take
 // that into account when comparing.
@@ -385,6 +391,7 @@
     // Requires explicit `FreeFlag` to activate, no effect otherwise.
     opts.zapping_by_free_flags = PartitionOptions::kEnabled;
     opts.eventually_zero_freed_memory = PartitionOptions::kEnabled;
+    opts.fewer_memory_regions = PartitionOptions::kDisabled;
     opts.scheduler_loop_quarantine = PartitionOptions::kEnabled;
     opts.scheduler_loop_quarantine_branch_capacity_in_bytes =
         std::numeric_limits<size_t>::max();
@@ -856,7 +863,7 @@
   ptrdiff_t diff = UntagPtr(ptr2) - UntagPtr(ptr1);
   EXPECT_EQ(static_cast<ptrdiff_t>(ActualTestAllocSize()), diff);
 
-  // Check that we re-use the just-freed slot.
+  // Check that we reuse the just-freed slot.
   allocator.root()->Free(ptr2);
   ptr2 = allocator.root()->Alloc(kTestAllocSize, type_name);
   EXPECT_TRUE(ptr2);
@@ -988,7 +995,7 @@
   PartitionRoot::Bucket* bucket = &allocator.root()->buckets[bucket_index];
   ASSERT_EQ(bucket->slot_size, slot_size);
 
-  // The first allocation is expected to span exactly the capcity of the slot.
+  // The first allocation is expected to span exactly the capacity of the slot.
   // The second one should overflow into a higher-size slot, and not fill its
   // capacity.
   size_t requested_size1 = slot_size - ExtraAllocSize(allocator);
@@ -2488,7 +2495,7 @@
 // Disable these tests on Android because, due to the allocation-heavy behavior,
 // they tend to get OOM-killed rather than pass.
 //
-// Disable these test on Windows, since they run slower, so tend to timout and
+// Disable these test on Windows, since they run slower, so tend to timeout and
 // cause flake.
 #if !PA_BUILDFLAG(IS_WIN) &&                                         \
         (!PA_BUILDFLAG(PA_ARCH_CPU_64_BITS) ||                       \
@@ -3817,7 +3824,6 @@
   PartitionOptions opts = GetCommonPartitionOptions();
   opts.scheduler_loop_quarantine = PartitionOptions::kDisabled;
   opts.thread_cache = PartitionOptions::kDisabled;
-  opts.star_scan_quarantine = PartitionOptions::kDisallowed;
   std::unique_ptr<PartitionRoot> root = CreateCustomTestRoot(opts, {});
 
   // This allocation is required to prevent slot span from being empty and
@@ -3839,7 +3845,7 @@
   void* ptr = allocator.root()->Alloc(1, type_name);
   EXPECT_TRUE(ptr);
   memset(ptr, 'A', 1);
-  constexpr auto kFlags = FreeFlags::kZap | FreeFlags::kSchedulerLoopQuarantine;
+  constexpr auto kFlags = FreeFlags::kSchedulerLoopQuarantine;
   allocator.root()->Free<kFlags>(ptr);
   // Accessing memory after free requires a retag.
   ptr = TagPtr(ptr);
@@ -3861,6 +3867,137 @@
   allocator.root()->GetSchedulerLoopQuarantineBranchForTesting().Purge();
 }
 
+#if PA_BUILDFLAG(IS_LINUX) || PA_BUILDFLAG(IS_ANDROID) || \
+    PA_BUILDFLAG(IS_CHROMEOS)
+
+TEST_P(PartitionAllocTest, InaccessibleRegionAfterSlotSpans) {
+  auto* root = allocator.root();
+  ASSERT_FALSE(root->settings.fewer_memory_regions);
+
+  // Look for an allocation size that matches a bucket which doesn't fill its
+  // last PartitionPage.  Scan through allocation sizes rather than buckets, as
+  // depending on the bucket distribution, some buckets may not be active.
+  PartitionBucket* incomplete_bucket = nullptr;
+  // Only regular buckets, give up if we can't find one (and GTEST_SKIP()
+  // below).
+  for (size_t alloc_size = 0;
+       alloc_size < MaxRegularSlotSpanSize() - ExtraAllocSize(allocator);
+       alloc_size++) {
+    size_t index = SizeToIndex(alloc_size + ExtraAllocSize(allocator));
+    auto& bucket = root->buckets[index];
+    if (bucket.get_bytes_per_span() != bucket.get_pages_per_slot_span()
+                                           << PartitionPageShift()) {
+      incomplete_bucket = &bucket;
+      break;
+    }
+  }
+
+  // Didn't find any bucket that doesn't fill the last PartitionPage. Unlikely,
+  // but so be it.
+  if (!incomplete_bucket) {
+    GTEST_SKIP();
+  }
+
+  // Allocate memory, get the end of the slot span, and check that there is an
+  // inaccessible region starting there.
+  void* ptr =
+      root->Alloc(incomplete_bucket->slot_size - ExtraAllocSize(allocator), "");
+  ASSERT_TRUE(ptr);
+  uintptr_t start = SlotSpanMetadata<MetadataKind::kReadOnly>::ToSlotSpanStart(
+      SlotSpanMetadata<MetadataKind::kReadOnly>::FromAddr(UntagPtr(ptr)));
+  uintptr_t end = start + incomplete_bucket->get_bytes_per_span();
+
+  std::string proc_maps;
+  std::vector<base::debug::MappedMemoryRegion> regions;
+  ASSERT_TRUE(base::debug::ReadProcMaps(&proc_maps));
+  ASSERT_TRUE(base::debug::ParseProcMaps(proc_maps, &regions));
+  bool found = false;
+  for (const auto& region : regions) {
+    if (region.start == end) {
+      found = true;
+      EXPECT_EQ(region.permissions, base::debug::MappedMemoryRegion::PRIVATE);
+      break;
+    }
+  }
+  EXPECT_TRUE(found);
+
+  root->Free(ptr);
+}
+
+TEST_P(PartitionAllocTest, FewerMemoryRegions) {
+  auto* root = allocator.root();
+  ASSERT_FALSE(root->settings.fewer_memory_regions);
+  root->settings.fewer_memory_regions = true;
+
+  // Look for an allocation size that matches a bucket which doesn't fill its
+  // last PartitionPage.  Scan through allocation sizes rather than buckets, as
+  // depending on the bucket distribution, some buckets may not be active.
+  PartitionBucket* incomplete_bucket = nullptr;
+  // Only regular buckets, give up if we can't find one (and GTEST_SKIP()
+  // below).
+  for (size_t alloc_size = 0;
+       alloc_size < MaxRegularSlotSpanSize() - ExtraAllocSize(allocator);
+       alloc_size++) {
+    size_t index = SizeToIndex(alloc_size + ExtraAllocSize(allocator));
+    auto& bucket = root->buckets[index];
+    if (bucket.get_bytes_per_span() != bucket.get_pages_per_slot_span()
+                                           << PartitionPageShift()) {
+      incomplete_bucket = &bucket;
+      break;
+    }
+  }
+
+  // Didn't find any bucket that doesn't fill the last PartitionPage. Unlikely,
+  // but so be it.
+  if (!incomplete_bucket) {
+    GTEST_SKIP();
+  }
+
+  // Allocate memory, get the end of the slot span, and check that there is an
+  // inaccessible region starting there.
+  void* ptr =
+      root->Alloc(incomplete_bucket->slot_size - ExtraAllocSize(allocator), "");
+  ASSERT_TRUE(ptr);
+  uintptr_t start = SlotSpanMetadata<MetadataKind::kReadOnly>::ToSlotSpanStart(
+      SlotSpanMetadata<MetadataKind::kReadOnly>::FromAddr(UntagPtr(ptr)));
+  uintptr_t end = start + incomplete_bucket->get_bytes_per_span();
+
+  std::string proc_maps;
+  std::vector<base::debug::MappedMemoryRegion> regions;
+  ASSERT_TRUE(base::debug::ReadProcMaps(&proc_maps));
+  ASSERT_TRUE(base::debug::ParseProcMaps(proc_maps, &regions));
+
+  // Cannot find a region that starts exactly at the end of the incomplete slot
+  // span.
+  bool found = false;
+  for (const auto& region : regions) {
+    if (region.start == end) {
+      found = true;
+      break;
+    }
+  }
+  EXPECT_FALSE(found);
+
+  // The enclosing region has RW permissions.
+  found = false;
+  for (const auto& region : regions) {
+    if (region.start <= end && region.end >= end) {
+      EXPECT_EQ(region.permissions,
+                base::debug::MappedMemoryRegion::READ |
+                    base::debug::MappedMemoryRegion::WRITE |
+                    base::debug::MappedMemoryRegion::PRIVATE);
+      found = true;
+      break;
+    }
+  }
+  EXPECT_TRUE(found);
+
+  root->Free(ptr);
+}
+
+#endif  // PA_BUILDFLAG(IS_LINUX) || PA_BUILDFLAG(IS_ANDROID) ||
+        // PA_BUILDFLAG(IS_CHROMEOS)
+
 TEST_P(PartitionAllocTest, ZeroFreedMemory) {
   auto* root = allocator.root();
   ASSERT_TRUE(root->settings.eventually_zero_freed_memory);
@@ -3899,7 +4036,7 @@
 
 TEST_P(PartitionAllocTest, Bug_897585) {
   // Need sizes big enough to be direct mapped and a delta small enough to
-  // allow re-use of the slot span when cookied. These numbers fall out of the
+  // allow reuse of the slot span when cookied. These numbers fall out of the
   // test case in the indicated bug.
   size_t kInitialSize = 983050;
   size_t kDesiredSize = 983100;
@@ -4364,7 +4501,7 @@
                 root.total_size_of_direct_mapped_pages);
 
       // Freeing memory in the diret map decommits pages right away. The address
-      // space is released for re-use too.
+      // space is released for reuse too.
       root.Free(ptr);
       expected_committed_size -= aligned_size;
       expected_direct_map_size = 0;
@@ -4504,6 +4641,93 @@
   }
 }
 
+TEST_P(PartitionAllocTest, ExtraExtrasSize) {
+  constexpr size_t kExtraExtrasSize = 4;
+  constexpr size_t kSlotSize = 64;
+
+  std::unique_ptr<PartitionRoot> root_with_extra = CreateCustomTestRoot(
+      [&]() {
+        PartitionOptions opts = GetCommonPartitionOptions();
+        opts.backup_ref_ptr = PartitionOptions::kEnabled;
+        opts.backup_ref_ptr_extra_extras_size = kExtraExtrasSize;
+        return opts;
+      }(),
+      {});
+  std::unique_ptr<PartitionRoot> root_no_extra = CreateCustomTestRoot(
+      [&]() {
+        PartitionOptions opts = GetCommonPartitionOptions();
+        opts.backup_ref_ptr = PartitionOptions::kEnabled;
+        return opts;
+      }(),
+      {});
+
+  // Max size which fits within 64 bytes bucket when there is no extra.
+  const size_t alloc_size =
+      root_no_extra->AdjustSizeForExtrasSubtract(kSlotSize);
+
+  EXPECT_EQ(
+      root_with_extra->AdjustSizeForExtrasAdd(alloc_size),
+      root_no_extra->AdjustSizeForExtrasAdd(alloc_size) + kExtraExtrasSize);
+
+  void* ptr1 = root_with_extra->Alloc(alloc_size, type_name);
+  auto* slot_span1 =
+      SlotSpan::FromSlotStart(root_with_extra->ObjectToSlotStart(ptr1));
+
+  void* ptr2 = root_no_extra->Alloc(alloc_size, type_name);
+  auto* slot_span2 =
+      SlotSpan::FromSlotStart(root_no_extra->ObjectToSlotStart(ptr2));
+
+  // Verify adding extra consumes more memory.
+  EXPECT_NE(slot_span1->bucket->slot_size, slot_span2->bucket->slot_size);
+
+  root_no_extra->Free(ptr2);
+}
+
+TEST_P(PartitionAllocTest, ExtraExtrasNullfyOffByOneDetection) {
+#if !PA_BUILDFLAG(HAS_64_BIT_POINTERS)
+  GTEST_SKIP()
+      << "This test is not compatible with 32-bit bucket distribution.";
+#else
+  std::unique_ptr<PartitionRoot> root_no_extra = CreateCustomTestRoot(
+      [&]() {
+        PartitionOptions opts = GetCommonPartitionOptions();
+        opts.backup_ref_ptr = PartitionOptions::kEnabled;
+        return opts;
+      }(),
+      {});
+
+  // `ptr1` can be located at page start hence lacks in-slot style
+  // `InSlotMetadata`. See `InSlotMetadataPointer`.
+  int64_t* ptr1 = static_cast<int64_t*>(root_no_extra->Alloc(8));
+  int64_t* ptr2 = static_cast<int64_t*>(root_no_extra->Alloc(8));
+
+  // Off-by-one (8 bytes).
+  EXPECT_DEATH_IF_SUPPORTED((ptr2[1] = 0, root_no_extra->Free(ptr2)), "");
+
+  root_no_extra->Free(ptr2);
+  root_no_extra->Free(ptr1);
+
+  // Repeat the same but with extra extras of 8 bytes.
+  std::unique_ptr<PartitionRoot> root_with_extra = CreateCustomTestRoot(
+      [&]() {
+        PartitionOptions opts = GetCommonPartitionOptions();
+        opts.backup_ref_ptr = PartitionOptions::kEnabled;
+        opts.backup_ref_ptr_extra_extras_size = 8;
+        return opts;
+      }(),
+      {});
+
+  ptr1 = static_cast<int64_t*>(root_with_extra->Alloc(8));
+  ptr2 = static_cast<int64_t*>(root_with_extra->Alloc(8));
+
+  // This off-by-one overwrites the extra extras and does not corrupt
+  // `InSlotMetadata`.
+  ptr2[1] = 0;
+  root_with_extra->Free(ptr2);
+  root_with_extra->Free(ptr1);
+#endif  // !PA_BUILDFLAG(HAS_64_BIT_POINTERS)
+}
+
 int g_unretained_dangling_raw_ptr_detected_count = 0;
 
 class UnretainedDanglingRawPtrTest : public PartitionAllocTest {
@@ -5012,7 +5236,7 @@
 #if PA_USE_DEATH_TESTS()
 // DCHECK message are stripped in official build. It causes death tests with
 // matchers to fail.
-#if !defined(OFFICIAL_BUILD) || !defined(NDEBUG)
+#if !defined(OFFICIAL_BUILD) || PA_BUILDFLAG(IS_DEBUG)
 
 // Acquire() once, Release() twice => CRASH
 TEST_P(PartitionAllocDeathTest, ReleaseUnderflowRawPtr) {
@@ -5046,7 +5270,7 @@
   allocator.root()->Free(ptr);
 }
 
-#endif  //! defined(OFFICIAL_BUILD) || !defined(NDEBUG)
+#endif  //! defined(OFFICIAL_BUILD) || PA_BUILDFLAG(IS_DEBUG)
 #endif  // PA_USE_DEATH_TESTS()
 #endif  // PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS)
 
@@ -5208,11 +5432,11 @@
 
   // DCHECKs don't work with EXPECT_DEATH on official builds.
 #if PA_BUILDFLAG(DCHECKS_ARE_ON) && \
-    (!defined(OFFICIAL_BUILD) || !defined(NDEBUG))
+    (!defined(OFFICIAL_BUILD) || PA_BUILDFLAG(IS_DEBUG))
   // Expect to DCHECK on unallocated region.
   EXPECT_DEATH_IF_SUPPORTED(IsReservationStart(address_to_check), "");
 #endif  //  PA_BUILDFLAG(DCHECKS_ARE_ON) && (!defined(OFFICIAL_BUILD) ||
-        //  !defined(NDEBUG))
+        //  PA_BUILDFLAG(IS_DEBUG))
 
   EXPECT_FALSE(
       IsManagedByNormalBucketsForTesting(address_to_check, allocator.root()));
@@ -5283,14 +5507,14 @@
 #if PA_USE_DEATH_TESTS()
 // DCHECK message are stripped in official build. It causes death tests with
 // matchers to fail.
-#if !defined(OFFICIAL_BUILD) || !defined(NDEBUG)
+#if !defined(OFFICIAL_BUILD) || PA_BUILDFLAG(IS_DEBUG)
 
 TEST_P(PartitionAllocDeathTest, CheckTriggered) {
   PA_EXPECT_DCHECK_DEATH_WITH(PA_CHECK(5 == 7), "Check failed.*5 == 7");
   EXPECT_DEATH(PA_CHECK(5 == 7), "Check failed.*5 == 7");
 }
 
-#endif  // !defined(OFFICIAL_BUILD) && !defined(NDEBUG)
+#endif  // !defined(OFFICIAL_BUILD) && PA_BUILDFLAG(IS_DEBUG)
 #endif  // PA_USE_DEATH_TESTS()
 
 // Not on chromecast, since gtest considers extra output from itself as a test
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_bucket.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_bucket.cc
index 01ce68d..db2c5da 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_bucket.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_bucket.cc
@@ -684,7 +684,7 @@
   for (auto* page = gap_start_page->ToWritable(root);
        page < gap_end_page->ToWritable(root); ++page) {
     PA_DCHECK(!page->is_valid);
-    page->has_valid_span_after_this = 1;
+    page->has_valid_span_after_this = true;
   }
   root->next_partition_page =
       adjusted_next_partition_page + slot_span_reservation_size;
@@ -708,7 +708,7 @@
     PA_DEBUG_DATA_ON_STACK("spancmt", slot_span_committed_size);
 
     root->RecommitSystemPagesForData(
-        slot_span_start, slot_span_committed_size,
+        slot_span_start, SlotSpanCommittedSize(root),
         PageAccessibilityDisposition::kRequireUpdate,
         slot_size <= kMaxMemoryTaggingSize);
   }
@@ -1590,4 +1590,63 @@
   InitializeSlotSpan(slot_span, root);
 }
 
+size_t PartitionBucket::SlotSpanCommittedSize(PartitionRoot* root) const {
+  // With lazy commit, we certainly don't want to commit more than
+  // necessary. This is not reached, but keep the CHECK() as documentation.
+  PA_CHECK(!kUseLazyCommit);
+
+  // Memory is reserved in units of PartitionPage, but a given slot span may be
+  // smaller than the reserved area. For instance (assuming 4k pages), for a
+  // bucket where the slot span size is 40kiB, we reserve 4 PartitionPage = 16 *
+  // 4 = 48kiB, but only ever commit 40kiB out of it.
+  //
+  // This means that the address space then looks like, assuming that the
+  // PartitionPage next to it is committed:
+  //   [SlotSpan range, 40kiB]                       rw-p
+  //   [Unused area in the last PartitionPage, 8kiB] ---p
+  //   [Next PartitionPages, size unknown ]          rw-p
+  //
+  // So we have a "hole" of inaccessible memory, and 3 memory regions. If
+  // instead we commit the full PartitionPages, we get (due to the kernel
+  // merging neighboring regions with uniform permissions):
+  //
+  //   [SlotSpan range, 40kiB + Unused area, 8kiB + next PartitionPages] rw-p
+  //
+  // So 1 memory region rather then 3. This matters, because on Linux kernels,
+  // there is a maximum number of VMAs per process, with the default limit a bit
+  // less than 2^16, and Chromium sometimes hits the limit (see
+  // /proc/sys/vm/max_map_count for the current limit), largely because of
+  // PartitionAlloc contributing thousands of regions. Locally, on a Linux
+  // system, this reduces the number of PartitionAlloc regions by up to ~4x.
+  //
+  // Why is it safe?
+  // The extra memory is not used by anything, so committing it doesn't make a
+  // difference. It makes it accessible though.
+  //
+  // How much does it cost?
+  // Almost nothing. On Linux, "committing" memory merely changes its
+  // permissions, it doesn't cost any memory until the pages are touched, which
+  // they are not. However, mprotect()-ed areas that are writable count towards
+  // the RLIMIT_DATA resource limit, which is used by the sandbox. So, while
+  // this change costs 0 physical memory (and actually saves some, by reducing
+  // the size of the VMA red-black tree in the kernel), it might increase
+  // slightly the cases where we bump into the sandbox memory limit.
+  //
+  // Is it safe to do while running?
+  // Since this is decided through root settings, the value changes at runtime,
+  // so we may decommit memory that was never committed. This is safe onLinux,
+  // since decommitting is just changing permissions back to PROT_NONE, which
+  // the tail end would already have.
+  //
+  // Can we do better?
+  // For simplicity, we do not "fix" the regions that were committed before the
+  // settings are changed (after feature list initialization). This means that
+  // we end up with more regions that we could. The intent is to run a field
+  // experiment, then change the default value, at which point we get the full
+  // impact, so this is only temporary.
+  return root->settings.fewer_memory_regions
+             ? (get_pages_per_slot_span() << PartitionPageShift())
+             : get_bytes_per_span();
+}
+
 }  // namespace partition_alloc::internal
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_bucket.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_bucket.h
index 637a6ce..30f55bc 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_bucket.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_bucket.h
@@ -1,7 +1,6 @@
 // Copyright 2018 The Chromium Authors
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
-
 #ifndef PARTITION_ALLOC_PARTITION_BUCKET_H_
 #define PARTITION_ALLOC_PARTITION_BUCKET_H_
 
@@ -171,6 +170,8 @@
       SlotSpanMetadata<MetadataKind::kReadOnly>* slot_span,
       PartitionRoot* root);
 
+  size_t SlotSpanCommittedSize(PartitionRoot* root) const;
+
  private:
   // Sets `this->can_store_raw_size`.
   void InitCanStoreRawSize(bool use_small_single_slot_spans);
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_lock.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_lock.h
index e76a988..3e68b62 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_lock.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_lock.h
@@ -78,6 +78,28 @@
         // PA_BUILDFLAG(ENABLE_PARTITION_LOCK_REENTRANCY_CHECK)
     lock_.Release();
   }
+
+  bool TryAcquire() PA_EXCLUSIVE_TRYLOCK_FUNCTION(true) {
+    // Unlike `Acquire()`, `TryAcquire()` does not provide any reentrancy
+    // protection. Instead, it just fails and returns `false`.
+    // Hence this should not be used in (de)allocation code path.
+    if (!lock_.Try()) {
+      return false;
+    }
+
+#if PA_BUILDFLAG(DCHECKS_ARE_ON) || \
+    PA_BUILDFLAG(ENABLE_PARTITION_LOCK_REENTRANCY_CHECK)
+#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION)
+    LiftThreadIsolationScope lift_thread_isolation_restrictions;
+#endif
+
+    base::PlatformThreadRef current_thread = base::PlatformThread::CurrentRef();
+    owning_thread_ref_.store(current_thread, std::memory_order_release);
+#endif
+
+    return true;
+  }
+
   void AssertAcquired() const PA_ASSERT_EXCLUSIVE_LOCK() {
     lock_.AssertAcquired();
 #if PA_BUILDFLAG(DCHECKS_ARE_ON) || \
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_lock_unittest.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_lock_unittest.cc
index d5e5afc..76334ce 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_lock_unittest.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_lock_unittest.cc
@@ -189,7 +189,7 @@
 // AssertAcquired() is only enforced with DCHECK()s.
 // DCHECKs don't work with EXPECT_DEATH on official builds.
 #if defined(GTEST_HAS_DEATH_TEST) && PA_BUILDFLAG(DCHECKS_ARE_ON) && \
-    (!defined(OFFICIAL_BUILD) || !defined(NDEBUG))
+    (!defined(OFFICIAL_BUILD) || PA_BUILDFLAG(IS_DEBUG))
 
 TEST(PartitionAllocLockTest, AssertAcquiredDeathTest) {
   Lock lock;
@@ -225,7 +225,7 @@
 
   // DCHECKs don't work with EXPECT_DEATH on official builds.
 #if PA_BUILDFLAG(DCHECKS_ARE_ON) && \
-    (!defined(OFFICIAL_BUILD) || !defined(NDEBUG))
+    (!defined(OFFICIAL_BUILD) || PA_BUILDFLAG(IS_DEBUG))
   EXPECT_DEATH(lock.AssertAcquired(), "");
 #endif
 }
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_page.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_page.cc
index 799eeed..9186149 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_page.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_page.cc
@@ -248,7 +248,7 @@
   size_t dirty_size =
       base::bits::AlignUp(GetProvisionedSize(), SystemPageSize());
   size_t size_to_decommit =
-      kUseLazyCommit ? dirty_size : bucket->get_bytes_per_span();
+      kUseLazyCommit ? dirty_size : bucket->SlotSpanCommittedSize(root);
 
   PA_DCHECK(root->empty_slot_spans_dirty_bytes >= dirty_size);
   root->empty_slot_spans_dirty_bytes -= dirty_size;
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_page.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_page.h
index f9ccbe9..1b0061b 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_page.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_page.h
@@ -938,8 +938,7 @@
 // Iterates over all slot spans in a super-page. |Callback| must return true if
 // early return is needed.
 template <typename Callback>
-void IterateSlotSpans(uintptr_t super_page,
-                      Callback callback) {
+void IterateSlotSpans(uintptr_t super_page, Callback callback) {
 #if PA_BUILDFLAG(DCHECKS_ARE_ON)
   PA_DCHECK(!(super_page % kSuperPageAlignment));
   auto* extent_entry = PartitionSuperPageToExtent(super_page);
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_page_constants.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_page_constants.h
index a5c96b6..1557414 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_page_constants.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_page_constants.h
@@ -17,7 +17,7 @@
 // PartitionPageSize() is 4 times the OS page size.
 static constexpr size_t kMaxSlotsPerSlotSpan = 4 * (1 << 14) / kSmallestBucket;
 #elif defined(PARTITION_ALLOCATOR_CONSTANTS_POSIX_NONCONST_PAGE_SIZE) && \
-    PA_BUILDFLAG(IS_LINUX) && \
+    PA_BUILDFLAG(IS_LINUX) &&                                            \
     (PA_BUILDFLAG(PA_ARCH_CPU_ARM64) || PA_BUILDFLAG(PA_ARCH_CPU_PPC64))
 // System page size can be 4, 16, or 64 kiB on Linux on AArch64.
 // System page size can be 4 or 64 kiB on Linux on ppc64.
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_root.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_root.cc
index d2f222c..2398eaa 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_root.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_root.cc
@@ -1154,6 +1154,8 @@
         opts.zapping_by_free_flags == PartitionOptions::kEnabled;
     settings.eventually_zero_freed_memory =
         opts.eventually_zero_freed_memory == PartitionOptions::kEnabled;
+    settings.fewer_memory_regions =
+        opts.fewer_memory_regions == PartitionOptions::kEnabled;
 
     settings.scheduler_loop_quarantine =
         opts.scheduler_loop_quarantine == PartitionOptions::kEnabled;
@@ -1218,6 +1220,7 @@
     if (brp_enabled()) {
       settings.in_slot_metadata_size = internal::kInSlotMetadataSizeAdjustment;
       settings.extras_size += internal::kInSlotMetadataSizeAdjustment;
+      settings.extras_size += opts.backup_ref_ptr_extra_extras_size;
 #if PA_CONFIG(MAYBE_ENABLE_MAC11_MALLOC_SIZE_HACK)
       EnableMac11MallocSizeHackIfNeeded();
 #endif
@@ -1343,15 +1346,17 @@
   // become visible to another thread before the effects of
   // `internal::ThreadCacheInit()` are visible. To prevent that, we fake thread
   // cache creation being in-progress while this is running.
-  //
-  // This synchronizes with the acquire load in `MaybeInitThreadCacheAndAlloc()`
-  // to ensure that we don't create (and thus use) a ThreadCache before
-  // ThreadCache::Init()'s effects are visible.
-  int before =
-      thread_caches_being_constructed_.fetch_add(1, std::memory_order_acquire);
-  PA_CHECK(before == 0);
-  ThreadCache::Init(this);
-  thread_caches_being_constructed_.fetch_sub(1, std::memory_order_release);
+
+  {
+    ::partition_alloc::internal::ScopedGuard construction_guard{
+        thread_cache_construction_lock};
+
+    ThreadCache::Init(this);
+    // Create thread cache for this thread so that we can start using it right
+    // after.
+    ThreadCache::Create(this);
+  }
+
   settings.with_thread_cache = true;
 #endif  // PA_CONFIG(THREAD_CACHE_SUPPORTED)
 }
@@ -1891,17 +1896,9 @@
 
 ThreadCache* PartitionRoot::MaybeInitThreadCache() {
   auto* tcache = ThreadCache::Get();
-  // See comment in `EnableThreadCacheIfSupport()` for why this is an acquire
-  // load.
-  if (ThreadCache::IsTombstone(tcache) ||
-      thread_caches_being_constructed_.load(std::memory_order_acquire)) {
-    // Two cases:
-    // 1. Thread is being terminated, don't try to use the thread cache, and
-    //    don't try to resurrect it.
-    // 2. Someone, somewhere is currently allocating a thread cache. This may
-    //    be us, in which case we are re-entering and should not create a thread
-    //    cache. If it is not us, then this merely delays thread cache
-    //    construction a bit, which is not an issue.
+  if (ThreadCache::IsTombstone(tcache)) {
+    // Thread is being terminated, don't try to use the thread cache, and don't
+    // try to resurrect it.
     return nullptr;
   }
 
@@ -1914,16 +1911,40 @@
   // variable. This would end up here again, which is not what we want (and
   // likely is not supported by libc).
   //
-  // To avoid this sort of reentrancy, increase the count of thread caches that
-  // are currently allocating a thread cache.
   //
-  // Note that there is no deadlock or data inconsistency concern, since we do
-  // not hold the lock, and has such haven't touched any internal data.
-  int before =
-      thread_caches_being_constructed_.fetch_add(1, std::memory_order_relaxed);
-  PA_CHECK(before < std::numeric_limits<int>::max());
+  // Note that there is no data inconsistency concern, since we do not hold
+  // the global `lock_`, and has such haven't touched any internal data.
+  if (!thread_cache_construction_lock.TryAcquire()) {
+    // Someone, somewhere is currently allocating a thread cache. This may be
+    // us, in which case we are re-entering and should not create a thread
+    // cache. If it is not us, then this merely delays thread cache
+    // construction a bit, which is not an issue.
+    return nullptr;
+  }
+
   tcache = ThreadCache::Create(this);
-  thread_caches_being_constructed_.fetch_sub(1, std::memory_order_relaxed);
+  thread_cache_construction_lock.Release();
+
+  return tcache;
+}
+
+ThreadCache* PartitionRoot::ForceInitThreadCache() {
+  auto* tcache = ThreadCache::Get();
+  if (ThreadCache::IsTombstone(tcache)) {
+    // Thread is being terminated, don't try to use the thread cache, and don't
+    // try to resurrect it.
+    return nullptr;
+  }
+
+  // As noted in comments for `MaybeInitThreadCache()`, TLS variable creation
+  // may allocate.
+  // Unlike `MaybeInitThreadCache()`, this function `Acquire()`s the lock and
+  // reentrancy means deadlock here (should crash on debug builds).
+  // Therefore (de)allocation code path in PartitionAlloc must not use this
+  // function.
+  ::partition_alloc::internal::ScopedGuard construction_guard{
+      thread_cache_construction_lock};
+  tcache = ThreadCache::Create(this);
 
   return tcache;
 }
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_root.h b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_root.h
index 6cac7de..fef18b0 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/partition_root.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/partition_root.h
@@ -166,10 +166,12 @@
   static constexpr auto kEnabled = EnableToggle::kEnabled;
 
   EnableToggle thread_cache = kDisabled;
-  AllowToggle star_scan_quarantine = kDisallowed;
   EnableToggle backup_ref_ptr = kDisabled;
   AllowToggle use_configurable_pool = kDisallowed;
 
+  // TODO(https://crbug.com/371135823): Remove after the investigation.
+  size_t backup_ref_ptr_extra_extras_size = 0;
+
   EnableToggle scheduler_loop_quarantine = kDisabled;
   size_t scheduler_loop_quarantine_branch_capacity_in_bytes = 0;
 
@@ -180,6 +182,7 @@
   // compression ratio of freed memory inside partially allocated pages (due to
   // fragmentation).
   EnableToggle eventually_zero_freed_memory = kDisabled;
+  EnableToggle fewer_memory_regions = kDisabled;
 
   struct {
     EnableToggle enabled = kDisabled;
@@ -259,9 +262,14 @@
     size_t in_slot_metadata_size = 0;
 #endif  // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
     bool use_configurable_pool = false;
+    // Despite its name, `FreeFlags` for zapping is deleted and does not exist.
+    // This value is used for SchedulerLoopQuarantine.
+    // TODO(https://crbug.com/351974425): group this setting and quarantine
+    // setting in one place.
     bool zapping_by_free_flags = false;
     bool eventually_zero_freed_memory = false;
     bool scheduler_loop_quarantine = false;
+    bool fewer_memory_regions = false;
 #if PA_BUILDFLAG(HAS_MEMORY_TAGGING)
     bool memory_tagging_enabled_ = false;
     bool use_random_memory_tagging_ = false;
@@ -372,7 +380,11 @@
 
   // Integrity check = ~reinterpret_cast<uintptr_t>(this).
   uintptr_t inverted_self = 0;
-  std::atomic<int> thread_caches_being_constructed_{0};
+
+  // A lock which is hold during thread cache construction.
+  // Any (de)allocation code path should not try to `Acquire()` this lock to
+  // prevent deadlocks. Instead, `TryAcquire()`.
+  internal::Lock thread_cache_construction_lock;
 
   size_t scheduler_loop_quarantine_branch_capacity_in_bytes = 0;
   internal::LightweightQuarantineRoot scheduler_loop_quarantine_root;
@@ -891,6 +903,14 @@
     return GetSchedulerLoopQuarantineBranch();
   }
 
+  void SetSchedulerLoopQuarantineThreadLocalBranchCapacity(
+      size_t capacity_in_bytes) {
+    ThreadCache* thread_cache = this->EnsureThreadCache();
+    PA_CHECK(ThreadCache::IsValid(thread_cache));
+    thread_cache->GetSchedulerLoopQuarantineBranch().SetCapacityInBytes(
+        capacity_in_bytes);
+  }
+
   const internal::PartitionFreelistDispatcher* get_freelist_dispatcher() {
 #if PA_BUILDFLAG(USE_FREELIST_DISPATCHER)
     if (settings.use_pool_offset_freelists) {
@@ -1030,10 +1050,16 @@
   PA_ALWAYS_INLINE void RawFreeLocked(uintptr_t slot_start)
       PA_EXCLUSIVE_LOCKS_REQUIRED(internal::PartitionRootLock(this));
   ThreadCache* MaybeInitThreadCache();
+  ThreadCache* ForceInitThreadCache();
 
   // May return an invalid thread cache.
   PA_ALWAYS_INLINE ThreadCache* GetOrCreateThreadCache();
   PA_ALWAYS_INLINE ThreadCache* GetThreadCache();
+  // Similar to `GetOrCreateThreadCache()`, but this creates a new thread cache
+  // with `ForceInitThreadCache()`. This can be slow since it acquires a lock,
+  // and hence with a risk of deadlock.
+  // Must NOT be used inside (de)allocation code path.
+  PA_ALWAYS_INLINE ThreadCache* EnsureThreadCache();
 
   PA_ALWAYS_INLINE internal::LightweightQuarantineBranch&
   GetSchedulerLoopQuarantineBranch();
@@ -1506,16 +1532,11 @@
   // cacheline ping-pong.
   PA_PREFETCH(slot_span);
 
-  // Further down, we may zap the memory, no point in doing it twice.  We may
-  // zap twice if kZap is enabled without kSchedulerLoopQuarantine. Make sure it
-  // does not happen. This is not a hard requirement: if this is deemed cheap
-  // enough, it can be relaxed, the static_assert() is here to make it a
-  // conscious decision.
-  static_assert(!ContainsFlags(flags, FreeFlags::kZap) ||
-                    ContainsFlags(flags, FreeFlags::kSchedulerLoopQuarantine),
-                "kZap and kSchedulerLoopQuarantine should be used together to "
-                "avoid double zapping");
-  if constexpr (ContainsFlags(flags, FreeFlags::kZap)) {
+  // TODO(crbug.com/40287058): Collecting objects for
+  // `kSchedulerLoopQuarantineBranch` here means it "delays" other checks (BRP
+  // refcount, cookie, etc.)
+  // For better debuggability, we should do these checks before quarantining.
+  if constexpr (ContainsFlags(flags, FreeFlags::kSchedulerLoopQuarantine)) {
     // No need to zap direct mapped allocations, as they are unmapped right
     // away. This also ensures that we don't needlessly memset() very large
     // allocations.
@@ -1524,12 +1545,7 @@
       internal::SecureMemset(object, internal::kFreedByte,
                              GetSlotUsableSize(slot_span));
     }
-  }
-  // TODO(crbug.com/40287058): Collecting objects for
-  // `kSchedulerLoopQuarantineBranch` here means it "delays" other checks (BRP
-  // refcount, cookie, etc.)
-  // For better debuggability, we should do these checks before quarantining.
-  if constexpr (ContainsFlags(flags, FreeFlags::kSchedulerLoopQuarantine)) {
+
     if (settings.scheduler_loop_quarantine) {
 #if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
       // TODO(keishi): Add `[[likely]]` when brp is fully enabled as
@@ -2472,7 +2488,7 @@
   constexpr bool no_hooks = ContainsFlags(alloc_flags, AllocFlags::kNoHooks);
   const bool hooks_enabled = PartitionAllocHooks::AreHooksEnabled();
   bool overridden = false;
-  size_t old_usable_size;
+  size_t old_usable_size = 0;
   if (!no_hooks && hooks_enabled) [[unlikely]] {
     overridden = PartitionAllocHooks::ReallocOverrideHookIfEnabled(
         &old_usable_size, ptr);
@@ -2515,6 +2531,21 @@
     }
   }
 
+#if PA_BUILDFLAG(REALLOC_GROWTH_FACTOR_MITIGATION)
+  // Some nVidia drivers have a performance bug where they repeatedly realloc a
+  // buffer with a small 4144 byte increment instead of using a growth factor to
+  // amortize the cost of a memcpy. To work around this, we apply a growth
+  // factor to the new size to avoid this issue. This workaround is only
+  // intended to be used for Skia bots, and is not intended to be a general
+  // solution.
+  if (new_size > old_usable_size && new_size > 12 << 20) {
+    // 1.5x growth factor.
+    // Note that in case of integer overflow, the std::max ensures that the
+    // new_size is at least as large as the old_usable_size.
+    new_size = std::max(new_size, old_usable_size * 3 / 2);
+  }
+#endif
+
   // This realloc cannot be resized in-place. Sadness.
   void* ret = AllocInternal<alloc_flags>(
       new_size, internal::PartitionPageSize(), type_name);
@@ -2578,6 +2609,17 @@
   return nullptr;
 }
 
+ThreadCache* PartitionRoot::EnsureThreadCache() {
+  ThreadCache* thread_cache = nullptr;
+  if (settings.with_thread_cache) [[likely]] {
+    thread_cache = ThreadCache::Get();
+    if (!ThreadCache::IsValid(thread_cache)) [[unlikely]] {
+      thread_cache = ForceInitThreadCache();
+    }
+  }
+  return thread_cache;
+}
+
 // private.
 internal::LightweightQuarantineBranch&
 PartitionRoot::GetSchedulerLoopQuarantineBranch() {
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr.h b/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr.h
index d830220..bab29dd 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr.h
@@ -10,6 +10,8 @@
 #include <cstddef>
 #include <cstdint>
 #include <functional>
+#include <iterator>
+#include <memory>
 #include <type_traits>
 #include <utility>
 
@@ -70,7 +72,7 @@
 namespace base::internal {
 class DelayTimerBase;
 class JobTaskSource;
-}
+}  // namespace base::internal
 namespace base::test {
 struct RawPtrCountingImplForTest;
 }
@@ -1064,51 +1066,32 @@
 #endif
 
 template <typename T>
-struct IsRawPtr : std::false_type {};
-
+inline constexpr bool IsRawPtr = false;
 template <typename T, RawPtrTraits Traits>
-struct IsRawPtr<raw_ptr<T, Traits>> : std::true_type {};
+inline constexpr bool IsRawPtr<raw_ptr<T, Traits>> = true;
 
 template <typename T>
-inline constexpr bool IsRawPtrV = IsRawPtr<T>::value;
-
-template <typename T>
-inline constexpr bool IsRawPtrMayDangleV = false;
-
+inline constexpr bool IsRawPtrMayDangle = false;
 template <typename T, RawPtrTraits Traits>
-inline constexpr bool IsRawPtrMayDangleV<raw_ptr<T, Traits>> =
+inline constexpr bool IsRawPtrMayDangle<raw_ptr<T, Traits>> =
     partition_alloc::internal::ContainsFlags(Traits, RawPtrTraits::kMayDangle);
 
-// Template helpers for working with T* or raw_ptr<T>.
 template <typename T>
-struct IsRawPointerHelper : std::false_type {};
-
-template <typename T>
-struct IsRawPointerHelper<T*> : std::true_type {};
-
+inline constexpr bool IsPointerOrRawPtr = std::is_pointer_v<T>;
 template <typename T, RawPtrTraits Traits>
-struct IsRawPointerHelper<raw_ptr<T, Traits>> : std::true_type {};
+inline constexpr bool IsPointerOrRawPtr<raw_ptr<T, Traits>> = true;
 
+// Like `std::remove_pointer_t<>`, but also converts `raw_ptr<T>` => `T`.
 template <typename T>
-inline constexpr bool IsRawPointer = IsRawPointerHelper<T>::value;
-
-template <typename T>
-struct RemoveRawPointer {
-  using type = T;
+struct RemovePointer {
+  using type = std::remove_pointer_t<T>;
 };
-
-template <typename T>
-struct RemoveRawPointer<T*> {
-  using type = T;
-};
-
 template <typename T, RawPtrTraits Traits>
-struct RemoveRawPointer<raw_ptr<T, Traits>> {
+struct RemovePointer<raw_ptr<T, Traits>> {
   using type = T;
 };
-
 template <typename T>
-using RemoveRawPointerT = typename RemoveRawPointer<T>::type;
+using RemovePointerT = typename RemovePointer<T>::type;
 
 }  // namespace base
 
@@ -1272,6 +1255,34 @@
   }
 };
 
+#if PA_BUILDFLAG(ASSERT_CPP_20)
+// Mark `raw_ptr<T>` and `T*` as having a common reference type (the type to
+// which both can be converted or bound) of `T*`. This makes them satisfy
+// `std::equality_comparable`, which allows usage like:
+// ```
+//   std::vector<raw_ptr<T>> v;
+//   T* e;
+//   auto it = std::ranges::find(v, e);
+// ```
+// Without this, the `find()` call above would fail to compile with a cryptic
+// error about being unable to invoke `std::ranges::equal_to()`.
+template <typename T,
+          base::RawPtrTraits Traits,
+          template <typename> typename TQ,
+          template <typename> typename UQ>
+struct basic_common_reference<raw_ptr<T, Traits>, T*, TQ, UQ> {
+  using type = T*;
+};
+
+template <typename T,
+          base::RawPtrTraits Traits,
+          template <typename> typename TQ,
+          template <typename> typename UQ>
+struct basic_common_reference<T*, raw_ptr<T, Traits>, TQ, UQ> {
+  using type = T*;
+};
+#endif  // PA_BUILDFLAG(ASSERT_CPP_20)
+
 }  // namespace std
 
 #endif  // PARTITION_ALLOC_POINTERS_RAW_PTR_H_
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_asan_unowned_impl.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_asan_unowned_impl.cc
index 2ecddf5..00724df 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_asan_unowned_impl.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_asan_unowned_impl.cc
@@ -5,6 +5,7 @@
 #include "partition_alloc/pointers/raw_ptr_asan_unowned_impl.h"
 
 #include <sanitizer/asan_interface.h>
+
 #include <cstdint>
 
 #include "partition_alloc/partition_alloc_base/compiler_specific.h"
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_unittest.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_unittest.cc
index f49a2d0..5989dbd 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_unittest.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_unittest.cc
@@ -46,6 +46,7 @@
 
 #if PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
 #include <sanitizer/asan_interface.h>
+
 #include "base/debug/asan_service.h"
 #endif
 
@@ -166,12 +167,12 @@
     Int* array = new Int[4]();
     {
       raw_ptr<Int, base::RawPtrTraits::kAllowPtrArithmetic> ra(array);
-      ++ra;      // operator++()
-      --ra;      // operator--()
-      ra++;      // operator++(int)
-      ra--;      // operator--(int)
-      ra += 1u;  // operator+=()
-      ra -= 1u;  // operator-=()
+      ++ra;                                    // operator++()
+      --ra;                                    // operator--()
+      ra++;                                    // operator++(int)
+      ra--;                                    // operator--(int)
+      ra += 1u;                                // operator+=()
+      ra -= 1u;                                // operator-=()
       ra = ra + 1;                             // operator+(raw_ptr,int)
       ra = 1 + ra;                             // operator+(int,raw_ptr)
       ra = ra - 2;                             // operator-(raw_ptr,int)
@@ -286,9 +287,7 @@
 
 class RawPtrTest : public Test {
  protected:
-  void SetUp() override {
-    RawPtrCountingImpl::ClearCounters();
-  }
+  void SetUp() override { RawPtrCountingImpl::ClearCounters(); }
 };
 
 // Use this instead of std::ignore, to prevent the instruction from getting
@@ -454,11 +453,11 @@
   ptr.ClearAndDelete();
 
   EXPECT_THAT((CountingRawPtrExpectations{
-                .wrap_raw_ptr_cnt = 1,
-                .release_wrapped_ptr_cnt = 1,
-                .get_for_dereference_cnt = 0,
-                .get_for_extraction_cnt = 1,
-                .wrapped_ptr_swap_cnt = 0,
+                  .wrap_raw_ptr_cnt = 1,
+                  .release_wrapped_ptr_cnt = 1,
+                  .get_for_dereference_cnt = 0,
+                  .get_for_extraction_cnt = 1,
+                  .wrapped_ptr_swap_cnt = 0,
               }),
               CountersMatch());
   EXPECT_EQ(ptr.get(), nullptr);
@@ -469,11 +468,11 @@
   ptr.ClearAndDeleteArray();
 
   EXPECT_THAT((CountingRawPtrExpectations{
-                .wrap_raw_ptr_cnt = 1,
-                .release_wrapped_ptr_cnt = 1,
-                .get_for_dereference_cnt = 0,
-                .get_for_extraction_cnt = 1,
-                .wrapped_ptr_swap_cnt = 0,
+                  .wrap_raw_ptr_cnt = 1,
+                  .release_wrapped_ptr_cnt = 1,
+                  .get_for_dereference_cnt = 0,
+                  .get_for_extraction_cnt = 1,
+                  .wrapped_ptr_swap_cnt = 0,
               }),
               CountersMatch());
   EXPECT_EQ(ptr.get(), nullptr);
@@ -915,11 +914,14 @@
 
   {
     Derived derived_val(42, 84, 1024);
-    CountingRawPtr<Derived> checked_derived_ptr = &derived_val;
-    CountingRawPtr<Base1> checked_base1_ptr(std::move(checked_derived_ptr));
-    CountingRawPtr<Base2> checked_base2_ptr(std::move(checked_derived_ptr));
-    checked_base1_ptr = std::move(checked_derived_ptr);
-    checked_base2_ptr = std::move(checked_derived_ptr);
+    CountingRawPtr<Derived> checked_derived_ptr1 = &derived_val;
+    CountingRawPtr<Derived> checked_derived_ptr2 = &derived_val;
+    CountingRawPtr<Derived> checked_derived_ptr3 = &derived_val;
+    CountingRawPtr<Derived> checked_derived_ptr4 = &derived_val;
+    CountingRawPtr<Base1> checked_base1_ptr(std::move(checked_derived_ptr1));
+    CountingRawPtr<Base2> checked_base2_ptr(std::move(checked_derived_ptr2));
+    checked_base1_ptr = std::move(checked_derived_ptr3);
+    checked_base2_ptr = std::move(checked_derived_ptr4);
   }
 
   EXPECT_THAT((CountingRawPtrExpectations{
@@ -1310,6 +1312,20 @@
 
 // This test checks how the std library handles collections like
 // std::vector<raw_ptr<T>>.
+//
+// Currently, reallocating std::vector's storage (e.g. when growing the vector)
+// requires calling raw_ptr's destructor on the old storage (after
+// std::move-ing the data to the new storage).  In the future we hope that
+// TRIVIAL_ABI (or [trivially_relocatable]] proposed by P1144 [1]) will allow
+// memcpy-ing the elements into the new storage (without invoking destructors
+// and move constructors and/or move assignment operators).  At that point, the
+// assert in the test should be modified to capture the new, better behavior.
+//
+// In the meantime, this test ensures that raw_ptr<T> stored in a std::vector
+// passes basic smoke tests.
+//
+// [1]
+// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1144r5.html#wording-attribute
 TEST_F(RawPtrTest, TrivialRelocability) {
   std::vector<CountingRawPtr<int>> vector;
   int x = 123;
@@ -1326,7 +1342,19 @@
     }
     number_of_capacity_changes++;
   } while (number_of_capacity_changes < 10);
+#if PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) ||   \
+    PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || \
+    PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) ||     \
+    PA_BUILDFLAG(RAW_PTR_ZERO_ON_DESTRUCT)
+  // TODO(lukasza): In the future (once C++ language and std library
+  // support custom trivially relocatable objects) this #if branch can
+  // be removed (keeping only the right long-term expectation from the
+  // #else branch).
+  EXPECT_NE(0, RawPtrCountingImpl::release_wrapped_ptr_cnt);
+#else
+  // This is the right long-term expectation.
   EXPECT_EQ(0, RawPtrCountingImpl::release_wrapped_ptr_cnt);
+#endif
   // Basic smoke test that raw_ptr elements in a vector work okay.
   for (const auto& elem : vector) {
     EXPECT_EQ(elem.get(), &x);
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ref.h b/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ref.h
index b6d0e9a..2e619ba 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ref.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ref.h
@@ -26,18 +26,10 @@
 template <class T, RawPtrTraits Traits>
 class raw_ref;
 
-namespace internal {
-
 template <class T>
-struct is_raw_ref : std::false_type {};
-
+inline constexpr bool IsRawRef = false;
 template <class T, RawPtrTraits Traits>
-struct is_raw_ref<::base::raw_ref<T, Traits>> : std::true_type {};
-
-template <class T>
-constexpr inline bool is_raw_ref_v = is_raw_ref<T>::value;
-
-}  // namespace internal
+inline constexpr bool IsRawRef<::base::raw_ref<T, Traits>> = true;
 
 // A smart pointer for a pointer which can not be null, and which provides
 // Use-after-Free protection in the same ways as raw_ptr. This class acts like a
@@ -256,25 +248,25 @@
                                    const raw_ref<V, Traits2>& rhs);
 #endif
 
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr bool operator==(const raw_ref& lhs,
                                                     const U& rhs) {
     PA_RAW_PTR_CHECK(lhs.inner_);  // Catch use-after-move.
     return lhs.inner_ == &rhs;
   }
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr bool operator!=(const raw_ref& lhs,
                                                     const U& rhs) {
     PA_RAW_PTR_CHECK(lhs.inner_);  // Catch use-after-move.
     return lhs.inner_ != &rhs;
   }
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr bool operator==(const U& lhs,
                                                     const raw_ref& rhs) {
     PA_RAW_PTR_CHECK(rhs.inner_);  // Catch use-after-move.
     return &lhs == rhs.inner_;
   }
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr bool operator!=(const U& lhs,
                                                     const raw_ref& rhs) {
     PA_RAW_PTR_CHECK(rhs.inner_);  // Catch use-after-move.
@@ -282,62 +274,62 @@
   }
 
 #if PA_HAVE_SPACESHIP_OPERATOR
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr auto operator<=>(const raw_ref& lhs,
                                                      const U& rhs) {
     PA_RAW_PTR_CHECK(lhs.inner_);  // Catch use-after-move.
     return lhs.inner_ <=> &rhs;
   }
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr auto operator<=>(const U& lhs,
                                                      const raw_ref& rhs) {
     PA_RAW_PTR_CHECK(rhs.inner_);  // Catch use-after-move.
     return &lhs <=> rhs.inner_;
   }
 #else
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr bool operator<(const raw_ref& lhs,
                                                    const U& rhs) {
     PA_RAW_PTR_CHECK(lhs.inner_);  // Catch use-after-move.
     return lhs.inner_ < &rhs;
   }
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr bool operator>(const raw_ref& lhs,
                                                    const U& rhs) {
     PA_RAW_PTR_CHECK(lhs.inner_);  // Catch use-after-move.
     return lhs.inner_ > &rhs;
   }
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr bool operator<=(const raw_ref& lhs,
                                                     const U& rhs) {
     PA_RAW_PTR_CHECK(lhs.inner_);  // Catch use-after-move.
     return lhs.inner_ <= &rhs;
   }
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr bool operator>=(const raw_ref& lhs,
                                                     const U& rhs) {
     PA_RAW_PTR_CHECK(lhs.inner_);  // Catch use-after-move.
     return lhs.inner_ >= &rhs;
   }
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr bool operator<(const U& lhs,
                                                    const raw_ref& rhs) {
     PA_RAW_PTR_CHECK(rhs.inner_);  // Catch use-after-move.
     return &lhs < rhs.inner_;
   }
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr bool operator>(const U& lhs,
                                                    const raw_ref& rhs) {
     PA_RAW_PTR_CHECK(rhs.inner_);  // Catch use-after-move.
     return &lhs > rhs.inner_;
   }
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr bool operator<=(const U& lhs,
                                                     const raw_ref& rhs) {
     PA_RAW_PTR_CHECK(rhs.inner_);  // Catch use-after-move.
     return &lhs <= rhs.inner_;
   }
-  template <class U, class = std::enable_if_t<!internal::is_raw_ref_v<U>, void>>
+  template <class U, class = std::enable_if_t<!IsRawRef<U>, void>>
   PA_ALWAYS_INLINE friend constexpr bool operator>=(const U& lhs,
                                                     const raw_ref& rhs) {
     PA_RAW_PTR_CHECK(rhs.inner_);  // Catch use-after-move.
@@ -411,26 +403,15 @@
 template <class T>
 raw_ref(const T&) -> raw_ref<const T>;
 
-// Template helpers for working with raw_ref<T>.
-template <typename T>
-struct IsRawRef : std::false_type {};
-
-template <typename T, RawPtrTraits Traits>
-struct IsRawRef<raw_ref<T, Traits>> : std::true_type {};
-
-template <typename T>
-inline constexpr bool IsRawRefV = IsRawRef<T>::value;
-
+// Converts `raw_ref<T>` => `T`; leaves l/rvalue refs alone.
 template <typename T>
 struct RemoveRawRef {
   using type = T;
 };
-
 template <typename T, RawPtrTraits Traits>
 struct RemoveRawRef<raw_ref<T, Traits>> {
   using type = T;
 };
-
 template <typename T>
 using RemoveRawRefT = typename RemoveRawRef<T>::type;
 
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ref_unittest.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ref_unittest.cc
index 3e7e6a6..a3b1eba 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ref_unittest.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ref_unittest.cc
@@ -563,43 +563,56 @@
   int i = 1;
   auto r = raw_ref<int>(i);
   auto r2 = std::move(r);
-  EXPECT_CHECK_DEATH({ [[maybe_unused]] auto r3 = r; });
+  EXPECT_CHECK_DEATH({
+    [[maybe_unused]] auto r3 = r;  // NOLINT(bugprone-use-after-move)
+  });
 }
 
 TEST(RawRefDeathTest, MoveConstructAfterMove) {
   int i = 1;
   auto r = raw_ref<int>(i);
   auto r2 = std::move(r);
-  EXPECT_CHECK_DEATH({ [[maybe_unused]] auto r3 = std::move(r); });
+  EXPECT_CHECK_DEATH({
+    [[maybe_unused]] auto r3 = std::move(r);  // NOLINT(bugprone-use-after-move)
+  });
 }
 
 TEST(RawRefDeathTest, CopyAssignAfterMove) {
   int i = 1;
   auto r = raw_ref<int>(i);
   auto r2 = std::move(r);
-  EXPECT_CHECK_DEATH({ r2 = r; });
+  EXPECT_CHECK_DEATH({
+    r2 = r;  // NOLINT(bugprone-use-after-move)
+  });
 }
 
 TEST(RawRefDeathTest, MoveAssignAfterMove) {
   int i = 1;
   auto r = raw_ref<int>(i);
   auto r2 = std::move(r);
-  EXPECT_CHECK_DEATH({ r2 = std::move(r); });
+  EXPECT_CHECK_DEATH({
+    r2 = std::move(r);  // NOLINT(bugprone-use-after-move)
+  });
 }
 
 TEST(RawRefDeathTest, CopyConstructAfterMoveUpCast) {
   auto s = SubClass();
   auto r = raw_ref<SubClass>(s);
   auto moved = std::move(r);
-  EXPECT_CHECK_DEATH({ [[maybe_unused]] auto r2 = raw_ref<BaseClass>(r); });
+  EXPECT_CHECK_DEATH({
+    [[maybe_unused]] auto r2 =
+        raw_ref<BaseClass>(r);  // NOLINT(bugprone-use-after-move)
+  });
 }
 
 TEST(RawRefDeathTest, MoveConstructAfterMoveUpCast) {
   auto s = SubClass();
   auto r = raw_ref<SubClass>(s);
   auto moved = std::move(r);
-  EXPECT_CHECK_DEATH(
-      { [[maybe_unused]] auto r2 = raw_ref<BaseClass>(std::move(r)); });
+  EXPECT_CHECK_DEATH({
+    [[maybe_unused]] auto r2 =
+        raw_ref<BaseClass>(std::move(r));  // NOLINT(bugprone-use-after-move)
+  });
 }
 
 TEST(RawRefDeathTest, FromPtrWithNullptr) {
@@ -612,7 +625,9 @@
   auto t = BaseClass();
   auto rt = raw_ref<const BaseClass>(t);
   auto moved = std::move(r);
-  EXPECT_CHECK_DEATH({ rt = r; });
+  EXPECT_CHECK_DEATH({
+    rt = r;  // NOLINT(bugprone-use-after-move)
+  });
 }
 
 TEST(RawRefDeathTest, MoveAssignAfterMoveUpCast) {
@@ -621,21 +636,27 @@
   auto t = BaseClass();
   auto rt = raw_ref<const BaseClass>(t);
   auto moved = std::move(r);
-  EXPECT_CHECK_DEATH({ rt = std::move(r); });
+  EXPECT_CHECK_DEATH({
+    rt = std::move(r);  // NOLINT(bugprone-use-after-move)
+  });
 }
 
 TEST(RawRefDeathTest, DerefAfterMove) {
   int i;
   auto r = raw_ref<int>(i);
   auto moved = std::move(r);
-  EXPECT_CHECK_DEATH({ r.operator*(); });
+  EXPECT_CHECK_DEATH({
+    r.operator*();  // NOLINT(bugprone-use-after-move)
+  });
 }
 
 TEST(RawRefDeathTest, ArrowAfterMove) {
   int i;
   auto r = raw_ref<int>(i);
   auto moved = std::move(r);
-  EXPECT_CHECK_DEATH({ r.operator->(); });
+  EXPECT_CHECK_DEATH({
+    r.operator->();  // NOLINT(bugprone-use-after-move)
+  });
 }
 
 TEST(RawRefDeathTest, SwapAfterMove) {
@@ -646,7 +667,9 @@
     auto rj = raw_ref<int>(j);
 
     auto moved = std::move(ri);
-    EXPECT_CHECK_DEATH({ swap(ri, rj); });
+    EXPECT_CHECK_DEATH({
+      swap(ri, rj);  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i;
@@ -655,7 +678,9 @@
     auto rj = raw_ref<int>(j);
 
     auto moved = std::move(rj);
-    EXPECT_CHECK_DEATH({ swap(ri, rj); });
+    EXPECT_CHECK_DEATH({
+      swap(ri, rj);  // NOLINT(bugprone-use-after-move)
+    });
   }
 }
 
@@ -665,20 +690,26 @@
     auto r1 = raw_ref<int>(i);
     auto r2 = raw_ref<int>(i);
     auto moved = std::move(r1);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 == r2; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 == r2;  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i = 1;
     auto r1 = raw_ref<int>(i);
     auto r2 = raw_ref<int>(i);
     auto moved = std::move(r2);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 == r2; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 == r2;  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i = 1;
     auto r1 = raw_ref<int>(i);
     auto moved = std::move(r1);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 == r1; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 == r1;  // NOLINT(bugprone-use-after-move)
+    });
   }
 }
 
@@ -688,20 +719,26 @@
     auto r1 = raw_ref<int>(i);
     auto r2 = raw_ref<int>(i);
     auto moved = std::move(r1);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 != r2; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 != r2;  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i = 1;
     auto r1 = raw_ref<int>(i);
     auto r2 = raw_ref<int>(i);
     auto moved = std::move(r2);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 != r2; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 != r2;  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i = 1;
     auto r1 = raw_ref<int>(i);
     auto moved = std::move(r1);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 != r1; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 != r1;  // NOLINT(bugprone-use-after-move)
+    });
   }
 }
 
@@ -711,20 +748,26 @@
     auto r1 = raw_ref<int>(i);
     auto r2 = raw_ref<int>(i);
     auto moved = std::move(r1);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 < r2; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 < r2;  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i = 1;
     auto r1 = raw_ref<int>(i);
     auto r2 = raw_ref<int>(i);
     auto moved = std::move(r2);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 < r2; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 < r2;  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i = 1;
     auto r1 = raw_ref<int>(i);
     auto moved = std::move(r1);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 < r1; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 < r1;  // NOLINT(bugprone-use-after-move)
+    });
   }
 }
 
@@ -734,20 +777,26 @@
     auto r1 = raw_ref<int>(i);
     auto r2 = raw_ref<int>(i);
     auto moved = std::move(r1);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 > r2; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 > r2;  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i = 1;
     auto r1 = raw_ref<int>(i);
     auto r2 = raw_ref<int>(i);
     auto moved = std::move(r2);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 > r2; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 > r2;  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i = 1;
     auto r1 = raw_ref<int>(i);
     auto moved = std::move(r1);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 > r1; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 > r1;  // NOLINT(bugprone-use-after-move)
+    });
   }
 }
 
@@ -757,20 +806,26 @@
     auto r1 = raw_ref<int>(i);
     auto r2 = raw_ref<int>(i);
     auto moved = std::move(r1);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 <= r2; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 <= r2;  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i = 1;
     auto r1 = raw_ref<int>(i);
     auto r2 = raw_ref<int>(i);
     auto moved = std::move(r2);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 <= r2; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 <= r2;  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i = 1;
     auto r1 = raw_ref<int>(i);
     auto moved = std::move(r1);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 <= r1; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 <= r1;  // NOLINT(bugprone-use-after-move)
+    });
   }
 }
 
@@ -780,20 +835,26 @@
     auto r1 = raw_ref<int>(i);
     auto r2 = raw_ref<int>(i);
     auto moved = std::move(r1);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 >= r2; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 >= r2;  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i = 1;
     auto r1 = raw_ref<int>(i);
     auto r2 = raw_ref<int>(i);
     auto moved = std::move(r2);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 >= r2; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 >= r2;  // NOLINT(bugprone-use-after-move)
+    });
   }
   {
     int i = 1;
     auto r1 = raw_ref<int>(i);
     auto moved = std::move(r1);
-    EXPECT_CHECK_DEATH({ [[maybe_unused]] bool b = r1 >= r1; });
+    EXPECT_CHECK_DEATH({
+      [[maybe_unused]] bool b = r1 >= r1;  // NOLINT(bugprone-use-after-move)
+    });
   }
 }
 
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/random.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/random.cc
index 6e7a97d..9ace4f0 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/random.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/random.cc
@@ -27,7 +27,7 @@
   }
 
  private:
-  ::partition_alloc::internal::Lock lock_ = {};
+  ::partition_alloc::internal::Lock lock_;
   bool initialized_ PA_GUARDED_BY(lock_) = false;
   union {
     internal::base::InsecureRandomGenerator instance_ PA_GUARDED_BY(lock_);
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/reservation_offset_table.h b/tot/base/allocator/partition_allocator/src/partition_alloc/reservation_offset_table.h
index e5fba00..463912b 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/reservation_offset_table.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/reservation_offset_table.h
@@ -8,7 +8,6 @@
 #include <cstddef>
 #include <cstdint>
 #include <limits>
-#include <tuple>
 
 #include "partition_alloc/address_pool_manager.h"
 #include "partition_alloc/build_config.h"
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.cc
index 03528ff..fa5ee97 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.cc
@@ -31,7 +31,6 @@
 // noexcept needs to be routed to
 // allocator_shim::internal::PartitionMallocUnchecked through the shim layer.
 #include "partition_alloc/shim/allocator_shim_override_cpp_symbols.h"
-
 #include "partition_alloc/shim/allocator_shim_override_libc_symbols.h"
 
 // Some glibc versions (until commit 6c444ad6e953dbdf9c7be065308a0a777)
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.h b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.h
index a790b31..af36a98 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.h
@@ -150,9 +150,9 @@
                                                  bool>;
 using EventuallyZeroFreedMemory = partition_alloc::internal::base::
     StrongAlias<class EventuallyZeroFreedMemoryTag, bool>;
-using UsePoolOffsetFreelists = partition_alloc::internal::base::
-    StrongAlias<class UsePoolOffsetFreelistsTag, bool>;
-
+using FewerMemoryRegions =
+    partition_alloc::internal::base::StrongAlias<class FewerMemoryRegionsTag,
+                                                 bool>;
 using UseSmallSingleSlotSpans = partition_alloc::internal::base::
     StrongAlias<class UseSmallSingleSlotSpansTag, bool>;
 
@@ -162,6 +162,7 @@
 PA_COMPONENT_EXPORT(ALLOCATOR_SHIM)
 void ConfigurePartitions(
     EnableBrp enable_brp,
+    size_t brp_extra_extras_size,
     EnableMemoryTagging enable_memory_tagging,
     partition_alloc::TagViolationReportingMode memory_tagging_reporting_mode,
     BucketDistribution distribution,
@@ -169,7 +170,7 @@
     size_t scheduler_loop_quarantine_branch_capacity_in_bytes,
     ZappingByFreeFlags zapping_by_free_flags,
     EventuallyZeroFreedMemory eventually_zero_freed_memory,
-    UsePoolOffsetFreelists use_pool_offset_freelists,
+    FewerMemoryRegions fewer_memory_regions,
     UseSmallSingleSlotSpans use_small_single_slot_spans);
 
 PA_COMPONENT_EXPORT(ALLOCATOR_SHIM) uint32_t GetMainPartitionRootExtrasSize();
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_glibc.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_glibc.cc
index 699d98d..93352d9 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_glibc.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_glibc.cc
@@ -2,6 +2,9 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include <dlfcn.h>
+#include <malloc.h>
+
 #include <limits>
 
 #include "partition_alloc/oom.h"
@@ -9,9 +12,6 @@
 #include "partition_alloc/partition_alloc_base/numerics/checked_math.h"
 #include "partition_alloc/shim/allocator_shim.h"
 
-#include <dlfcn.h>
-#include <malloc.h>
-
 // This translation unit defines a default dispatch for the allocator shim which
 // routes allocations to libc functions.
 // The code here is strongly inspired from tcmalloc's libc_override_glibc.h.
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.cc
index 3e7f3cc..afe6bb8 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.cc
@@ -26,6 +26,7 @@
 #include "partition_alloc/partition_root.h"
 #include "partition_alloc/partition_stats.h"
 #include "partition_alloc/shim/allocator_dispatch.h"
+#include "partition_alloc/shim/allocator_shim.h"
 #include "partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc_internal.h"
 #include "partition_alloc/shim/allocator_shim_internals.h"
 
@@ -101,7 +102,7 @@
     __cpp_lib_atomic_value_initialization < 201911L
   alignas(T) uint8_t instance_buffer_[sizeof(T)];
 #else
-  alignas(T) uint8_t instance_buffer_[sizeof(T)] = {0};
+  alignas(T) uint8_t instance_buffer_[sizeof(T)] = {};
 #endif
   std::atomic<bool> initialization_lock_;
 };
@@ -148,7 +149,6 @@
     // the decision to turn the thread cache on until then.
     // Also tests, such as the ThreadCache tests create a thread cache.
     opts.thread_cache = partition_alloc::PartitionOptions::kDisabled;
-    opts.star_scan_quarantine = partition_alloc::PartitionOptions::kAllowed;
     opts.backup_ref_ptr = partition_alloc::PartitionOptions::kDisabled;
     auto* new_root = new (buffer) partition_alloc::PartitionRoot(opts);
 
@@ -571,7 +571,6 @@
     PartitionAllocFunctionsInternal<
         partition_alloc::AllocFlags::kNoHooks,
         partition_alloc::FreeFlags::kNoHooks |
-            partition_alloc::FreeFlags::kZap |
             partition_alloc::FreeFlags::kSchedulerLoopQuarantine>;
 
 // static
@@ -612,6 +611,7 @@
 
 void ConfigurePartitions(
     EnableBrp enable_brp,
+    size_t brp_extra_extras_size,
     EnableMemoryTagging enable_memory_tagging,
     partition_alloc::TagViolationReportingMode memory_tagging_reporting_mode,
     BucketDistribution distribution,
@@ -619,7 +619,7 @@
     size_t scheduler_loop_quarantine_branch_capacity_in_bytes,
     ZappingByFreeFlags zapping_by_free_flags,
     EventuallyZeroFreedMemory eventually_zero_freed_memory,
-    UsePoolOffsetFreelists use_pool_offset_freelists,
+    FewerMemoryRegions fewer_memory_regions,
     UseSmallSingleSlotSpans use_small_single_slot_spans) {
   // Calling Get() is actually important, even if the return value isn't
   // used, because it has a side effect of initializing the variable, if it
@@ -640,10 +640,10 @@
         // another partition will have the thread cache enabled, by calling
         // EnableThreadCacheIfSupported().
         opts.thread_cache = partition_alloc::PartitionOptions::kDisabled;
-        opts.star_scan_quarantine = partition_alloc::PartitionOptions::kAllowed;
         opts.backup_ref_ptr =
             enable_brp ? partition_alloc::PartitionOptions::kEnabled
                        : partition_alloc::PartitionOptions::kDisabled;
+        opts.backup_ref_ptr_extra_extras_size = brp_extra_extras_size;
         opts.zapping_by_free_flags =
             zapping_by_free_flags
                 ? partition_alloc::PartitionOptions::kEnabled
@@ -652,6 +652,9 @@
             eventually_zero_freed_memory
                 ? partition_alloc::PartitionOptions::kEnabled
                 : partition_alloc::PartitionOptions::kDisabled;
+        opts.fewer_memory_regions =
+            fewer_memory_regions ? partition_alloc::PartitionOptions::kEnabled
+                                 : partition_alloc::PartitionOptions::kDisabled;
         opts.scheduler_loop_quarantine =
             scheduler_loop_quarantine
                 ? partition_alloc::PartitionOptions::kEnabled
@@ -664,9 +667,7 @@
                            : partition_alloc::PartitionOptions::kDisabled,
             .reporting_mode = memory_tagging_reporting_mode};
         opts.use_pool_offset_freelists =
-            use_pool_offset_freelists
-                ? partition_alloc::PartitionOptions::kEnabled
-                : partition_alloc::PartitionOptions::kDisabled;
+            partition_alloc::PartitionOptions::kEnabled;
         opts.use_small_single_slot_spans =
             use_small_single_slot_spans
                 ? partition_alloc::PartitionOptions::kEnabled
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h
index 129037c..d4bcc7c 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h
@@ -135,7 +135,6 @@
     PartitionAllocFunctionsInternal<
         partition_alloc::AllocFlags::kNoHooks,
         partition_alloc::FreeFlags::kNoHooks |
-            partition_alloc::FreeFlags::kZap |
             partition_alloc::FreeFlags::kSchedulerLoopQuarantine>;
 
 // `PartitionAllocFunctions` in instantiated in cc file.
@@ -147,7 +146,6 @@
     PartitionAllocFunctionsInternal<
         partition_alloc::AllocFlags::kNoHooks,
         partition_alloc::FreeFlags::kNoHooks |
-            partition_alloc::FreeFlags::kZap |
             partition_alloc::FreeFlags::kSchedulerLoopQuarantine>;
 
 }  // namespace internal
@@ -164,6 +162,7 @@
 // this function. They should call ConfigurePartitions() directly.
 PA_ALWAYS_INLINE void ConfigurePartitionsForTesting() {
   auto enable_brp = allocator_shim::EnableBrp(true);
+  size_t brp_extra_extras_size = 0;
 
   // Embedders's tests might benefit from MTE checks. However, this is costly
   // and shouldn't be used in benchmarks.
@@ -181,15 +180,15 @@
   size_t scheduler_loop_quarantine_capacity_in_bytes = 0;
   auto zapping_by_free_flags = ZappingByFreeFlags(false);
   auto eventually_zero_freed_memory = EventuallyZeroFreedMemory(false);
-  auto use_pool_offset_freelists = UsePoolOffsetFreelists(true);
+  auto fewer_memory_regions = FewerMemoryRegions(false);
   auto use_small_single_slot_spans = UseSmallSingleSlotSpans(true);
 
-  ConfigurePartitions(enable_brp, enable_memory_tagging,
+  ConfigurePartitions(enable_brp, brp_extra_extras_size, enable_memory_tagging,
                       memory_tagging_reporting_mode, distribution,
                       scheduler_loop_quarantine,
                       scheduler_loop_quarantine_capacity_in_bytes,
                       zapping_by_free_flags, eventually_zero_freed_memory,
-                      use_pool_offset_freelists, use_small_single_slot_spans);
+                      fewer_memory_regions, use_small_single_slot_spans);
 }
 #endif  // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
 
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_winheap.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_winheap.cc
index eca4faa..9338184 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_winheap.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_winheap.cc
@@ -2,11 +2,10 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "partition_alloc/shim/allocator_shim.h"
-
 #include <ostream>
 
 #include "partition_alloc/partition_alloc_check.h"
+#include "partition_alloc/shim/allocator_shim.h"
 #include "partition_alloc/shim/winheap_stubs_win.h"
 
 namespace {
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_ucrt_symbols_win.h b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_ucrt_symbols_win.h
index cc8fd59..f8a0f82 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_ucrt_symbols_win.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_ucrt_symbols_win.h
@@ -276,7 +276,7 @@
 }
 #endif
 
-#if !defined(NDEBUG)
+#if PA_BUILDFLAG(IS_DEBUG)
 typedef void (*_CRT_DUMP_CLIENT)(void*, size_t);
 
 int _crtDbgFlag = 0;
@@ -451,9 +451,9 @@
 }
 #endif  // defined(COMPONENT_BUILD)
 
-#endif  // !defined(NDEBUG)
+#endif  // PA_BUILDFLAG(IS_DEBUG)
 
-}  // extern "C"
+}       // extern "C"
 #endif  // PA_BUILDFLAG(USE_ALLOCATOR_SHIM)
 
 #endif  // PARTITION_ALLOC_SHIM_ALLOCATOR_SHIM_OVERRIDE_UCRT_SYMBOLS_WIN_H_
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_unittest.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_unittest.cc
index 26e2bb1..e2ab065 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_unittest.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_unittest.cc
@@ -63,7 +63,7 @@
 
 class AllocatorShimTest : public testing::Test {
  public:
-  AllocatorShimTest() : testing::Test() {}
+  AllocatorShimTest() = default;
 
   static size_t Hash(const void* ptr) {
     return reinterpret_cast<uintptr_t>(ptr) % MaxSizeTracked();
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/spinning_mutex.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/spinning_mutex.cc
index 91eda73..df55119 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/spinning_mutex.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/spinning_mutex.cc
@@ -142,8 +142,33 @@
 
 #elif PA_BUILDFLAG(IS_APPLE)
 
+// TODO(verwaest): We should use the constants from the header, but they aren't
+// exposed until macOS 15. See their definition here:
+// https://github.com/apple-oss-distributions/libplatform/blob/4f6349dfea579c35b8fa838d785644e441d14e0e/private/os/lock_private.h#L265
+//
+// The first flag prevents the runtime from creating more threads in response to
+// contention. The second will spin in the kernel if the lock owner is currently
+// running.
+#define OS_UNFAIR_LOCK_DATA_SYNCHRONIZATION 0x00010000
+#define OS_UNFAIR_LOCK_ADAPTIVE_SPIN 0x00040000
+
+typedef uint32_t os_unfair_lock_options_t;
+
+extern "C" {
+void __attribute__((weak))
+os_unfair_lock_lock_with_options(os_unfair_lock* lock,
+                                 os_unfair_lock_options_t);
+}
+
 void SpinningMutex::LockSlow() {
-  return os_unfair_lock_lock(&unfair_lock_);
+  if (os_unfair_lock_lock_with_options) {
+    const os_unfair_lock_options_t options =
+        static_cast<os_unfair_lock_options_t>(
+            OS_UNFAIR_LOCK_DATA_SYNCHRONIZATION | OS_UNFAIR_LOCK_ADAPTIVE_SPIN);
+    os_unfair_lock_lock_with_options(&unfair_lock_, options);
+  } else {
+    os_unfair_lock_lock(&unfair_lock_);
+  }
 }
 
 #elif PA_BUILDFLAG(IS_POSIX)
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/thread_cache.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/thread_cache.cc
index f20c924..9b0df39 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/thread_cache.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/thread_cache.cc
@@ -377,7 +377,11 @@
 // static
 void ThreadCache::RemoveTombstoneForTesting() {
   PA_CHECK(IsTombstone(Get()));
+#if PA_CONFIG(THREAD_CACHE_FAST_TLS)
+  internal::g_thread_cache = nullptr;
+#else
   internal::PartitionTlsSet(internal::g_thread_cache_key, nullptr);
+#endif
 }
 
 // static
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/thread_cache_unittest.cc b/tot/base/allocator/partition_allocator/src/partition_alloc/thread_cache_unittest.cc
index cc48ea4..895b62c 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/thread_cache_unittest.cc
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/thread_cache_unittest.cc
@@ -89,7 +89,6 @@
 #if !PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
   opts.thread_cache = PartitionOptions::kEnabled;
 #endif  // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
-  opts.star_scan_quarantine = PartitionOptions::kAllowed;
   opts.use_pool_offset_freelists =
       (encoding == internal::PartitionFreelistEncoding::kPoolOffsetFreeList)
           ? PartitionOptions::kEnabled
@@ -117,6 +116,7 @@
       ThreadCache::RemoveTombstoneForTesting();
     }
   }
+
  protected:
   void SetUp() override {
     PartitionRoot* root = allocator_->root();
@@ -301,7 +301,6 @@
 
 TEST_P(PartitionAllocThreadCacheTest, NoCrossPartitionCache) {
   PartitionOptions opts;
-  opts.star_scan_quarantine = PartitionOptions::kAllowed;
   PartitionAllocatorForTesting allocator(opts);
 
   size_t bucket_index = FillThreadCacheAndReturnIndex(kSmallSize);
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey.h b/tot/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey.h
index c36bfa4..8c233f6 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey.h
@@ -12,7 +12,6 @@
 #include <cstddef>
 #include <cstdint>
 
-#include "partition_alloc/buildflags.h"
 #include "partition_alloc/partition_alloc_base/component_export.h"
 #include "partition_alloc/thread_isolation/alignment.h"
 
diff --git a/tot/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/thread_isolation.h b/tot/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/thread_isolation.h
index dc183f2..f3dbe9d 100644
--- a/tot/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/thread_isolation.h
+++ b/tot/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/thread_isolation.h
@@ -12,7 +12,6 @@
 #include <cstddef>
 #include <cstdint>
 
-#include "partition_alloc/buildflags.h"
 #include "partition_alloc/partition_alloc_base/component_export.h"
 
 #if PA_BUILDFLAG(ENABLE_PKEYS)
diff --git a/tot/base/android/android_info.cc b/tot/base/android/android_info.cc
new file mode 100644
index 0000000..99d736d
--- /dev/null
+++ b/tot/base/android/android_info.cc
@@ -0,0 +1,197 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/android/android_info.h"
+
+#include <cstring>
+#include <mutex>
+#include <string>
+#include <variant>
+
+#include "base/android/jni_android.h"
+#include "base/android/jni_array.h"
+#include "base/android/jni_string.h"
+#include "base/android/scoped_java_ref.h"
+#include "base/check.h"
+#include "base/compiler_specific.h"
+#include "base/strings/string_number_conversions.h"
+
+// Must come after all headers that specialize FromJniType() / ToJniType().
+#include "base/android_info_jni/AndroidInfo_jni.h"
+
+namespace base::android::android_info {
+
+namespace {
+
+struct AndroidInfo {
+  // Const char* is used instead of std::strings because these values must be
+  // available even if the process is in a crash state. Sadly
+  // std::string.c_str() doesn't guarantee that memory won't be allocated when
+  // it is called.
+  const char* device;
+
+  const char* manufacturer;
+
+  const char* model;
+
+  const char* brand;
+
+  const char* android_build_id;
+
+  const char* build_type;
+
+  const char* board;
+
+  const char* android_build_fp;
+
+  int sdk_int;
+
+  bool is_debug_android;
+
+  const char* version_incremental;
+
+  const char* hardware;
+
+  bool is_at_least_u;
+
+  const char* codename;
+
+  // Available only on android S+. For S-, this method returns empty string.
+  const char* soc_manufacturer;
+
+  bool is_at_least_t;
+
+  const char* abi_name;
+};
+
+std::optional<AndroidInfo> holder;
+
+const AndroidInfo& get_android_info() {
+  [[maybe_unused]] static auto once = [] {
+    Java_AndroidInfo_nativeReadyForFields(AttachCurrentThread());
+    return std::monostate();
+  }();
+  // holder should be initialized as the java is supposed to call the native
+  // method FillFields which will initialize the fields within the holder.
+  DCHECK(holder.has_value());
+  return *holder;
+}
+
+}  // namespace
+
+static void JNI_AndroidInfo_FillFields(
+    JNIEnv* env,
+    const jni_zero::JavaParamRef<jstring>& brand,
+    const jni_zero::JavaParamRef<jstring>& device,
+    const jni_zero::JavaParamRef<jstring>& buildId,
+    const jni_zero::JavaParamRef<jstring>& manufacturer,
+    const jni_zero::JavaParamRef<jstring>& model,
+    const jni_zero::JavaParamRef<jstring>& type,
+    const jni_zero::JavaParamRef<jstring>& board,
+    const jni_zero::JavaParamRef<jstring>& androidBuildFingerprint,
+    const jni_zero::JavaParamRef<jstring>& versionIncremental,
+    const jni_zero::JavaParamRef<jstring>& hardware,
+    const jni_zero::JavaParamRef<jstring>& codeName,
+    const jni_zero::JavaParamRef<jstring>& socManufacturer,
+    const jni_zero::JavaParamRef<jstring>& supportedAbis,
+    jint sdkInt,
+    jboolean isDebugAndroid,
+    jboolean isAtleastU,
+    jboolean isAtleastT) {
+  DCHECK(!holder.has_value());
+  auto java_string_to_const_char =
+      [](const jni_zero::JavaParamRef<jstring>& str) {
+        return UNSAFE_TODO(strdup(ConvertJavaStringToUTF8(str).c_str()));
+      };
+  holder = AndroidInfo{
+      .device = java_string_to_const_char(device),
+      .manufacturer = java_string_to_const_char(manufacturer),
+      .model = java_string_to_const_char(model),
+      .brand = java_string_to_const_char(brand),
+      .android_build_id = java_string_to_const_char(buildId),
+      .build_type = java_string_to_const_char(type),
+      .board = java_string_to_const_char(board),
+      .android_build_fp = java_string_to_const_char(androidBuildFingerprint),
+      .sdk_int = sdkInt,
+      .is_debug_android = static_cast<bool>(isDebugAndroid),
+      .version_incremental = java_string_to_const_char(versionIncremental),
+      .hardware = java_string_to_const_char(hardware),
+      .is_at_least_u = static_cast<bool>(isAtleastU),
+      .codename = java_string_to_const_char(codeName),
+      .soc_manufacturer = java_string_to_const_char(socManufacturer),
+      .is_at_least_t = static_cast<bool>(isAtleastT),
+      .abi_name = java_string_to_const_char(supportedAbis),
+  };
+}
+
+const char* device() {
+  return get_android_info().device;
+}
+
+const char* manufacturer() {
+  return get_android_info().manufacturer;
+}
+
+const char* model() {
+  return get_android_info().model;
+}
+
+const char* brand() {
+  return get_android_info().brand;
+}
+
+const char* android_build_id() {
+  return get_android_info().android_build_id;
+}
+
+const char* build_type() {
+  return get_android_info().build_type;
+}
+
+const char* board() {
+  return get_android_info().board;
+}
+
+const char* android_build_fp() {
+  return get_android_info().android_build_fp;
+}
+
+int sdk_int() {
+  return get_android_info().sdk_int;
+}
+
+bool is_debug_android() {
+  return get_android_info().is_debug_android;
+}
+
+const char* version_incremental() {
+  return get_android_info().version_incremental;
+}
+
+const char* hardware() {
+  return get_android_info().hardware;
+}
+
+bool is_at_least_u() {
+  return get_android_info().is_at_least_u;
+}
+
+const char* codename() {
+  return get_android_info().codename;
+}
+
+// Available only on android S+. For S-, this method returns empty string.
+const char* soc_manufacturer() {
+  return get_android_info().soc_manufacturer;
+}
+
+bool is_at_least_t() {
+  return get_android_info().is_at_least_t;
+}
+
+const char* abi_name() {
+  return get_android_info().abi_name;
+}
+
+}  // namespace base::android::android_info
diff --git a/tot/base/android/android_info.h b/tot/base/android/android_info.h
new file mode 100644
index 0000000..38cc8d0
--- /dev/null
+++ b/tot/base/android/android_info.h
@@ -0,0 +1,74 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_ANDROID_ANDROID_INFO_H_
+#define BASE_ANDROID_ANDROID_INFO_H_
+
+#include "base/base_export.h"
+
+namespace base::android::android_info {
+
+// This enumeration maps to the values returned by AndroidInfo::sdk_int(),
+// indicating the Android release associated with a given SDK version.
+enum SdkVersion {
+  SDK_VERSION_JELLY_BEAN = 16,
+  SDK_VERSION_JELLY_BEAN_MR1 = 17,
+  SDK_VERSION_JELLY_BEAN_MR2 = 18,
+  SDK_VERSION_KITKAT = 19,
+  SDK_VERSION_KITKAT_WEAR = 20,
+  SDK_VERSION_LOLLIPOP = 21,
+  SDK_VERSION_LOLLIPOP_MR1 = 22,
+  SDK_VERSION_MARSHMALLOW = 23,
+  SDK_VERSION_NOUGAT = 24,
+  SDK_VERSION_NOUGAT_MR1 = 25,
+  SDK_VERSION_OREO = 26,
+  SDK_VERSION_O_MR1 = 27,
+  SDK_VERSION_P = 28,
+  SDK_VERSION_Q = 29,
+  SDK_VERSION_R = 30,
+  SDK_VERSION_S = 31,
+  SDK_VERSION_Sv2 = 32,
+  SDK_VERSION_T = 33,
+  SDK_VERSION_U = 34,
+  SDK_VERSION_V = 35,
+};
+
+const char* device();
+
+const char* manufacturer();
+
+const char* model();
+
+BASE_EXPORT const char* brand();
+
+const char* android_build_id();
+
+const char* build_type();
+
+const char* board();
+
+const char* android_build_fp();
+
+BASE_EXPORT int sdk_int();
+
+bool is_debug_android();
+
+const char* version_incremental();
+
+BASE_EXPORT const char* hardware();
+
+bool is_at_least_u();
+
+const char* codename();
+
+// Available only on android S+. For S-, this method returns empty string.
+const char* soc_manufacturer();
+
+bool is_at_least_t();
+
+const char* abi_name();
+
+}  // namespace base::android::android_info
+
+#endif  // BASE_ANDROID_ANDROID_INFO_H_
diff --git a/tot/base/android/apk_assets.cc b/tot/base/android/apk_assets.cc
index 4273a46..9df5cb5 100644
--- a/tot/base/android/apk_assets.cc
+++ b/tot/base/android/apk_assets.cc
@@ -2,10 +2,10 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include <jni.h>
-
 #include "base/android/apk_assets.h"
 
+#include <jni.h>
+
 #include "base/android/jni_array.h"
 #include "base/android/jni_string.h"
 #include "base/android/scoped_java_ref.h"
@@ -26,8 +26,7 @@
   // resources :(
   JNIEnv* env = base::android::AttachCurrentThread();
   ScopedJavaLocalRef<jlongArray> jarr =
-      Java_ApkAssets_open(env, ConvertUTF8ToJavaString(env, file_path),
-                          ConvertUTF8ToJavaString(env, split_name));
+      Java_ApkAssets_open(env, file_path, split_name);
   std::vector<jlong> results;
   base::android::JavaLongArrayToLongVector(env, jarr, &results);
   CHECK_EQ(3U, results.size());
@@ -48,8 +47,9 @@
   base::MemoryMappedFile::Region region =
       base::MemoryMappedFile::Region::kWholeFile;
   int asset_fd = OpenApkAsset(file_path.value(), &region);
-  if (asset_fd == -1)
+  if (asset_fd == -1) {
     return false;
+  }
   base::FileDescriptorStore::GetInstance().Set(key, base::ScopedFD(asset_fd),
                                                region);
   return true;
@@ -57,13 +57,11 @@
 
 void DumpLastOpenApkAssetFailure() {
   JNIEnv* env = base::android::AttachCurrentThread();
-  base::android::ScopedJavaLocalRef<jstring> error =
-      Java_ApkAssets_takeLastErrorString(env);
-  if (!error) {
+  std::string error = Java_ApkAssets_takeLastErrorString(env);
+  if (error.empty()) {
     return;
   }
-  SCOPED_CRASH_KEY_STRING256("base", "OpenApkAssetError",
-                             ConvertJavaStringToUTF8(env, error));
+  SCOPED_CRASH_KEY_STRING256("base", "OpenApkAssetError", error);
   base::debug::DumpWithoutCrashing();
 }
 
diff --git a/tot/base/android/apk_assets.h b/tot/base/android/apk_assets.h
index 6389eb0..5b720b4 100644
--- a/tot/base/android/apk_assets.h
+++ b/tot/base/android/apk_assets.h
@@ -26,9 +26,8 @@
 BASE_EXPORT int OpenApkAsset(const std::string& file_path,
                              const std::string& split_name,
                              base::MemoryMappedFile::Region* region);
-BASE_EXPORT int OpenApkAsset(
-    const std::string& file_path,
-    base::MemoryMappedFile::Region* region);
+BASE_EXPORT int OpenApkAsset(const std::string& file_path,
+                             base::MemoryMappedFile::Region* region);
 
 // Registers an uncompressed asset from within the apk in the
 // FileDescriptorStore.
diff --git a/tot/base/android/apk_info.cc b/tot/base/android/apk_info.cc
new file mode 100644
index 0000000..f9e629e
--- /dev/null
+++ b/tot/base/android/apk_info.cc
@@ -0,0 +1,132 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/android/apk_info.h"
+
+#include <string>
+#include <variant>
+
+#include "base/android/jni_android.h"
+#include "base/android/jni_array.h"
+#include "base/android/jni_string.h"
+#include "base/android/scoped_java_ref.h"
+#include "base/compiler_specific.h"
+#include "base/strings/string_number_conversions.h"
+
+// Must come after all headers that specialize FromJniType() / ToJniType().
+#include "base/build_info_jni/ApkInfo_jni.h"
+
+namespace base::android::apk_info {
+
+namespace {
+
+struct ApkInfo {
+  // Const char* is used instead of std::strings because these values must be
+  // available even if the process is in a crash state. Sadly
+  // std::string.c_str() doesn't guarantee that memory won't be allocated when
+  // it is called.
+  const char* host_package_name;
+  const char* host_version_code;
+  const char* host_package_label;
+  const char* package_version_code;
+  const char* package_version_name;
+  const char* package_name;
+  const char* resources_version;
+  const char* installer_package_name;
+  bool is_debug_app;
+  bool targets_at_least_u;
+  int target_sdk_version;
+};
+
+std::optional<ApkInfo> holder;
+
+ApkInfo& get_apk_info() {
+  [[maybe_unused]] static auto once = [] {
+    Java_ApkInfo_nativeReadyForFields(AttachCurrentThread());
+    return std::monostate();
+  }();
+  // holder should be initialized as the java is supposed to call the native
+  // method FillFields which will initialize the fields within the holder.
+  DCHECK(holder.has_value());
+  return *holder;
+}
+
+}  // namespace
+
+static void JNI_ApkInfo_FillFields(
+    JNIEnv* env,
+    const jni_zero::JavaParamRef<jstring>& hostPackageName,
+    const jni_zero::JavaParamRef<jstring>& hostVersionCode,
+    const jni_zero::JavaParamRef<jstring>& hostPackageLabel,
+    const jni_zero::JavaParamRef<jstring>& packageVersionCode,
+    const jni_zero::JavaParamRef<jstring>& packageVersionName,
+    const jni_zero::JavaParamRef<jstring>& packageName,
+    const jni_zero::JavaParamRef<jstring>& resourcesVersion,
+    const jni_zero::JavaParamRef<jstring>& installerPackageName,
+    jboolean isDebugApp,
+    jboolean targetsAtleastU,
+    jint targetSdkVersion) {
+  DCHECK(!holder.has_value());
+  auto java_string_to_const_char =
+      [](const jni_zero::JavaParamRef<jstring>& str) {
+        return UNSAFE_TODO(strdup(ConvertJavaStringToUTF8(str).c_str()));
+      };
+  holder = ApkInfo{
+      .host_package_name = java_string_to_const_char(hostPackageName),
+      .host_version_code = java_string_to_const_char(hostVersionCode),
+      .host_package_label = java_string_to_const_char(hostPackageLabel),
+      .package_version_code = java_string_to_const_char(packageVersionCode),
+      .package_version_name = java_string_to_const_char(packageVersionName),
+      .package_name = java_string_to_const_char(packageName),
+      .resources_version = java_string_to_const_char(resourcesVersion),
+      .installer_package_name = java_string_to_const_char(installerPackageName),
+      .is_debug_app = static_cast<bool>(isDebugApp),
+      .targets_at_least_u = static_cast<bool>(targetsAtleastU),
+      .target_sdk_version = targetSdkVersion};
+}
+
+const char* host_package_name() {
+  return get_apk_info().host_package_name;
+}
+
+const char* host_version_code() {
+  return get_apk_info().host_version_code;
+}
+
+const char* host_package_label() {
+  return get_apk_info().host_package_label;
+}
+
+const char* package_version_code() {
+  return get_apk_info().package_version_code;
+}
+
+const char* package_version_name() {
+  return get_apk_info().package_version_name;
+}
+
+const char* package_name() {
+  return get_apk_info().package_name;
+}
+
+const char* resources_version() {
+  return get_apk_info().resources_version;
+}
+
+const char* installer_package_name() {
+  return get_apk_info().installer_package_name;
+}
+
+bool is_debug_app() {
+  return get_apk_info().is_debug_app;
+}
+
+int target_sdk_version() {
+  return get_apk_info().target_sdk_version;
+}
+
+bool targets_at_least_u() {
+  return get_apk_info().targets_at_least_u;
+}
+}  // namespace base::android::apk_info
diff --git a/tot/base/android/apk_info.h b/tot/base/android/apk_info.h
new file mode 100644
index 0000000..6bba04d
--- /dev/null
+++ b/tot/base/android/apk_info.h
@@ -0,0 +1,43 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_ANDROID_APK_INFO_H_
+#define BASE_ANDROID_APK_INFO_H_
+
+namespace base::android::apk_info {
+// The package name of the host app which has loaded WebView, retrieved from
+// the application context. In the context of the SDK Runtime, the package
+// name of the app that owns this particular instance of the SDK Runtime will
+// also be included. e.g.
+// com.google.android.sdksandbox:com:com.example.myappwithads
+const char* host_package_name();
+
+// The application name (e.g. "Chrome"). For WebView, this is name of the
+// embedding app. In the context of the SDK Runtime, this is the name of the
+// app that owns this particular instance of the SDK Runtime.
+const char* host_version_code();
+
+// By default: same as versionCode. For WebView: versionCode of the embedding
+// app. In the context of the SDK Runtime, this is the versionCode of the app
+// that owns this particular instance of the SDK Runtime.
+const char* host_package_label();
+
+const char* package_version_code();
+
+const char* package_version_name();
+
+const char* package_name();
+
+const char* resources_version();
+
+const char* installer_package_name();
+
+bool is_debug_app();
+
+int target_sdk_version();
+
+bool targets_at_least_u();
+
+}  // namespace base::android::apk_info
+#endif  // BASE_ANDROID_APK_INFO_H_
diff --git a/tot/base/android/application_status_listener.cc b/tot/base/android/application_status_listener.cc
index af943a5..eb922c2 100644
--- a/tot/base/android/application_status_listener.cc
+++ b/tot/base/android/application_status_listener.cc
@@ -66,8 +66,9 @@
   }
 
   void Notify(ApplicationState state) override {
-    if (callback_)
+    if (callback_) {
       callback_.Run(state);
+    }
   }
 
  private:
@@ -113,9 +114,8 @@
       Java_ApplicationStatus_getStateForApplication(AttachCurrentThread()));
 }
 
-static void JNI_ApplicationStatus_OnApplicationStateChange(
-    JNIEnv* env,
-    jint new_state) {
+static void JNI_ApplicationStatus_OnApplicationStateChange(JNIEnv* env,
+                                                           jint new_state) {
   ApplicationState application_state = static_cast<ApplicationState>(new_state);
   ApplicationStatusListener::NotifyApplicationStateChange(application_state);
 }
diff --git a/tot/base/android/application_status_listener.h b/tot/base/android/application_status_listener.h
index dbbc36b..51f3837 100644
--- a/tot/base/android/application_status_listener.h
+++ b/tot/base/android/application_status_listener.h
@@ -6,6 +6,7 @@
 #define BASE_ANDROID_APPLICATION_STATUS_LISTENER_H_
 
 #include <jni.h>
+
 #include <memory>
 
 #include "base/android/jni_android.h"
diff --git a/tot/base/android/base_feature_map.cc b/tot/base/android/base_feature_map.cc
index fd261ac..bfda99e 100644
--- a/tot/base/android/base_feature_map.cc
+++ b/tot/base/android/base_feature_map.cc
@@ -22,8 +22,8 @@
 
 // static
 base::android::FeatureMap* GetFeatureMap() {
-  static base::NoDestructor<base::android::FeatureMap> kFeatureMap(std::vector(
-      std::begin(kFeaturesExposedToJava), std::end(kFeaturesExposedToJava)));
+  static base::NoDestructor<base::android::FeatureMap> kFeatureMap(
+      kFeaturesExposedToJava);
   return kFeatureMap.get();
 }
 
diff --git a/tot/base/android/build_info.cc b/tot/base/android/build_info.cc
index 22d36c3..6d6ba20 100644
--- a/tot/base/android/build_info.cc
+++ b/tot/base/android/build_info.cc
@@ -6,6 +6,9 @@
 
 #include <string>
 
+#include "base/android/android_info.h"
+#include "base/android/apk_info.h"
+#include "base/android/device_info.h"
 #include "base/android/jni_android.h"
 #include "base/android/jni_array.h"
 #include "base/android/jni_string.h"
@@ -16,35 +19,13 @@
 #include "base/strings/string_number_conversions.h"
 
 // Must come after all headers that specialize FromJniType() / ToJniType().
-#include "base/base_jni/BuildInfo_jni.h"
+#include "base/build_info_jni/BuildInfo_jni.h"
 
 namespace base {
 namespace android {
 
-namespace {
-
-// We are leaking these strings.
-const char* StrDupParam(const std::vector<std::string>& params, size_t index) {
-  return strdup(params[index].c_str());
-}
-
-int GetIntParam(const std::vector<std::string>& params, size_t index) {
-  int ret = 0;
-  bool success = StringToInt(params[index], &ret);
-  DCHECK(success);
-  return ret;
-}
-
-}  // namespace
-
 struct BuildInfoSingletonTraits {
-  static BuildInfo* New() {
-    JNIEnv* env = AttachCurrentThread();
-    ScopedJavaLocalRef<jobjectArray> params_objs = Java_BuildInfo_getAll(env);
-    std::vector<std::string> params;
-    AppendJavaStringArrayToStringVector(env, params_objs, &params);
-    return new BuildInfo(params);
-  }
+  static BuildInfo* New() { return new BuildInfo(); }
 
   static void Delete(BuildInfo* x) {
     // We're leaking this type, see kRegisterAtExit.
@@ -57,62 +38,60 @@
 #endif
 };
 
-BuildInfo::BuildInfo(const std::vector<std::string>& params)
-    : brand_(StrDupParam(params, 0)),
-      device_(StrDupParam(params, 1)),
-      android_build_id_(StrDupParam(params, 2)),
-      manufacturer_(StrDupParam(params, 3)),
-      model_(StrDupParam(params, 4)),
-      sdk_int_(GetIntParam(params, 5)),
-      build_type_(StrDupParam(params, 6)),
-      board_(StrDupParam(params, 7)),
-      host_package_name_(StrDupParam(params, 8)),
-      host_version_code_(StrDupParam(params, 9)),
-      host_package_label_(StrDupParam(params, 10)),
-      package_name_(StrDupParam(params, 11)),
-      package_version_code_(StrDupParam(params, 12)),
-      package_version_name_(StrDupParam(params, 13)),
-      android_build_fp_(StrDupParam(params, 14)),
-      gms_version_code_(StrDupParam(params, 15)),
-      installer_package_name_(StrDupParam(params, 16)),
-      abi_name_(StrDupParam(params, 17)),
-      custom_themes_(StrDupParam(params, 18)),
-      resources_version_(StrDupParam(params, 19)),
-      target_sdk_version_(GetIntParam(params, 20)),
-      is_debug_android_(GetIntParam(params, 21)),
-      is_tv_(GetIntParam(params, 22)),
-      version_incremental_(StrDupParam(params, 23)),
-      hardware_(StrDupParam(params, 24)),
-      is_at_least_t_(GetIntParam(params, 25)),
-      is_automotive_(GetIntParam(params, 26)),
-      is_at_least_u_(GetIntParam(params, 27)),
-      targets_at_least_u_(GetIntParam(params, 28)),
-      codename_(StrDupParam(params, 29)),
-      vulkan_deqp_level_(GetIntParam(params, 30)),
-      is_foldable_(GetIntParam(params, 31)),
-      soc_manufacturer_(StrDupParam(params, 32)),
-      is_debug_app_(GetIntParam(params, 33)),
-      is_desktop_(GetIntParam(params, 34)) {}
+BuildInfo::BuildInfo()
+    : brand_(android_info::brand()),
+      device_(android_info::device()),
+      android_build_id_(android_info::android_build_id()),
+      manufacturer_(android_info::manufacturer()),
+      model_(android_info::model()),
+      sdk_int_(android_info::sdk_int()),
+      build_type_(android_info::build_type()),
+      board_(android_info::board()),
+      host_package_name_(apk_info::host_package_name()),
+      host_version_code_(apk_info::host_version_code()),
+      host_package_label_(apk_info::host_package_label()),
+      package_name_(apk_info::package_name()),
+      package_version_code_(apk_info::package_version_code()),
+      package_version_name_(apk_info::package_version_name()),
+      android_build_fp_(android_info::android_build_fp()),
+      installer_package_name_(apk_info::installer_package_name()),
+      abi_name_(android_info::abi_name()),
+      resources_version_(apk_info::resources_version()),
+      target_sdk_version_(apk_info::target_sdk_version()),
+      is_debug_android_(android_info::is_debug_android()),
+      is_tv_(device_info::is_tv()),
+      version_incremental_(android_info::version_incremental()),
+      hardware_(android_info::hardware()),
+      is_at_least_t_(android_info::is_at_least_t()),
+      is_automotive_(device_info::is_automotive()),
+      is_at_least_u_(android_info::is_at_least_u()),
+      targets_at_least_u_(apk_info::targets_at_least_u()),
+      codename_(android_info::codename()),
+      vulkan_deqp_level_(device_info::vulkan_deqp_level()),
+      is_foldable_(device_info::is_foldable()),
+      soc_manufacturer_(android_info::soc_manufacturer()),
+      is_debug_app_(apk_info::is_debug_app()),
+      is_desktop_(device_info::is_desktop()) {}
 
 BuildInfo::~BuildInfo() = default;
 
+const char* BuildInfo::gms_version_code() const {
+  return device_info::gms_version_code();
+}
+
 void BuildInfo::set_gms_version_code_for_test(
     const std::string& gms_version_code) {
-  // This leaks the string, just like production code.
-  gms_version_code_ = strdup(gms_version_code.c_str());
-  Java_BuildInfo_setGmsVersionCodeForTest(AttachCurrentThread(),
-                                          gms_version_code);
+  device_info::set_gms_version_code_for_test(gms_version_code);
 }
 
 std::string BuildInfo::host_signing_cert_sha256() {
   JNIEnv* env = AttachCurrentThread();
-  return base::android::ConvertJavaStringToUTF8(
-      env, Java_BuildInfo_lazyGetHostSigningCertSha256(env));
+  return Java_BuildInfo_lazyGetHostSigningCertSha256(env);
 }
 
 // static
 BuildInfo* BuildInfo::GetInstance() {
-  return Singleton<BuildInfo, BuildInfoSingletonTraits >::get();
+  return Singleton<BuildInfo, BuildInfoSingletonTraits>::get();
 }
 
 }  // namespace android
diff --git a/tot/base/android/build_info.h b/tot/base/android/build_info.h
index cf72b30..93ab210 100644
--- a/tot/base/android/build_info.h
+++ b/tot/base/android/build_info.h
@@ -10,36 +10,42 @@
 #include <string>
 #include <vector>
 
+#include "base/android/android_info.h"
 #include "base/base_export.h"
 #include "base/memory/singleton.h"
 
 namespace base::android {
 
+// DEPRECATED: Please use android_info::SdkVersion.
+//
 // This enumeration maps to the values returned by BuildInfo::sdk_int(),
 // indicating the Android release associated with a given SDK version.
 enum SdkVersion {
-  SDK_VERSION_JELLY_BEAN = 16,
-  SDK_VERSION_JELLY_BEAN_MR1 = 17,
-  SDK_VERSION_JELLY_BEAN_MR2 = 18,
-  SDK_VERSION_KITKAT = 19,
-  SDK_VERSION_KITKAT_WEAR = 20,
-  SDK_VERSION_LOLLIPOP = 21,
-  SDK_VERSION_LOLLIPOP_MR1 = 22,
-  SDK_VERSION_MARSHMALLOW = 23,
-  SDK_VERSION_NOUGAT = 24,
-  SDK_VERSION_NOUGAT_MR1 = 25,
-  SDK_VERSION_OREO = 26,
-  SDK_VERSION_O_MR1 = 27,
-  SDK_VERSION_P = 28,
-  SDK_VERSION_Q = 29,
-  SDK_VERSION_R = 30,
-  SDK_VERSION_S = 31,
-  SDK_VERSION_Sv2 = 32,
-  SDK_VERSION_T = 33,
-  SDK_VERSION_U = 34,
-  SDK_VERSION_V = 35,
+  SDK_VERSION_JELLY_BEAN = android_info::SDK_VERSION_JELLY_BEAN,
+  SDK_VERSION_JELLY_BEAN_MR1 = android_info::SDK_VERSION_JELLY_BEAN_MR1,
+  SDK_VERSION_JELLY_BEAN_MR2 = android_info::SDK_VERSION_JELLY_BEAN_MR2,
+  SDK_VERSION_KITKAT = android_info::SDK_VERSION_KITKAT,
+  SDK_VERSION_KITKAT_WEAR = android_info::SDK_VERSION_KITKAT_WEAR,
+  SDK_VERSION_LOLLIPOP = android_info::SDK_VERSION_LOLLIPOP,
+  SDK_VERSION_LOLLIPOP_MR1 = android_info::SDK_VERSION_LOLLIPOP_MR1,
+  SDK_VERSION_MARSHMALLOW = android_info::SDK_VERSION_MARSHMALLOW,
+  SDK_VERSION_NOUGAT = android_info::SDK_VERSION_NOUGAT,
+  SDK_VERSION_NOUGAT_MR1 = android_info::SDK_VERSION_NOUGAT_MR1,
+  SDK_VERSION_OREO = android_info::SDK_VERSION_OREO,
+  SDK_VERSION_O_MR1 = android_info::SDK_VERSION_O_MR1,
+  SDK_VERSION_P = android_info::SDK_VERSION_P,
+  SDK_VERSION_Q = android_info::SDK_VERSION_Q,
+  SDK_VERSION_R = android_info::SDK_VERSION_R,
+  SDK_VERSION_S = android_info::SDK_VERSION_S,
+  SDK_VERSION_Sv2 = android_info::SDK_VERSION_Sv2,
+  SDK_VERSION_T = android_info::SDK_VERSION_T,
+  SDK_VERSION_U = android_info::SDK_VERSION_U,
+  SDK_VERSION_V = android_info::SDK_VERSION_V,
 };
 
+// DEPRECATED: Use AndroidInfo, DeviceInfo or ApkInfo instead.
+// These are more efficient because they only retrieve the data being queried.
+//
 // BuildInfo is a singleton class that stores android build and device
 // information. It will be called from Android specific code and gets used
 // primarily in crash reporting.
@@ -60,33 +66,19 @@
   // available even if the process is in a crash state. Sadly
   // std::string.c_str() doesn't guarantee that memory won't be allocated when
   // it is called.
-  const char* device() const {
-    return device_;
-  }
+  const char* device() const { return device_; }
 
-  const char* manufacturer() const {
-    return manufacturer_;
-  }
+  const char* manufacturer() const { return manufacturer_; }
 
-  const char* model() const {
-    return model_;
-  }
+  const char* model() const { return model_; }
 
-  const char* brand() const {
-    return brand_;
-  }
+  const char* brand() const { return brand_; }
 
-  const char* android_build_id() const {
-    return android_build_id_;
-  }
+  const char* android_build_id() const { return android_build_id_; }
 
-  const char* android_build_fp() const {
-    return android_build_fp_;
-  }
+  const char* android_build_fp() const { return android_build_fp_; }
 
-  const char* gms_version_code() const {
-    return gms_version_code_;
-  }
+  const char* gms_version_code() const;
 
   void set_gms_version_code_for_test(const std::string& gms_version_code);
 
@@ -111,25 +103,15 @@
   // This will default to an empty string if we were unable to retrieve it.
   std::string host_signing_cert_sha256();
 
-  const char* package_version_code() const {
-    return package_version_code_;
-  }
+  const char* package_version_code() const { return package_version_code_; }
 
-  const char* package_version_name() const {
-    return package_version_name_;
-  }
+  const char* package_version_name() const { return package_version_name_; }
 
-  const char* package_name() const {
-    return package_name_;
-  }
-
-  const char* custom_themes() const { return custom_themes_; }
+  const char* package_name() const { return package_name_; }
 
   const char* resources_version() const { return resources_version_; }
 
-  const char* build_type() const {
-    return build_type_;
-  }
+  const char* build_type() const { return build_type_; }
 
   const char* board() const { return board_; }
 
@@ -137,9 +119,7 @@
 
   const char* abi_name() const { return abi_name_; }
 
-  int sdk_int() const {
-    return sdk_int_;
-  }
+  int sdk_int() const { return sdk_int_; }
 
   // Returns the targetSdkVersion of the currently running app. If called from a
   // library, this returns the embedding app's targetSdkVersion.
@@ -182,7 +162,7 @@
  private:
   friend struct BuildInfoSingletonTraits;
 
-  explicit BuildInfo(const std::vector<std::string>& params);
+  explicit BuildInfo();
 
   // Const char* is used instead of std::strings because these values must be
   // available even if the process is in a crash state. Sadly
@@ -203,11 +183,8 @@
   const char* const package_version_code_;
   const char* const package_version_name_;
   const char* const android_build_fp_;
-  // Can be overridden in tests.
-  const char* gms_version_code_ = nullptr;
   const char* const installer_package_name_;
   const char* const abi_name_;
-  const char* const custom_themes_;
   const char* const resources_version_;
   // Not needed by breakpad.
   const int target_sdk_version_;
diff --git a/tot/base/android/bundle_utils.cc b/tot/base/android/bundle_utils.cc
index 0efd0f3..f77fe7a 100644
--- a/tot/base/android/bundle_utils.cc
+++ b/tot/base/android/bundle_utils.cc
@@ -55,19 +55,12 @@
 std::string BundleUtils::ResolveLibraryPath(const std::string& library_name,
                                             const std::string& split_name) {
   JNIEnv* env = AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> java_path = Java_BundleUtils_getNativeLibraryPath(
-      env, ConvertUTF8ToJavaString(env, library_name),
-      ConvertUTF8ToJavaString(env, split_name));
-  // TODO(crbug.com/40656179): Remove this tolerance.
-  if (!java_path) {
-    return std::string();
-  }
-  return ConvertJavaStringToUTF8(env, java_path);
+  return Java_BundleUtils_getNativeLibraryPath(env, library_name, split_name);
 }
 
 // static
 bool BundleUtils::IsBundle() {
-  return Java_BundleUtils_isBundleForNative(AttachCurrentThread());
+  return Java_BundleUtils_isBundle(AttachCurrentThread());
 }
 
 // static
diff --git a/tot/base/android/callback_android.cc b/tot/base/android/callback_android.cc
index 8b0b6e5..220f979 100644
--- a/tot/base/android/callback_android.cc
+++ b/tot/base/android/callback_android.cc
@@ -10,13 +10,9 @@
 #include "base/android/scoped_java_ref.h"
 #include "base/time/time.h"
 #include "base/types/optional_ref.h"
-#include "build/robolectric_buildflags.h"
 
-#if BUILDFLAG(IS_ROBOLECTRIC)
-#include "base/base_robolectric_jni/Callback_jni.h"  // nogncheck
-#else
+// Must come after all headers that specialize FromJniType() / ToJniType().
 #include "base/callback_jni/Callback_jni.h"
-#endif
 
 namespace base {
 namespace android {
diff --git a/tot/base/android/command_line_android.cc b/tot/base/android/command_line_android.cc
index eded1cb..bb93f95 100644
--- a/tot/base/android/command_line_android.cc
+++ b/tot/base/android/command_line_android.cc
@@ -5,24 +5,20 @@
 #include "base/command_line.h"
 
 #include "base/android/jni_string.h"
-#include "build/robolectric_buildflags.h"
 
 // Must come after all headers that specialize FromJniType() / ToJniType().
-#if BUILDFLAG(IS_ROBOLECTRIC)
-#include "base/base_robolectric_jni/CommandLine_jni.h"  // nogncheck
-#else
 #include "base/command_line_jni/CommandLine_jni.h"
-#endif
 
+using base::CommandLine;
 using base::android::JavaParamRef;
 using base::android::ScopedJavaLocalRef;
-using base::CommandLine;
 
 namespace {
 
 void AppendToCommandLine(std::vector<std::string>& vec, bool includes_program) {
-  if (!includes_program)
+  if (!includes_program) {
     vec.insert(vec.begin(), std::string());
+  }
   CommandLine extra_command_line(vec);
   CommandLine::ForCurrentProcess()->AppendArguments(extra_command_line,
                                                     includes_program);
@@ -40,21 +36,8 @@
   return CommandLine::ForCurrentProcess()->GetSwitchValueNative(switch_string);
 }
 
-static std::vector<std::string> JNI_CommandLine_GetSwitchesFlattened(
-    JNIEnv* env) {
-  // JNI doesn't support returning Maps. Instead, express this map as a 1
-  // dimensional array: [ key1, value1, key2, value2, ... ]
-  std::vector<std::string> keys_and_values;
-  for (const auto& entry : CommandLine::ForCurrentProcess()->GetSwitches()) {
-    keys_and_values.push_back(entry.first);
-    keys_and_values.push_back(entry.second);
-  }
-  return keys_and_values;
-}
-
-static void JNI_CommandLine_AppendSwitch(JNIEnv* env,
-                                         std::string& switch_string) {
-  CommandLine::ForCurrentProcess()->AppendSwitch(switch_string);
+static CommandLine::SwitchMap JNI_CommandLine_GetSwitches(JNIEnv* env) {
+  return CommandLine::ForCurrentProcess()->GetSwitches();
 }
 
 static void JNI_CommandLine_AppendSwitchWithValue(JNIEnv* env,
diff --git a/tot/base/android/content_uri_utils.cc b/tot/base/android/content_uri_utils.cc
index 8bdb7f9..be84f86 100644
--- a/tot/base/android/content_uri_utils.cc
+++ b/tot/base/android/content_uri_utils.cc
@@ -22,15 +22,6 @@
 using base::android::ScopedJavaLocalRef;
 
 namespace base {
-namespace {
-std::string SafeConvertJavaStringToUTF8(JNIEnv* env,
-                                        const JavaRef<jstring>& str) {
-  if (str.is_null()) {
-    return std::string();
-  }
-  return base::android::ConvertJavaStringToUTF8(env, str);
-}
-}  // namespace
 
 namespace internal {
 
@@ -114,33 +105,30 @@
 
 }  // namespace internal
 
-void JNI_ContentUriUtils_AddFileInfoToVector(
-    JNIEnv* env,
-    jlong vector_pointer,
-    const JavaParamRef<jstring>& uri,
-    const JavaParamRef<jstring>& display_name,
-    jboolean is_directory,
-    jlong size,
-    jlong last_modified) {
+void JNI_ContentUriUtils_AddFileInfoToVector(JNIEnv* env,
+                                             jlong vector_pointer,
+                                             std::string& uri,
+                                             std::string& display_name,
+                                             jboolean is_directory,
+                                             jlong size,
+                                             jlong last_modified) {
   auto* result =
       reinterpret_cast<std::vector<FileEnumerator::FileInfo>*>(vector_pointer);
-  result->emplace_back(FilePath(SafeConvertJavaStringToUTF8(env, uri)),
-                       FilePath(SafeConvertJavaStringToUTF8(env, display_name)),
-                       is_directory, size,
+  result->emplace_back(FilePath(uri), FilePath(display_name), is_directory,
+                       size,
                        Time::FromMillisecondsSinceUnixEpoch(last_modified));
 }
 
 std::string GetContentUriMimeType(const FilePath& content_uri) {
   JNIEnv* env = android::AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> j_mime =
-      Java_ContentUriUtils_getMimeType(env, content_uri.value());
-  return SafeConvertJavaStringToUTF8(env, j_mime);
+  return Java_ContentUriUtils_getMimeType(env, content_uri.value());
 }
 
 bool MaybeGetFileDisplayName(const FilePath& content_uri,
                              std::u16string* file_display_name) {
-  if (!content_uri.IsContentUri())
+  if (!content_uri.IsContentUri()) {
     return false;
+  }
 
   DCHECK(file_display_name);
 
@@ -148,8 +136,9 @@
   ScopedJavaLocalRef<jstring> j_display_name =
       Java_ContentUriUtils_maybeGetDisplayName(env, content_uri.value());
 
-  if (j_display_name.is_null())
+  if (j_display_name.is_null()) {
     return false;
+  }
 
   *file_display_name = android::ConvertJavaStringToUTF16(j_display_name);
   return true;
@@ -159,10 +148,9 @@
     const FilePath& tree_uri,
     const std::string& encoded_document_id) {
   JNIEnv* env = android::AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> j_uri =
-      Java_ContentUriUtils_buildDocumentUriUsingTree(env, tree_uri.value(),
-                                                     encoded_document_id);
-  return FilePath(SafeConvertJavaStringToUTF8(env, j_uri));
+  std::string j_uri = Java_ContentUriUtils_buildDocumentUriUsingTree(
+      env, tree_uri.value(), encoded_document_id);
+  return FilePath(j_uri);
 }
 
 FilePath ContentUriGetChildDocumentOrQuery(const FilePath& parent,
@@ -171,10 +159,9 @@
                                            bool is_directory,
                                            bool create) {
   JNIEnv* env = android::AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> j_uri =
-      Java_ContentUriUtils_getChildDocumentOrQuery(
-          env, parent.value(), display_name, mime_type, is_directory, create);
-  return FilePath(SafeConvertJavaStringToUTF8(env, j_uri));
+  std::string j_uri = Java_ContentUriUtils_getChildDocumentOrQuery(
+      env, parent.value(), display_name, mime_type, is_directory, create);
+  return FilePath(j_uri);
 }
 
 bool ContentUriIsCreateChildDocumentQuery(const FilePath& content_uri) {
@@ -186,9 +173,9 @@
 FilePath ContentUriGetDocumentFromQuery(const FilePath& content_uri,
                                         bool create) {
   JNIEnv* env = android::AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> j_uri = Java_ContentUriUtils_getDocumentFromQuery(
+  std::string j_uri = Java_ContentUriUtils_getDocumentFromQuery(
       env, content_uri.value(), create);
-  return FilePath(SafeConvertJavaStringToUTF8(env, j_uri));
+  return FilePath(j_uri);
 }
 
 }  // namespace base
diff --git a/tot/base/android/content_uri_utils_unittest.cc b/tot/base/android/content_uri_utils_unittest.cc
index 042f7df..bfa3628 100644
--- a/tot/base/android/content_uri_utils_unittest.cc
+++ b/tot/base/android/content_uri_utils_unittest.cc
@@ -94,11 +94,17 @@
       *test::android::GetContentUriFromCacheDirFilePath(file);
   FilePath content_uri_dir =
       *test::android::GetContentUriFromCacheDirFilePath(dir);
+  FilePath content_uri_document =
+      *test::android::GetInMemoryContentDocumentUriFromCacheDirFilePath(file);
+  FilePath content_uri_tree =
+      *test::android::GetInMemoryContentTreeUriFromCacheDirDirectory(dir);
   FilePath content_uri_not_exists =
       *test::android::GetContentUriFromCacheDirFilePath(not_exists);
 
   EXPECT_TRUE(PathExists(content_uri_file));
   EXPECT_TRUE(PathExists(content_uri_dir));
+  EXPECT_TRUE(PathExists(content_uri_document));
+  EXPECT_TRUE(PathExists(content_uri_tree));
   EXPECT_FALSE(PathExists(content_uri_not_exists));
 
   File::Info info;
@@ -109,7 +115,18 @@
   EXPECT_FALSE(content_uri_info.is_directory);
   EXPECT_EQ(content_uri_info.last_modified, info.last_modified);
 
+  EXPECT_TRUE(GetFileInfo(content_uri_document, &content_uri_info));
+  EXPECT_FALSE(content_uri_info.is_directory);
+  // Java DocumentProvider only does resolution to seconds.
+  EXPECT_EQ(content_uri_info.last_modified.ToTimeT(),
+            info.last_modified.ToTimeT());
+
   EXPECT_TRUE(GetFileInfo(dir, &info));
+  EXPECT_TRUE(GetFileInfo(content_uri_tree, &content_uri_info));
+  EXPECT_TRUE(content_uri_info.is_directory);
+  EXPECT_EQ(content_uri_info.last_modified.ToTimeT(),
+            info.last_modified.ToTimeT());
+
   EXPECT_TRUE(GetFileInfo(content_uri_dir, &content_uri_info));
   EXPECT_TRUE(content_uri_info.is_directory);
   EXPECT_EQ(content_uri_info.last_modified, info.last_modified);
diff --git a/tot/base/android/device_info.cc b/tot/base/android/device_info.cc
new file mode 100644
index 0000000..645226c
--- /dev/null
+++ b/tot/base/android/device_info.cc
@@ -0,0 +1,103 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/android/device_info.h"
+
+#include <string>
+
+#include "base/android/jni_android.h"
+#include "base/android/jni_array.h"
+#include "base/android/jni_string.h"
+#include "base/android/scoped_java_ref.h"
+#include "base/compiler_specific.h"
+#include "base/strings/string_number_conversions.h"
+
+// Must come after all headers that specialize FromJniType() / ToJniType().
+#include "base/build_info_jni/DeviceInfo_jni.h"
+#include "base/synchronization/lock.h"
+
+namespace base::android::device_info {
+namespace {
+struct DeviceInfo {
+  // Const char* is used instead of std::strings because these values must be
+  // available even if the process is in a crash state. Sadly
+  // std::string.c_str() doesn't guarantee that memory won't be allocated when
+  // it is called.
+  const char* gms_version_code;
+  bool is_tv;
+  bool is_automotive;
+  bool is_foldable;
+  bool is_desktop;
+  // Available only on Android T+.
+  int32_t vulkan_deqp_level;
+};
+
+std::optional<DeviceInfo> holder;
+
+DeviceInfo& get_device_info() {
+  [[maybe_unused]] static auto once = [] {
+    Java_DeviceInfo_nativeReadyForFields(AttachCurrentThread());
+    return std::monostate();
+  }();
+  // holder should be initialized as the java is supposed to call the native
+  // method FillFields which will initialize the fields within the holder.
+  DCHECK(holder.has_value());
+  return *holder;
+}
+
+}  // namespace
+
+static void JNI_DeviceInfo_FillFields(
+    JNIEnv* env,
+    const jni_zero::JavaParamRef<jstring>& gmsVersionCode,
+    jboolean isTV,
+    jboolean isAutomotive,
+    jboolean isFoldable,
+    jboolean isDesktop,
+    jint vulkanDeqpLevel) {
+  DCHECK(!holder.has_value());
+  auto java_string_to_const_char =
+      [](const jni_zero::JavaParamRef<jstring>& str) {
+        return UNSAFE_TODO(strdup(ConvertJavaStringToUTF8(str).c_str()));
+      };
+  holder =
+      DeviceInfo{.gms_version_code = java_string_to_const_char(gmsVersionCode),
+                 .is_tv = static_cast<bool>(isTV),
+                 .is_automotive = static_cast<bool>(isAutomotive),
+                 .is_foldable = static_cast<bool>(isFoldable),
+                 .is_desktop = static_cast<bool>(isDesktop),
+                 .vulkan_deqp_level = vulkanDeqpLevel};
+}
+
+const char* gms_version_code() {
+  return get_device_info().gms_version_code;
+}
+
+void set_gms_version_code_for_test(const std::string& gms_version_code) {
+  get_device_info().gms_version_code =
+      UNSAFE_TODO(strdup(gms_version_code.c_str()));
+  Java_DeviceInfo_setGmsVersionCodeForTest(AttachCurrentThread(),
+                                           gms_version_code);
+}
+
+bool is_tv() {
+  return get_device_info().is_tv;
+}
+bool is_automotive() {
+  return get_device_info().is_automotive;
+}
+bool is_foldable() {
+  return get_device_info().is_foldable;
+}
+
+bool is_desktop() {
+  return get_device_info().is_desktop;
+}
+
+// Available only on Android T+.
+int32_t vulkan_deqp_level() {
+  return get_device_info().vulkan_deqp_level;
+}
+
+}  // namespace base::android::device_info
diff --git a/tot/base/android/device_info.h b/tot/base/android/device_info.h
new file mode 100644
index 0000000..ccf2f46
--- /dev/null
+++ b/tot/base/android/device_info.h
@@ -0,0 +1,24 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_ANDROID_DEVICE_INFO_H_
+#define BASE_ANDROID_DEVICE_INFO_H_
+
+#include <string>
+
+namespace base::android::device_info {
+const char* gms_version_code();
+
+void set_gms_version_code_for_test(const std::string& gms_version_code);
+
+bool is_tv();
+bool is_automotive();
+bool is_foldable();
+bool is_desktop();
+// Available only on Android T+.
+int32_t vulkan_deqp_level();
+
+}  // namespace base::android::device_info
+
+#endif  // BASE_ANDROID_DEVICE_INFO_H_
diff --git a/tot/base/android/early_trace_event_binding.cc b/tot/base/android/early_trace_event_binding.cc
index 280e0e2..66fce41 100644
--- a/tot/base/android/early_trace_event_binding.cc
+++ b/tot/base/android/early_trace_event_binding.cc
@@ -18,41 +18,35 @@
 namespace base {
 namespace android {
 
-static void JNI_EarlyTraceEvent_RecordEarlyBeginEvent(
-    JNIEnv* env,
-    const JavaParamRef<jstring>& jname,
-    jlong time_ns,
-    jint thread_id,
-    jlong thread_time_ms) {
+static void JNI_EarlyTraceEvent_RecordEarlyBeginEvent(JNIEnv* env,
+                                                      std::string& name,
+                                                      jlong time_ns,
+                                                      jint thread_id,
+                                                      jlong thread_time_ms) {
 #if BUILDFLAG(ENABLE_BASE_TRACING)
-  std::string name = ConvertJavaStringToUTF8(env, jname);
-
   static const unsigned char* category_group_enabled =
       TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(internal::kJavaTraceCategory);
   trace_event_internal::AddTraceEventWithThreadIdAndTimestamps(
       TRACE_EVENT_PHASE_BEGIN, category_group_enabled, name.c_str(),
-      /*scope=*/nullptr, trace_event_internal::kNoId, thread_id,
-      TimeTicks::FromJavaNanoTime(time_ns),
+      /*scope=*/nullptr, trace_event_internal::kNoId,
+      PlatformThreadId(thread_id), TimeTicks::FromJavaNanoTime(time_ns),
       ThreadTicks() + Milliseconds(thread_time_ms),
       TRACE_EVENT_FLAG_JAVA_STRING_LITERALS | TRACE_EVENT_FLAG_COPY);
 #endif  // BUILDFLAG(ENABLE_BASE_TRACING)
 }
 
-static void JNI_EarlyTraceEvent_RecordEarlyEndEvent(
-    JNIEnv* env,
-    const JavaParamRef<jstring>& jname,
-    jlong time_ns,
-    jint thread_id,
-    jlong thread_time_ms) {
+static void JNI_EarlyTraceEvent_RecordEarlyEndEvent(JNIEnv* env,
+                                                    std::string& name,
+                                                    jlong time_ns,
+                                                    jint thread_id,
+                                                    jlong thread_time_ms) {
 #if BUILDFLAG(ENABLE_BASE_TRACING)
-  std::string name = ConvertJavaStringToUTF8(env, jname);
-
   static const unsigned char* category_group_enabled =
       TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(internal::kJavaTraceCategory);
   trace_event_internal::AddTraceEventWithThreadIdAndTimestamps(
       TRACE_EVENT_PHASE_END, category_group_enabled, name.c_str(),
-      /*scope=*/nullptr, trace_event_internal::kNoId, thread_id,
-      TimeTicks::FromJavaNanoTime(time_ns),
+      /*scope=*/nullptr, trace_event_internal::kNoId,
+      PlatformThreadId(thread_id), TimeTicks::FromJavaNanoTime(time_ns),
       ThreadTicks() + Milliseconds(thread_time_ms),
       TRACE_EVENT_FLAG_JAVA_STRING_LITERALS | TRACE_EVENT_FLAG_COPY);
 #endif  // BUILDFLAG(ENABLE_BASE_TRACING)
@@ -60,20 +54,18 @@
 
 static void JNI_EarlyTraceEvent_RecordEarlyToplevelBeginEvent(
     JNIEnv* env,
-    const JavaParamRef<jstring>& jname,
+    std::string& name,
     jlong time_ns,
     jint thread_id,
     jlong thread_time_ms) {
 #if BUILDFLAG(ENABLE_BASE_TRACING)
-  std::string name = ConvertJavaStringToUTF8(env, jname);
-
   static const unsigned char* category_group_enabled =
       TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
           internal::kToplevelTraceCategory);
   trace_event_internal::AddTraceEventWithThreadIdAndTimestamps(
       TRACE_EVENT_PHASE_BEGIN, category_group_enabled, name.c_str(),
-      /*scope=*/nullptr, trace_event_internal::kNoId, thread_id,
-      TimeTicks::FromJavaNanoTime(time_ns),
+      /*scope=*/nullptr, trace_event_internal::kNoId,
+      PlatformThreadId(thread_id), TimeTicks::FromJavaNanoTime(time_ns),
       ThreadTicks() + Milliseconds(thread_time_ms),
       TRACE_EVENT_FLAG_JAVA_STRING_LITERALS | TRACE_EVENT_FLAG_COPY);
 #endif  // BUILDFLAG(ENABLE_BASE_TRACING)
@@ -81,35 +73,31 @@
 
 static void JNI_EarlyTraceEvent_RecordEarlyToplevelEndEvent(
     JNIEnv* env,
-    const JavaParamRef<jstring>& jname,
+    std::string& name,
     jlong time_ns,
     jint thread_id,
     jlong thread_time_ms) {
 #if BUILDFLAG(ENABLE_BASE_TRACING)
-  std::string name = ConvertJavaStringToUTF8(env, jname);
-
   static const unsigned char* category_group_enabled =
       TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
           internal::kToplevelTraceCategory);
   trace_event_internal::AddTraceEventWithThreadIdAndTimestamps(
       TRACE_EVENT_PHASE_END, category_group_enabled, name.c_str(),
-      /*scope=*/nullptr, trace_event_internal::kNoId, thread_id,
-      TimeTicks::FromJavaNanoTime(time_ns),
+      /*scope=*/nullptr, trace_event_internal::kNoId,
+      PlatformThreadId(thread_id), TimeTicks::FromJavaNanoTime(time_ns),
       ThreadTicks() + Milliseconds(thread_time_ms),
       TRACE_EVENT_FLAG_JAVA_STRING_LITERALS | TRACE_EVENT_FLAG_COPY);
 #endif  // BUILDFLAG(ENABLE_BASE_TRACING)
 }
 
-static void JNI_EarlyTraceEvent_RecordEarlyAsyncBeginEvent(
-    JNIEnv* env,
-    const JavaParamRef<jstring>& jname,
-    jlong id,
-    jlong time_ns) {
+static void JNI_EarlyTraceEvent_RecordEarlyAsyncBeginEvent(JNIEnv* env,
+                                                           std::string& name,
+                                                           jlong id,
+                                                           jlong time_ns) {
   TRACE_EVENT_BEGIN(internal::kJavaTraceCategory, nullptr,
                     perfetto::Track(static_cast<uint64_t>(id)),
                     TimeTicks::FromJavaNanoTime(time_ns),
                     [&](::perfetto::EventContext& ctx) {
-                      std::string name = ConvertJavaStringToUTF8(env, jname);
                       ctx.event()->set_name(name.c_str());
                     });
 }
@@ -121,7 +109,7 @@
                   perfetto::Track(static_cast<uint64_t>(id)));
 }
 
-bool GetBackgroundStartupTracingFlag() {
+bool GetBackgroundStartupTracingFlagFromJava() {
   JNIEnv* env = jni_zero::AttachCurrentThread();
   return base::android::Java_EarlyTraceEvent_getBackgroundStartupTracingFlag(
       env);
diff --git a/tot/base/android/early_trace_event_binding.h b/tot/base/android/early_trace_event_binding.h
index f1e600e..527c53e 100644
--- a/tot/base/android/early_trace_event_binding.h
+++ b/tot/base/android/early_trace_event_binding.h
@@ -12,7 +12,7 @@
 
 // Returns true if background startup tracing flag was set on the previous
 // startup.
-BASE_EXPORT bool GetBackgroundStartupTracingFlag();
+BASE_EXPORT bool GetBackgroundStartupTracingFlagFromJava();
 
 // Sets a flag to chrome application preferences to enable startup tracing next
 // time the app is started.
diff --git a/tot/base/android/feature_map.cc b/tot/base/android/feature_map.cc
index 817fdcd..6fa02fd 100644
--- a/tot/base/android/feature_map.cc
+++ b/tot/base/android/feature_map.cc
@@ -24,7 +24,8 @@
   return std::make_pair(feature->name, feature);
 }
 
-FeatureMap::FeatureMap(std::vector<const Feature*> features_exposed_to_java) {
+FeatureMap::FeatureMap(
+    base::span<const Feature* const> features_exposed_to_java) {
   mapping_ =
       MakeFlatMap<std::string_view, raw_ptr<const Feature, CtnExperimental>>(
           features_exposed_to_java, {}, &MakeNameToFeaturePair);
diff --git a/tot/base/android/feature_map.h b/tot/base/android/feature_map.h
index c222002..684def5 100644
--- a/tot/base/android/feature_map.h
+++ b/tot/base/android/feature_map.h
@@ -9,6 +9,7 @@
 
 #include "base/base_export.h"
 #include "base/containers/flat_map.h"
+#include "base/containers/span.h"
 #include "base/feature_list.h"
 #include "base/memory/raw_ptr.h"
 
@@ -22,7 +23,8 @@
 // Each component should have its own FeatureMap.
 class BASE_EXPORT FeatureMap {
  public:
-  explicit FeatureMap(std::vector<const Feature*> featuresExposedToJava);
+  explicit FeatureMap(
+      base::span<const Feature* const> features_exposed_to_java);
   ~FeatureMap();
 
   // Map a |feature_name| to a Feature*.
diff --git a/tot/base/android/field_trial_list.cc b/tot/base/android/field_trial_list.cc
index 8e9149d..f50591d 100644
--- a/tot/base/android/field_trial_list.cc
+++ b/tot/base/android/field_trial_list.cc
@@ -34,8 +34,8 @@
     // Changes to format of the log message below must be accompanied by
     // changes to finch smoke tests since they look for this log message
     // in the logcat.
-    LOG(INFO) << "Active field trial \"" << trial_name
-              << "\" in group \"" << group_name<< '"';
+    LOG(INFO) << "Active field trial \"" << trial_name << "\" in group \""
+              << group_name << '"';
   }
 
  protected:
@@ -73,6 +73,8 @@
 // friend the JNI function and is, in turn, friended by
 // FieldTrialListIncludingLowAnonymity which allows for the private
 // GetActiveFieldTrialGroups() to be reached.
+static void JNI_FieldTrialList_LogActiveTrials(JNIEnv* env);
+
 class AndroidFieldTrialListLogActiveTrialsFriendHelper {
  private:
   friend void ::JNI_FieldTrialList_LogActiveTrials(JNIEnv* env);
@@ -89,7 +91,7 @@
 };
 
 static void JNI_FieldTrialList_LogActiveTrials(JNIEnv* env) {
-  DCHECK(!g_trial_logger.IsCreated()); // This need only be called once.
+  DCHECK(!g_trial_logger.IsCreated());  // This need only be called once.
 
   LOG(INFO) << "Logging active field trials...";
   AndroidFieldTrialListLogActiveTrialsFriendHelper::AddObserver(
@@ -110,3 +112,5 @@
   return base::FieldTrialList::CreateFieldTrial(trial_name, group_name) !=
          nullptr;
 }
+
+DEFINE_JNI_FOR_FieldTrialList()
diff --git a/tot/base/android/input_hint_checker.cc b/tot/base/android/input_hint_checker.cc
index 3c9dcb3..ff8ef6d 100644
--- a/tot/base/android/input_hint_checker.cc
+++ b/tot/base/android/input_hint_checker.cc
@@ -14,6 +14,7 @@
 #include "base/metrics/histogram_functions.h"
 #include "base/metrics/histogram_macros.h"
 #include "base/no_destructor.h"
+#include "base/rand_util.h"
 #include "base/time/time.h"
 
 // Must come after all headers that specialize FromJniType() / ToJniType().
@@ -41,13 +42,14 @@
 BASE_EXPORT
 BASE_FEATURE(kYieldWithInputHint,
              "YieldWithInputHint",
-             base::FEATURE_DISABLED_BY_DEFAULT);
+             base::FEATURE_ENABLED_BY_DEFAULT);
 
 // Min time delta between checks for the input hint. Must be a smaller than
 // time to produce a frame, but a bit longer than the time it takes to retrieve
 // the hint.
+// Note: Do not use the prepared macro as of no need for a local cache.
 const base::FeatureParam<int> kPollIntervalMillisParam{&kYieldWithInputHint,
-                                                       "poll_interval_ms", 3};
+                                                       "poll_interval_ms", 1};
 
 // Class calling a private method of InputHintChecker.
 // This allows not to declare the method called by pthread_create in the public
@@ -305,8 +307,11 @@
   g_test_instance = nullptr;
 }
 
-// static
 void InputHintChecker::RecordInputHintResult(InputHintResult result) {
+  if (!metric_subsampling_disabled_ &&
+      !base::ShouldRecordSubsampledMetric(0.001)) {
+    return;
+  }
   UMA_HISTOGRAM_ENUMERATION("Android.InputHintChecker.InputHintResult", result);
 }
 
@@ -318,8 +323,7 @@
 void JNI_InputHintChecker_OnCompositorViewHolderTouchEvent(_JNIEnv* env) {
   auto& checker = InputHintChecker::GetInstance();
   if (checker.is_after_input_yield()) {
-    InputHintChecker::RecordInputHintResult(
-        InputHintResult::kCompositorViewTouchEvent);
+    checker.RecordInputHintResult(InputHintResult::kCompositorViewTouchEvent);
   }
   checker.set_is_after_input_yield(false);
 }
@@ -346,6 +350,7 @@
 void JNI_InputHintChecker_SetIsAfterInputYieldForTesting(  // IN-TEST
     _JNIEnv* env,
     jboolean after) {
+  InputHintChecker::GetInstance().disable_metric_subsampling();
   InputHintChecker::GetInstance().set_is_after_input_yield(after);
 }
 
diff --git a/tot/base/android/input_hint_checker.h b/tot/base/android/input_hint_checker.h
index c8d830f..7e0e459 100644
--- a/tot/base/android/input_hint_checker.h
+++ b/tot/base/android/input_hint_checker.h
@@ -83,8 +83,11 @@
   void set_is_after_input_yield(bool after) { is_after_input_yield_ = after; }
   bool is_after_input_yield() { return is_after_input_yield_; }
 
+  // Used to test UMA metric recording.
+  void disable_metric_subsampling() { metric_subsampling_disabled_ = true; }
+
   // Records the UMA metric based on the InputHintResult.
-  static void RecordInputHintResult(InputHintResult result);
+  void RecordInputHintResult(InputHintResult result);
 
   bool IsInitializedForTesting();
   bool FailedToInitializeForTesting();
@@ -105,6 +108,7 @@
   bool HasInputImpl(JNIEnv* env, jobject o);
 
   bool is_after_input_yield_ = false;
+  bool metric_subsampling_disabled_ = false;
 
   // Last time the input hint was requested. Used for throttling.
   base::TimeTicks last_checked_;
diff --git a/tot/base/android/int_string_callback.cc b/tot/base/android/int_string_callback.cc
index 5cfeda8..d73f17c 100644
--- a/tot/base/android/int_string_callback.cc
+++ b/tot/base/android/int_string_callback.cc
@@ -13,7 +13,7 @@
 #include "base/android/jni_string.h"
 
 // Must come after all headers that specialize FromJniType() / ToJniType().
-#include "base/base_jni/IntStringCallback_jni.h"
+#include "base/base_minimal_jni/IntStringCallback_jni.h"
 
 namespace base {
 namespace android {
@@ -22,9 +22,10 @@
                                  int int_arg,
                                  const std::string& str_arg) {
   JNIEnv* env = jni_zero::AttachCurrentThread();
-  Java_IntStringCallback_onResult(env, callback, int_arg,
-                                  ConvertUTF8ToJavaString(env, str_arg));
+  Java_IntStringCallback_onResult(env, callback, int_arg, str_arg);
 }
 
 }  // namespace android
 }  // namespace base
+
+DEFINE_JNI_FOR_IntStringCallback()
diff --git a/tot/base/android/jank_metric_uma_recorder_unittest.cc b/tot/base/android/jank_metric_uma_recorder_unittest.cc
index 9e8a9c6..2a08f5b 100644
--- a/tot/base/android/jank_metric_uma_recorder_unittest.cc
+++ b/tot/base/android/jank_metric_uma_recorder_unittest.cc
@@ -65,7 +65,6 @@
 }  // namespace
 
 TEST(JankMetricUMARecorder, TestUMARecording) {
-
   JNIEnv* env = AttachCurrentThread();
 
   jlongArray java_durations = GenerateJavaLongArray(env, kDurations);
diff --git a/tot/base/android/java/src/org/chromium/base/AconfigFlaggedApiDelegate.java b/tot/base/android/java/src/org/chromium/base/AconfigFlaggedApiDelegate.java
new file mode 100644
index 0000000..7a9879d
--- /dev/null
+++ b/tot/base/android/java/src/org/chromium/base/AconfigFlaggedApiDelegate.java
@@ -0,0 +1,37 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.base;
+
+import android.net.http.X509TrustManagerExtensions;
+import android.view.contentcapture.ContentCaptureSession;
+
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.List;
+
+/** Interface to call unreleased Android APIs that are guarded by aconfig flags. */
+@NullMarked
+public interface AconfigFlaggedApiDelegate {
+    /** Call ContentCaptureSession.flush() if supported, otherwise no-op. */
+    default void flushContentCaptureSession(ContentCaptureSession session) {}
+
+    /**
+     * Call the CertificateTransparency-enabled cert verification platform API if its supported,
+     * otherwise call the normal non-CT cert verification API.
+     */
+    default List<X509Certificate> checkServerTrusted(
+            X509TrustManagerExtensions tm,
+            X509Certificate[] chain,
+            String authType,
+            String host,
+            byte @Nullable [] ocspResponse,
+            byte @Nullable [] sctList)
+            throws CertificateException {
+        return tm.checkServerTrusted(chain, authType, host);
+    }
+}
diff --git a/tot/base/android/java/src/org/chromium/base/ActivityLifecycleCallbacksAdapter.java b/tot/base/android/java/src/org/chromium/base/ActivityLifecycleCallbacksAdapter.java
index 4abcc95..a60bcac 100644
--- a/tot/base/android/java/src/org/chromium/base/ActivityLifecycleCallbacksAdapter.java
+++ b/tot/base/android/java/src/org/chromium/base/ActivityLifecycleCallbacksAdapter.java
@@ -8,13 +8,17 @@
 import android.app.Application;
 import android.os.Bundle;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /** An ActivityLifecycleCallbacks that routes all methods to a single onStateChanged(). */
+@NullMarked
 public abstract class ActivityLifecycleCallbacksAdapter
         implements Application.ActivityLifecycleCallbacks {
     public abstract void onStateChanged(Activity activity, @ActivityState int newState);
 
     @Override
-    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
+    public void onActivityCreated(Activity activity, @Nullable Bundle savedInstanceState) {
         onStateChanged(activity, ActivityState.CREATED);
     }
 
diff --git a/tot/base/android/java/src/org/chromium/base/ActivityState.java b/tot/base/android/java/src/org/chromium/base/ActivityState.java
index 08adc88..09c754d 100644
--- a/tot/base/android/java/src/org/chromium/base/ActivityState.java
+++ b/tot/base/android/java/src/org/chromium/base/ActivityState.java
@@ -6,10 +6,13 @@
 
 import androidx.annotation.IntDef;
 
+import org.chromium.build.annotations.NullMarked;
+
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 
 /** A set of states that represent the last state change of an Activity. */
+@NullMarked
 @Retention(RetentionPolicy.SOURCE)
 @IntDef({
     ActivityState.CREATED,
diff --git a/tot/base/android/java/src/org/chromium/base/AndroidInfo.java b/tot/base/android/java/src/org/chromium/base/AndroidInfo.java
new file mode 100644
index 0000000..a9cd969
--- /dev/null
+++ b/tot/base/android/java/src/org/chromium/base/AndroidInfo.java
@@ -0,0 +1,93 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.base;
+
+import android.os.Build;
+import android.os.Build.VERSION_CODES;
+import android.text.TextUtils;
+
+import org.jni_zero.CalledByNative;
+import org.jni_zero.JNINamespace;
+import org.jni_zero.NativeMethods;
+
+import org.chromium.build.annotations.NullMarked;
+
+/** AndroidInfo is a utility class to access Android's Build information specific data. */
+@JNINamespace("base::android::android_info")
+@NullMarked
+public final class AndroidInfo {
+    private static final String TAG = "AndroidInfo";
+
+    // Called by the native code to retrieve field values. There is no easy way to
+    // return several fields from Java to native, so instead this calls back into
+    // native, passing the fields as parameters to a native function.
+    // The native code expects native `fillFields()` to be called inline from this
+    // function.
+    @CalledByNative
+    private static void nativeReadyForFields() {
+        AndroidInfoJni.get()
+                .fillFields(
+                        /* brand= */ Build.BRAND,
+                        /* device= */ Build.DEVICE,
+                        /* buildId= */ Build.ID,
+                        /* manufacturer= */ Build.MANUFACTURER,
+                        /* model= */ Build.MODEL,
+                        /* type= */ Build.TYPE,
+                        /* board= */ Build.BOARD,
+                        /* androidBuildFingerprint= */ getAndroidBuildFingerprint(),
+                        /* versionIncremental= */ Build.VERSION.INCREMENTAL,
+                        /* hardware= */ Build.HARDWARE,
+                        /* codeName= */ Build.VERSION.CODENAME,
+                        /* socManufacturer= */ Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
+                                ? Build.SOC_MANUFACTURER
+                                : "",
+                        /* supportedAbis= */ TextUtils.join(", ", Build.SUPPORTED_ABIS),
+                        /* sdkInt= */ Build.VERSION.SDK_INT,
+                        /* isDebugAndroid= */ isDebugAndroid(),
+                        /* isAtleastU= */ Build.VERSION.SDK_INT >= VERSION_CODES.UPSIDE_DOWN_CAKE,
+                        /* isAtleastT= */ Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU);
+    }
+
+    /* Truncated version of Build.FINGERPRINT (for crash reporting). */
+    public static String getAndroidBuildFingerprint() {
+        return Build.FINGERPRINT.substring(0, Math.min(Build.FINGERPRINT.length(), 128));
+    }
+
+    public static String getAndroidSupportedAbis() {
+        return TextUtils.join(", ", Build.SUPPORTED_ABIS);
+    }
+
+    private AndroidInfo() {}
+
+    /**
+     * Check if this is a debuggable build of Android. This is a rough approximation of the hidden
+     * API {@code Build.IS_DEBUGGABLE}.
+     */
+    public static boolean isDebugAndroid() {
+        return "eng".equals(Build.TYPE) || "userdebug".equals(Build.TYPE);
+    }
+
+    @NativeMethods
+    interface Natives {
+        void fillFields(
+                String brand,
+                String device,
+                String buildId,
+                String manufacturer,
+                String model,
+                String type,
+                String board,
+                String androidBuildFingerprint,
+                String versionIncremental,
+                String hardware,
+                String codeName,
+                String socManufacturer,
+                String supportedAbis,
+                int sdkInt,
+                boolean isDebugAndroid,
+                boolean isAtleastU,
+                boolean isAtleastT);
+    }
+}
diff --git a/tot/base/android/java/src/org/chromium/base/ApiCompatibilityUtils.java b/tot/base/android/java/src/org/chromium/base/ApiCompatibilityUtils.java
index 814467f..aad27ea 100644
--- a/tot/base/android/java/src/org/chromium/base/ApiCompatibilityUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/ApiCompatibilityUtils.java
@@ -25,9 +25,10 @@
 import android.view.Display;
 import android.view.View;
 
-import androidx.annotation.NonNull;
+import org.chromium.build.annotations.NullMarked;
 
 import java.io.IOException;
+import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.nio.charset.StandardCharsets;
@@ -40,6 +41,7 @@
  * Do not inline because we use many new APIs, and if they are inlined, they could cause dex
  * validation errors on low Android versions.
  */
+@NullMarked
 public class ApiCompatibilityUtils {
     private static final String TAG = "ApiCompatUtil";
 
@@ -72,10 +74,14 @@
             // For Android Oreo+, Resources.getDrawable(id, null) delegates to
             // Resources.getDrawableForDensity(id, 0, null), but before that the two functions are
             // independent. This check can be removed after Oreo becomes the minimum supported API.
+            Drawable ret;
             if (density == 0) {
-                return res.getDrawable(id, null);
+                ret = res.getDrawable(id, null);
+            } else {
+                ret = res.getDrawableForDensity(id, density, null);
             }
-            return res.getDrawableForDensity(id, density, null);
+            assert ret != null : "Drawable " + id;
+            return ret;
         } finally {
             StrictMode.setThreadPolicy(oldPolicy);
         }
@@ -114,7 +120,6 @@
      * @return A list of display ids. Empty if there is none or version is less than Q, or
      *     windowAndroid does not contain an activity.
      */
-    @NonNull
     public static List<Integer> getTargetableDisplayIds(Activity activity) {
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
             List<Integer> displayList = new ArrayList<>();
@@ -140,17 +145,36 @@
     }
 
     /**
-     * Sets the mode {@link ActivityOptions#MODE_BACKGROUND_ACTIVITY_START_ALLOWED} to the given
-     * {@link ActivityOptions}. The options can be used to send {@link PendingIntent} passed to
-     * Chrome from a backgrounded app.
+     * Sets the mode {@link ActivityOptions#MODE_BACKGROUND_ACTIVITY_START_ALLOW_ALWAYS} to the
+     * given {@link ActivityOptions}. The options can be used to send {@link PendingIntent} passed
+     * to Chrome from a backgrounded app.
      *
      * @param options {@ActivityOptions} to set the required mode to.
      */
-    public static void setActivityOptionsBackgroundActivityStartMode(
-            @NonNull ActivityOptions options) {
+    public static void setActivityOptionsBackgroundActivityStartAllowAlways(
+            ActivityOptions options) {
         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return;
-        options.setPendingIntentBackgroundActivityStartMode(
-                ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
+
+        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
+            options.setPendingIntentBackgroundActivityStartMode(
+                    ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
+        } else {
+            options.setPendingIntentBackgroundActivityStartMode(
+                    getBackgroundActivityStartAllowAlwaysMode());
+        }
+    }
+
+    private static int getBackgroundActivityStartAllowAlwaysMode() {
+        // TODO(crbug.com/366220935): Stop using reflection and inline this method once
+        // the constant becomes available in B.
+        try {
+            Class<?> clazz = ActivityOptions.class;
+            Field field = clazz.getDeclaredField("MODE_BACKGROUND_ACTIVITY_START_ALLOW_ALWAYS");
+            field.setAccessible(true);
+            return field.getInt(null);
+        } catch (NoSuchFieldException | IllegalAccessException e) {
+            throw new RuntimeException("Background start mode cannot be found.", e);
+        }
     }
 
     /**
@@ -160,7 +184,7 @@
      * @param options {@ActivityOptions} to set the required mode to.
      */
     public static void setCreatorActivityOptionsBackgroundActivityStartMode(
-            @NonNull ActivityOptions options) {
+            ActivityOptions options) {
         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return;
         options.setPendingIntentCreatorBackgroundActivityStartMode(
                 ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
diff --git a/tot/base/android/java/src/org/chromium/base/ApkAssets.java b/tot/base/android/java/src/org/chromium/base/ApkAssets.java
index 87a40b6..213c03b 100644
--- a/tot/base/android/java/src/org/chromium/base/ApkAssets.java
+++ b/tot/base/android/java/src/org/chromium/base/ApkAssets.java
@@ -11,8 +11,11 @@
 
 import org.jni_zero.CalledByNative;
 import org.jni_zero.JNINamespace;
+import org.jni_zero.JniType;
 
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.io.IOException;
 import java.util.Arrays;
@@ -22,16 +25,18 @@
  * defined as tuple (file descriptor, offset, size) enabling direct mapping without deflation. This
  * can be used even within the renderer process, since it just dup's the apk's fd.
  */
+@NullMarked
 @JNINamespace("base::android")
 public class ApkAssets {
     private static final String TAG = "ApkAssets";
 
     // This isn't thread safe, but that's ok because it's only used for debugging.
     // Note reference operations are atomic so there is no security issue.
-    private static String sLastError;
+    private static @Nullable String sLastError;
 
     @CalledByNative
-    public static long[] open(String apkSubpath, String splitName) {
+    public static long[] open(
+            @JniType("std::string") String apkSubpath, @JniType("std::string") String splitName) {
         apkSubpath = maybeAddSuffix(apkSubpath);
         sLastError = null;
         AssetFileDescriptor afd = null;
@@ -58,7 +63,7 @@
             // For that reason, we only suppress the message when the exception message doesn't look
             // informative (Android framework passes the filename as the message on actual file not
             // found, and the empty string also wouldn't give any useful information for debugging).
-            if (!e.getMessage().equals("") && !e.getMessage().equals(apkSubpath)) {
+            if (!TextUtils.isEmpty(e.getMessage()) && !e.getMessage().equals(apkSubpath)) {
                 Log.e(TAG, sLastError);
             }
             return new long[] {-1, -1, -1};
@@ -91,7 +96,7 @@
     }
 
     @CalledByNative
-    private static String takeLastErrorString() {
+    private static @Nullable @JniType("std::string") String takeLastErrorString() {
         String rv = sLastError;
         sLastError = null;
         return rv;
diff --git a/tot/base/android/java/src/org/chromium/base/ApkInfo.java b/tot/base/android/java/src/org/chromium/base/ApkInfo.java
new file mode 100644
index 0000000..cb020ce
--- /dev/null
+++ b/tot/base/android/java/src/org/chromium/base/ApkInfo.java
@@ -0,0 +1,350 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.base;
+
+import static org.chromium.build.NullUtil.assumeNonNull;
+
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.os.Build;
+import android.os.Process;
+
+import org.jni_zero.CalledByNative;
+import org.jni_zero.JNINamespace;
+import org.jni_zero.NativeMethods;
+
+import org.chromium.base.version_info.VersionInfo;
+import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
+/**
+ * AndroidInfo is a utility class to access the APK-related information.
+ *
+ * <p>Warning: Adding any new field here will means that all products of Chromium that initializes
+ * this class will have to pay the cost of that new field, this can be costy especially when the
+ * field added is not useful to the entire codebase. Over time this can lead to performance
+ * regressions.
+ */
+@JNINamespace("base::android::apk_info")
+@NullMarked
+public final class ApkInfo {
+    private static final String TAG = "ApkInfo";
+
+    private static boolean sInitialized;
+    private static @Nullable PackageInfo sBrowserPackageInfo;
+
+    private final ApplicationInfo mBrowserApplicationInfo;
+
+    /**
+     * The package name of the host app which has loaded WebView, retrieved from the application
+     * context. In the context of the SDK Runtime, the package name of the app that owns this
+     * particular instance of the SDK Runtime will also be included. e.g.
+     * com.google.android.sdksandbox:com:com.example.myappwithads
+     */
+    private final String mHostPackageName;
+
+    /**
+     * The application name (e.g. "Chrome"). For WebView, this is name of the embedding app. In the
+     * context of the SDK Runtime, this is the name of the app that owns this particular instance of
+     * the SDK Runtime.
+     */
+    private final String mHostPackageLabel;
+
+    /**
+     * By default: same as versionCode. For WebView: versionCode of the embedding app. In the
+     * context of the SDK Runtime, this is the versionCode of the app that owns this particular
+     * instance of the SDK Runtime.
+     */
+    private final long mHostVersionCode;
+
+    /** The versionName of Chrome/WebView. Use application context for host app versionName. */
+    private final String mVersionName;
+
+    /** Result of PackageManager.getInstallerPackageName(). Never null, but may be "". */
+    private final String mInstallerPackageName;
+
+    /**
+     * The packageName of Chrome/WebView. Use application context for host app packageName. Same as
+     * the host information within any child process.
+     */
+    private final String mPackageName;
+
+    /** Product version as stored in Android resources. */
+    private final String mResourcesVersion;
+
+    private static volatile @Nullable ApkInfo sInstance;
+
+    private static final Object CREATION_LOCK = new Object();
+
+    // Called by the native code to retrieve field values. There is no easy way to
+    // return several fields from Java to native, so instead this calls back into
+    // native, passing the fields as parameters to a native function.
+    // The native code expects native `fillFields()` to be called inline from this
+    // function.
+    @CalledByNative
+    private static void nativeReadyForFields() {
+        ApkInfo instance = getInstance();
+        ApkInfoJni.get()
+                .fillFields(
+                        /* hostPackageName= */ instance.mHostPackageName,
+                        /* hostVersionCode= */ String.valueOf(instance.mHostVersionCode),
+                        /* hostPackageLabel= */ instance.mHostPackageLabel,
+                        /* packageVersionCode= */ String.valueOf(BuildConfig.VERSION_CODE),
+                        /* packageVersionName= */ instance.mVersionName,
+                        /* packageName= */ instance.mPackageName,
+                        /* resourcesVersion= */ instance.mResourcesVersion,
+                        /* installerPackageName= */ instance.mInstallerPackageName,
+                        /* isDebugApp= */ isDebugApp(),
+                        /* targetsAtleastU= */ targetsAtLeastU(),
+                        /* targetSdkVersion= */ ContextUtils.getApplicationContext()
+                                .getApplicationInfo()
+                                .targetSdkVersion);
+    }
+
+    public static String getHostPackageName() {
+        return getInstance().mHostPackageName;
+    }
+
+    public static long getHostVersionCode() {
+        return getInstance().mHostVersionCode;
+    }
+
+    public static String getHostPackageLabel() {
+        return getInstance().mHostPackageLabel;
+    }
+
+    public static String getPackageName() {
+        return getInstance().mPackageName;
+    }
+
+    public static String getPackageVersionCode() {
+        return String.valueOf(BuildConfig.VERSION_CODE);
+    }
+
+    public static String getPackageVersionName() {
+        return getInstance().mVersionName;
+    }
+
+    public static String getInstallerPackageName() {
+        return getInstance().mInstallerPackageName;
+    }
+
+    public static String getResourcesVersion() {
+        return getInstance().mResourcesVersion;
+    }
+
+    /**
+     * Checks if the application targets pre-release SDK U. This must be manually maintained as the
+     * SDK goes through finalization! Avoid depending on this if possible; this is only intended for
+     * WebView.
+     */
+    public static boolean targetsAtLeastU() {
+        int target = ContextUtils.getApplicationContext().getApplicationInfo().targetSdkVersion;
+
+        return target >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE;
+    }
+
+    /**
+     * Checks if the application targets pre-release SDK B. This must be manually maintained as the
+     * SDK goes through finalization.
+     */
+    public static boolean targetAtLeastB() {
+        int target = ContextUtils.getApplicationContext().getApplicationInfo().targetSdkVersion;
+
+        // Logic for pre-API-finalization:
+        // return BuildCompat.isAtLeastU() && target == Build.VERSION_CODES.CUR_DEVELOPMENT;
+
+        // Logic for after API finalization but before public SDK release has to just hardcode the
+        // appropriate SDK integer. This will include Android builds with the finalized SDK, and
+        // also pre-API-finalization builds (because CUR_DEVELOPMENT == 10000).
+        return target >= 36;
+
+        // Now that the public SDK is upstreamed we can use the defined constant. All users of this
+        // should now just inline this check themselves.
+        // return target >= Build.VERSION_CODES.<PLACE_HOLDER>;
+    }
+
+    public static boolean isInitializedForTesting() {
+        return sInitialized;
+    }
+
+    public static ApkInfo getInstance() {
+        // Some tests mock out things BuildInfo is based on, so disable caching in tests to ensure
+        // such mocking is not defeated by caching.
+        if (BuildConfig.IS_FOR_TEST) {
+            return new ApkInfo();
+        }
+
+        if (sInstance == null) {
+            synchronized (CREATION_LOCK) {
+                if (sInstance == null) {
+                    sInstance = new ApkInfo();
+                }
+            }
+        }
+        return sInstance;
+    }
+
+    /**
+     * @return ApplicationInfo for Chrome/WebView (as opposed to host app).
+     */
+    public ApplicationInfo getBrowserApplicationInfo() {
+        return mBrowserApplicationInfo;
+    }
+
+    /**
+     * @param packageInfo Package for Chrome/WebView (as opposed to host app).
+     */
+    public static void setBrowserPackageInfo(PackageInfo packageInfo) {
+        assert !sInitialized;
+        sBrowserPackageInfo = packageInfo;
+    }
+
+    private static String nullToEmpty(@Nullable CharSequence seq) {
+        return seq == null ? "" : seq.toString();
+    }
+
+    private ApkInfo() {
+        sInitialized = true;
+        Context appContext = ContextUtils.getApplicationContext();
+        String appContextPackageName = appContext.getPackageName();
+        PackageManager pm = appContext.getPackageManager();
+
+        String providedHostPackageName = null;
+        String providedHostPackageLabel = null;
+        String providedPackageName = null;
+        String providedPackageVersionName = null;
+        Long providedHostVersionCode = null;
+
+        // The child processes are running in an isolated process so they can't grab a lot of
+        // package information in the same way that we normally would retrieve them. To get around
+        // this, we feed the information as command line switches.
+        if (CommandLine.isInitialized()) {
+            CommandLine commandLine = CommandLine.getInstance();
+            providedHostPackageName = commandLine.getSwitchValue(BaseSwitches.HOST_PACKAGE_NAME);
+            providedHostPackageLabel = commandLine.getSwitchValue(BaseSwitches.HOST_PACKAGE_LABEL);
+            providedPackageName = commandLine.getSwitchValue(BaseSwitches.PACKAGE_NAME);
+            providedPackageVersionName =
+                    commandLine.getSwitchValue(BaseSwitches.PACKAGE_VERSION_NAME);
+
+            String flagValue = commandLine.getSwitchValue(BaseSwitches.HOST_VERSION_CODE);
+
+            if (flagValue != null) {
+                providedHostVersionCode = Long.parseLong(flagValue);
+            }
+        }
+
+        boolean hostInformationProvided =
+                providedHostPackageName != null
+                        && providedHostPackageLabel != null
+                        && providedHostVersionCode != null
+                        && providedPackageName != null
+                        && providedPackageVersionName != null;
+
+        // We want to retrieve the original package installed to verify to host package name.
+        // In the case of the SDK Runtime, we would like to retrieve the package name loading the
+        // SDK.
+        String appInstalledPackageName = appContextPackageName;
+        ApplicationInfo appInfo = appContext.getApplicationInfo();
+
+        if (hostInformationProvided) {
+            mHostPackageName = assumeNonNull(providedHostPackageName);
+            mHostPackageLabel = assumeNonNull(providedHostPackageLabel);
+            mHostVersionCode = assumeNonNull(providedHostVersionCode);
+            mVersionName = assumeNonNull(providedPackageVersionName);
+            mPackageName = assumeNonNull(providedPackageName);
+        } else {
+            // The SDK Qualified package name will retrieve the same information as
+            // appInstalledPackageName but prefix it with the SDK Sandbox process so that we can
+            // tell SDK Runtime data apart from regular data in our logs and metrics.
+            String sdkQualifiedName = appInstalledPackageName;
+
+            // TODO(bewise): There isn't currently an official API to grab the host package name
+            // with the SDK Runtime. We can work around this because SDKs loaded in the SDK
+            // Runtime have the host UID + 10000. This should be updated if a public API comes
+            // along that we can use.
+            // You can see more about this in the Android source:
+            // https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/os/Process.java;l=292;drc=47fffdd53115a9af1820e3f89d8108745be4b55d
+            if (ContextUtils.isSdkSandboxProcess()) {
+                final int hostId = Process.myUid() - 10000;
+                final String[] packageNames = pm.getPackagesForUid(hostId);
+
+                if (packageNames != null && packageNames.length > 0) {
+                    // We could end up with more than one package name if the app used a
+                    // sharedUserId but these are deprecated so this is a safe bet to rely on the
+                    // first package name.
+                    appInstalledPackageName = packageNames[0];
+                    sdkQualifiedName += ":" + appInstalledPackageName;
+                }
+            }
+
+            mHostPackageName = sdkQualifiedName;
+            mHostPackageLabel = nullToEmpty(pm.getApplicationLabel(appInfo));
+
+            if (sBrowserPackageInfo != null) {
+                PackageInfo pi =
+                        assumeNonNull(PackageUtils.getPackageInfo(appInstalledPackageName, 0));
+                mHostVersionCode = PackageUtils.packageVersionCode(pi);
+                mPackageName = sBrowserPackageInfo.packageName;
+                mVersionName = nullToEmpty(sBrowserPackageInfo.versionName);
+                appInfo = sBrowserPackageInfo.applicationInfo;
+                sBrowserPackageInfo = null;
+            } else {
+                mPackageName = appContextPackageName;
+                mHostVersionCode = BuildConfig.VERSION_CODE;
+                mVersionName = VersionInfo.getProductVersion();
+            }
+        }
+        assert appInfo != null;
+        mBrowserApplicationInfo = appInfo;
+
+        mInstallerPackageName = nullToEmpty(pm.getInstallerPackageName(appInstalledPackageName));
+
+        String currentResourcesVersion = "Not Enabled";
+        // Controlled by target specific build flags.
+        if (BuildConfig.R_STRING_PRODUCT_VERSION != 0) {
+            try {
+                // This value can be compared with the actual product version to determine if
+                // corrupted resources were the cause of a crash. This can happen if the app
+                // loads resources from the outdated package  during an update
+                // (http://crbug.com/820591).
+                currentResourcesVersion =
+                        ContextUtils.getApplicationContext()
+                                .getString(BuildConfig.R_STRING_PRODUCT_VERSION);
+            } catch (Exception e) {
+                currentResourcesVersion = "Not found";
+            }
+        }
+        mResourcesVersion = currentResourcesVersion;
+    }
+
+    /*
+     * Check if the app is declared debuggable in its manifest.
+     * In WebView, this refers to the host app.
+     */
+    public static boolean isDebugApp() {
+        int appFlags = ContextUtils.getApplicationContext().getApplicationInfo().flags;
+        return (appFlags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
+    }
+
+    @NativeMethods
+    interface Natives {
+        void fillFields(
+                String hostPackageName,
+                String hostVersionCode,
+                String hostPackageLabel,
+                String packageVersionCode,
+                String packageVersionName,
+                String packageName,
+                String resourcesVersion,
+                String installerPackageName,
+                boolean isDebugApp,
+                boolean targetsAtleastU,
+                int targetSdkVersion);
+    }
+}
diff --git a/tot/base/android/java/src/org/chromium/base/ApplicationStatus.java b/tot/base/android/java/src/org/chromium/base/ApplicationStatus.java
index e4bc6db..76d7078 100644
--- a/tot/base/android/java/src/org/chromium/base/ApplicationStatus.java
+++ b/tot/base/android/java/src/org/chromium/base/ApplicationStatus.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.annotation.SuppressLint;
 import android.app.Activity;
 import android.app.Application;
@@ -12,13 +14,15 @@
 
 import androidx.annotation.AnyThread;
 import androidx.annotation.MainThread;
-import androidx.annotation.Nullable;
 import androidx.annotation.VisibleForTesting;
 
 import org.jni_zero.CalledByNative;
 import org.jni_zero.JNINamespace;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.lang.reflect.Field;
 import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.InvocationTargetException;
@@ -40,6 +44,7 @@
  * WebView/WebLayer, and should be moved out of base and into //chrome. It should not be relied upon
  * for //components.
  */
+@NullMarked
 @JNINamespace("base::android")
 public class ApplicationStatus {
     private static final String TOOLBAR_CALLBACK_WRAPPER_CLASS =
@@ -92,28 +97,28 @@
 
     /** Last activity that was shown (or null if none or it was destroyed). */
     @SuppressLint("StaticFieldLeak")
-    private static Activity sActivity;
+    private static @Nullable Activity sActivity;
 
     /** A lazily initialized listener that forwards application state changes to native. */
-    private static ApplicationStateListener sNativeApplicationStateListener;
+    private static @Nullable ApplicationStateListener sNativeApplicationStateListener;
 
     /** A list of observers to be notified when any {@link Activity} has a state change. */
-    private static ObserverList<ActivityStateListener> sGeneralActivityStateListeners;
+    private static @Nullable ObserverList<ActivityStateListener> sGeneralActivityStateListeners;
 
     /**
      * A list of observers to be notified when the visibility state of this {@link Application}
      * changes.  See {@link #getStateForApplication()}.
      */
-    private static ObserverList<ApplicationStateListener> sApplicationStateListeners;
+    private static @Nullable ObserverList<ApplicationStateListener> sApplicationStateListeners;
 
     /**
      * A list of observers to be notified when the window focus changes.
      * See {@link #registerWindowFocusChangedListener}.
      */
-    private static ObserverList<WindowFocusChangedListener> sWindowFocusListeners;
+    private static @Nullable ObserverList<WindowFocusChangedListener> sWindowFocusListeners;
 
     /** A list of observers to be notified when the visibility of any task changes. */
-    private static ObserverList<TaskVisibilityListener> sTaskVisibilityListeners;
+    private static @Nullable ObserverList<TaskVisibilityListener> sTaskVisibilityListeners;
 
     /** Interface to be implemented by listeners. */
     public interface ApplicationStateListener {
@@ -247,7 +252,8 @@
         }
 
         @Override
-        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+        public @Nullable Object invoke(Object proxy, Method method, Object[] args)
+                throws Throwable {
             if (method.getName().equals("onWindowFocusChanged")
                     && args.length == 1
                     && args[0] instanceof Boolean) {
@@ -348,7 +354,7 @@
      * checking the declared fields of the given callback using reflection.
      */
     @VisibleForTesting
-    static boolean reachesWindowCallback(@Nullable Window.Callback callback) {
+    static boolean reachesWindowCallback(Window.@Nullable Callback callback) {
         if (callback == null) return false;
         if (callback.getClass().getName().equals(TOOLBAR_CALLBACK_WRAPPER_CLASS)) {
             // We're actually not going to get called, see AndroidX report here:
@@ -390,8 +396,6 @@
      * @param newState New state value.
      */
     private static void onStateChange(Activity activity, @ActivityState int newState) {
-        assert activity != null;
-
         if (sActivity == null
                 || newState == ActivityState.CREATED
                 || newState == ActivityState.RESUMED
@@ -409,7 +413,7 @@
                 sActivityInfo.put(activity, new ActivityInfo());
             }
 
-            info = sActivityInfo.get(activity);
+            info = assumeNonNull(sActivityInfo.get(activity));
             info.setStatus(newState);
 
             // Remove before calling listeners so that isEveryActivityDestroyed() returns false when
@@ -467,7 +471,7 @@
      * out of all the activities tracked here, it has most recently gained window focus.
      */
     @MainThread
-    public static Activity getLastTrackedFocusedActivity() {
+    public static @Nullable Activity getLastTrackedFocusedActivity() {
         return sActivity;
     }
 
diff --git a/tot/base/android/java/src/org/chromium/base/BaseFeatureMap.java b/tot/base/android/java/src/org/chromium/base/BaseFeatureMap.java
index 22c2bb5..989cc17 100644
--- a/tot/base/android/java/src/org/chromium/base/BaseFeatureMap.java
+++ b/tot/base/android/java/src/org/chromium/base/BaseFeatureMap.java
@@ -7,6 +7,9 @@
 import org.jni_zero.JNINamespace;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+
+@NullMarked
 @JNINamespace("base::android")
 public class BaseFeatureMap extends FeatureMap {
     private static final BaseFeatureMap sInstance = new BaseFeatureMap();
diff --git a/tot/base/android/java/src/org/chromium/base/BinderCallsListener.java b/tot/base/android/java/src/org/chromium/base/BinderCallsListener.java
index 18c03fb..02147f3 100644
--- a/tot/base/android/java/src/org/chromium/base/BinderCallsListener.java
+++ b/tot/base/android/java/src/org/chromium/base/BinderCallsListener.java
@@ -7,15 +7,20 @@
 import android.os.Binder;
 import android.os.IBinder;
 import android.os.RemoteException;
+import android.os.SystemClock;
 
-import androidx.annotation.Nullable;
 import androidx.annotation.UiThread;
 import androidx.annotation.VisibleForTesting;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
+import java.util.Collections;
+import java.util.HashSet;
 import java.util.function.BiConsumer;
 
 /**
@@ -26,15 +31,105 @@
  * covers all Binder calls made through BinderProxy, which covers Chromium code, as well as
  * third-party and framework code.
  */
+@NullMarked
 public class BinderCallsListener {
     private static final String TAG = "BinderCallsListener";
     private static final String PROXY_TRANSACT_LISTENER_CLASS_NAME =
             "android.os.Binder$ProxyTransactListener";
 
-    private static BinderCallsListener sInstance;
+    private static @Nullable BinderCallsListener sInstance;
 
-    private Object mImplementation;
-    private InterfaceInvocationHandler mInvocationHandler;
+    /** A means of reporting an exception/stack without crashing. */
+    private static @Nullable Callback<Throwable> sExceptionReporter;
+
+    private static final long LONG_BINDER_CALL_LIMIT_MILLIS = 2;
+    private static final double UPLOAD_PROBABILITY = 0.2;
+    private static final int MAX_UPLOADS_PER_SESSION = 3;
+    private static final HashSet<String> sSlowBinderCallAllowList = new HashSet<>();
+
+    // The comments mostly correspond to the slow use cases.
+    static {
+        Collections.addAll(
+                sSlowBinderCallAllowList,
+                // Callbacks for lifecycle events.
+                "android.app.IActivityTaskManager",
+                // Used for getActivityInfo, hasSystemFeature, and getSystemAvailableFeatures calls.
+                "android.content.pm.IPackageManager",
+                // Called by Choreographer.
+                "android.view.IWindowSession",
+                // Check whether UI mode is TV.
+                "android.app.IUiModeManager",
+                // Used to add Incognito launcher shortcut.
+                "android.content.pm.IShortcutService",
+                // Interactions with activities, services and content providers.
+                "android.app.IActivityManager",
+                // Used for getService calls.
+                "android.os.IServiceManager",
+                // Checks if power saving mode is enabled.
+                "android.os.IPowerManager",
+                // Used by Android code.
+                "android.content.IContentProvider",
+                "android.view.accessibility.IAccessibilityManager",
+                "android.os.IUserManager",
+                "android.hardware.devicestate.IDeviceStateManager",
+                "com.android.internal.telephony.ISub",
+                "com.android.internal.app.IAppOpsService",
+                "android.view.IGraphicsStats",
+                "android.app.job.IJobCallback",
+                "android.app.trust.ITrustManager",
+                "android.media.IAudioService",
+                "com.android.internal.inputmethod.IImeTracker",
+                "com.android.internal.inputmethod.IInputMethodSession",
+                "com.android.internal.app.IVoiceInteractionManagerService",
+                "com.android.internal.textservice.ITextServicesManager",
+                // Gets activity task ID during startup; cached.
+                "android.app.IActivityClientController",
+                // Used to check if stylus is enabled.
+                "com.android.internal.view.IInputMethodManager",
+                // Registers content observers.
+                "android.content.IContentService",
+                // BackgroundTaskScheduler.
+                "android.app.job.IJobScheduler",
+                // ConnectivitiyManager#getNetworkInfo.
+                "android.net.IConnectivityManager",
+                // Used to get Window Insets.
+                "android.view.IWindowManager",
+                // Determines if specific permissions are revoked by policy.
+                "android.permission.IPermissionManager",
+                // Used to get the system locale to set the UI language.
+                "android.app.ILocaleManager",
+                // Gets all search widget IDs.
+                "com.android.internal.appwidget.IAppWidgetService",
+                // Registers HDR:SDR change listener.
+                "android.hardware.display.IDisplayManager",
+                // Register Clipboard listener.
+                "android.content.IClipboard",
+                // Register input device change listener.
+                "android.hardware.input.IInputManager",
+                // Creates notification channels for devices on Android O and above.
+                "android.app.INotificationManager",
+                // AppTask#getTaskInfo
+                "android.app.IAppTask",
+                // Used to determine if device can authenticate with a given level of strength.
+                "android.hardware.biometrics.IAuthService",
+                // Context#getExternalFilesDirs for download directories.
+                "android.os.storage.IStorageManager",
+                // Watches changes to Android prefs backed up using Android KV backup.
+                "android.app.backup.IBackupManager",
+                // Used in test screenshots.
+                "android.app.IUiAutomationConnection",
+                // PowerMonitor#getCurrentThermalStatus.
+                "android.os.IThermalService",
+                // StrictMode#setVmPolicy. Only enabled for local builds and 1% of Dev users.
+                "android.os.INetworkManagementService",
+                // Records background restrictions imposed on Chrome by Android.
+                "android.app.usage.IUsageStatsManager",
+                // Used for EditText UI elements.
+                "android.view.autofill.IAutoFillManager");
+    }
+
+    private @Nullable Object mImplementation;
+    private @Nullable InterfaceInvocationHandler mInvocationHandler;
     private boolean mInstalled;
 
     @UiThread
@@ -45,6 +140,13 @@
         return sInstance;
     }
 
+    /**
+     * @param reporter A means of reporting an exception without crashing.
+     */
+    public static void setExceptionReporter(Callback<Throwable> reporter) {
+        sExceptionReporter = reporter;
+    }
+
     private BinderCallsListener() {
         try {
             Class interfaceClass = Class.forName(PROXY_TRANSACT_LISTENER_CLASS_NAME);
@@ -80,7 +182,7 @@
         return installListener(mImplementation);
     }
 
-    private boolean installListener(Object listener) {
+    private boolean installListener(@Nullable Object listener) {
         if (mInstalled) return false;
 
         try {
@@ -119,32 +221,68 @@
     }
 
     private static class InterfaceInvocationHandler implements InvocationHandler {
-        private String mCurrentInterfaceDescriptor;
-        private BiConsumer<String, String> mObserver;
+        private @Nullable String mCurrentInterfaceDescriptor;
+        private @Nullable BiConsumer<String, String> mObserver;
+        private int mCurrentTransactionId;
+        private int mNumUploads;
+        private long mCurrentTransactionStartTimeMillis;
 
         @Override
-        public Object invoke(Object proxy, Method method, Object[] args) {
+        public @Nullable Object invoke(Object proxy, Method method, Object[] args) {
             if (!ThreadUtils.runningOnUiThread()) return null;
             switch (method.getName()) {
                 case "onTransactStarted":
                     IBinder binder = (IBinder) args[0];
+                    mCurrentTransactionId++;
+                    mCurrentTransactionStartTimeMillis = SystemClock.uptimeMillis();
                     try {
                         mCurrentInterfaceDescriptor = binder.getInterfaceDescriptor();
                     } catch (RemoteException e) {
                         mCurrentInterfaceDescriptor = null;
+                        return null;
                     }
 
                     TraceEvent.begin("BinderCallsListener.invoke", mCurrentInterfaceDescriptor);
                     if (mObserver != null) {
                         mObserver.accept("onTransactStarted", mCurrentInterfaceDescriptor);
                     }
+                    if (!sSlowBinderCallAllowList.contains(mCurrentInterfaceDescriptor)) {
+                        return mCurrentTransactionId;
+                    }
                     return null;
                 case "onTransactEnded":
                     TraceEvent.end("BinderCallsListener.invoke", mCurrentInterfaceDescriptor);
-
                     if (mObserver != null) {
                         mObserver.accept("onTransactEnded", mCurrentInterfaceDescriptor);
                     }
+
+                    Integer session = (Integer) args[0];
+                    if (session == null || session != mCurrentTransactionId) {
+                        return null;
+                    }
+
+                    long transactionDurationMillis =
+                            SystemClock.uptimeMillis() - mCurrentTransactionStartTimeMillis;
+
+                    // Only report a subset of slow calls for non-local builds.
+                    boolean shouldReportSlowCall =
+                            transactionDurationMillis >= LONG_BINDER_CALL_LIMIT_MILLIS
+                                    && Math.random() < UPLOAD_PROBABILITY
+                                    && mNumUploads < MAX_UPLOADS_PER_SESSION;
+                    if (shouldReportSlowCall && sExceptionReporter != null) {
+                        // If there was a new Binder call introduced, consider moving it to a
+                        // background thread if possible. If not, add it to the allow list.
+                        String message =
+                                "BinderCallsListener detected a slow call on the UI thread by: "
+                                        + mCurrentInterfaceDescriptor
+                                        + " with duration="
+                                        + transactionDurationMillis
+                                        + "ms (max allowed: "
+                                        + LONG_BINDER_CALL_LIMIT_MILLIS
+                                        + "ms)";
+                        sExceptionReporter.onResult(new Throwable(message));
+                        mNumUploads++;
+                    }
                     return null;
             }
             return null;
diff --git a/tot/base/android/java/src/org/chromium/base/BuildInfo.java b/tot/base/android/java/src/org/chromium/base/BuildInfo.java
index 2240537..c45bcde 100644
--- a/tot/base/android/java/src/org/chromium/base/BuildInfo.java
+++ b/tot/base/android/java/src/org/chromium/base/BuildInfo.java
@@ -4,27 +4,22 @@
 
 package org.chromium.base;
 
-import static android.content.Context.UI_MODE_SERVICE;
-
-import android.app.UiModeManager;
-import android.content.Context;
 import android.content.pm.ApplicationInfo;
-import android.content.pm.FeatureInfo;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.Signature;
-import android.content.res.Configuration;
 import android.os.Build;
 import android.os.Build.VERSION_CODES;
 import android.os.Process;
-import android.text.TextUtils;
 
 import org.jni_zero.CalledByNative;
-import org.jni_zero.CalledByNativeForTesting;
 import org.jni_zero.JniType;
 
 import org.chromium.build.BuildConfig;
 import org.chromium.build.NativeLibraries;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.NullUnmarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
@@ -34,20 +29,20 @@
 /**
  * BuildInfo is a utility class providing easy access to {@link PackageInfo} information. This is
  * primarily of use for accessing package information from native code.
+ *
+ * <p>NOTE: This class is deprecated, You can find the appropriate utilities that lived here in
+ * AndroidInfo, ApkInfo or DeviceInfo.
  */
+@NullMarked
+@Deprecated
 public class BuildInfo {
     private static final String TAG = "BuildInfo";
-    private static final int MAX_FINGERPRINT_LENGTH = 128;
-
-    private static PackageInfo sBrowserPackageInfo;
-    private static ApplicationInfo sBrowserApplicationInfo;
-    private static boolean sInitialized;
 
     /**
      * The package name of the host app which has loaded WebView, retrieved from the application
      * context. In the context of the SDK Runtime, the package name of the app that owns this
-     * particular instance of the SDK Runtime will also be included.
-     * e.g. com.google.android.sdksandbox:com:com.example.myappwithads
+     * particular instance of the SDK Runtime will also be included. e.g.
+     * com.google.android.sdksandbox:com:com.example.myappwithads
      */
     public final String hostPackageName;
 
@@ -86,9 +81,6 @@
     /** Truncated version of Build.FINGERPRINT (for crash reporting). */
     public final String androidBuildFingerprint;
 
-    /** Whether or not the device has apps installed for using custom themes. */
-    public final String customThemes;
-
     /** Product version as stored in Android resources. */
     public final String resourcesVersion;
 
@@ -114,10 +106,7 @@
      * an empty string if we were unable to retrieve it.
      */
     @GuardedBy("mCertLock")
-    private String mHostSigningCertSha256;
-
-    /** The versionCode of Play Services. Can be overridden in tests. */
-    private String mGmsVersionCode;
+    private @Nullable String mHostSigningCertSha256;
 
     private final Object mCertLock = new Object();
 
@@ -126,65 +115,12 @@
     }
 
     @CalledByNative
-    private static String[] getAll() {
-        return BuildInfo.getInstance().getAllProperties();
-    }
-
-    @CalledByNative
-    private static String lazyGetHostSigningCertSha256() {
+    private static @JniType("std::string") String lazyGetHostSigningCertSha256() {
         return BuildInfo.getInstance().getHostSigningCertSha256();
     }
 
-    @CalledByNativeForTesting
-    private static void setGmsVersionCodeForTest(@JniType("std::string") String gmsVersionCode) {
-        getInstance().mGmsVersionCode = gmsVersionCode;
-    }
-
-    /** Returns a serialized string array of all properties of this class. */
-    private String[] getAllProperties() {
-        // This implementation needs to be kept in sync with the native BuildInfo constructor.
-        return new String[] {
-            Build.BRAND,
-            Build.DEVICE,
-            Build.ID,
-            Build.MANUFACTURER,
-            Build.MODEL,
-            String.valueOf(Build.VERSION.SDK_INT),
-            Build.TYPE,
-            Build.BOARD,
-            hostPackageName,
-            String.valueOf(hostVersionCode),
-            hostPackageLabel,
-            packageName,
-            String.valueOf(versionCode),
-            versionName,
-            androidBuildFingerprint,
-            mGmsVersionCode,
-            installerPackageName,
-            abiString,
-            customThemes,
-            resourcesVersion,
-            String.valueOf(
-                    ContextUtils.getApplicationContext().getApplicationInfo().targetSdkVersion),
-            isDebugAndroid() ? "1" : "0",
-            isTV ? "1" : "0",
-            Build.VERSION.INCREMENTAL,
-            Build.HARDWARE,
-            Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU ? "1" : "0",
-            isAutomotive ? "1" : "0",
-            Build.VERSION.SDK_INT >= VERSION_CODES.UPSIDE_DOWN_CAKE ? "1" : "0",
-            targetsAtLeastU() ? "1" : "0",
-            Build.VERSION.CODENAME,
-            String.valueOf(vulkanDeqpLevel),
-            isFoldable ? "1" : "0",
-            Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ? Build.SOC_MANUFACTURER : "",
-            isDebugApp() ? "1" : "0",
-            isDesktop ? "1" : "0",
-        };
-    }
-
-    private static String nullToEmpty(CharSequence seq) {
-        return seq == null ? "" : seq.toString();
+    public static void setGmsVersionCodeForTest(@JniType("std::string") String gmsVersionCode) {
+        DeviceInfo.setGmsVersionCodeForTest(gmsVersionCode);
     }
 
     /**
@@ -217,15 +153,14 @@
      * @param packageInfo Package for Chrome/WebView (as opposed to host app).
      */
     public static void setBrowserPackageInfo(PackageInfo packageInfo) {
-        assert !sInitialized;
-        sBrowserPackageInfo = packageInfo;
+        ApkInfo.setBrowserPackageInfo(packageInfo);
     }
 
     /**
      * @return ApplicationInfo for Chrome/WebView (as opposed to host app).
      */
     public ApplicationInfo getBrowserApplicationInfo() {
-        return sBrowserApplicationInfo;
+        return ApkInfo.getInstance().getBrowserApplicationInfo();
     }
 
     public static BuildInfo getInstance() {
@@ -239,178 +174,25 @@
 
     /** The versionCode of Play Services. */
     public String getGmsVersionCode() {
-        return mGmsVersionCode;
+        return DeviceInfo.getGmsVersionCode();
     }
 
+    @SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/98
     private BuildInfo() {
-        sInitialized = true;
-        Context appContext = ContextUtils.getApplicationContext();
-        String appContextPackageName = appContext.getPackageName();
-        PackageManager pm = appContext.getPackageManager();
-
-        String providedHostPackageName = null;
-        String providedHostPackageLabel = null;
-        String providedPackageName = null;
-        String providedPackageVersionName = null;
-        Long providedHostVersionCode = null;
-
-        // The child processes are running in an isolated process so they can't grab a lot of
-        // package information in the same way that we normally would retrieve them. To get around
-        // this, we feed the information as command line switches.
-        if (CommandLine.isInitialized()) {
-            CommandLine commandLine = CommandLine.getInstance();
-            providedHostPackageName = commandLine.getSwitchValue(BaseSwitches.HOST_PACKAGE_NAME);
-            providedHostPackageLabel = commandLine.getSwitchValue(BaseSwitches.HOST_PACKAGE_LABEL);
-            providedPackageName = commandLine.getSwitchValue(BaseSwitches.PACKAGE_NAME);
-            providedPackageVersionName =
-                    commandLine.getSwitchValue(BaseSwitches.PACKAGE_VERSION_NAME);
-
-            if (commandLine.hasSwitch(BaseSwitches.HOST_VERSION_CODE)) {
-                providedHostVersionCode =
-                        Long.parseLong(commandLine.getSwitchValue(BaseSwitches.HOST_VERSION_CODE));
-            }
-        }
-
-        boolean hostInformationProvided =
-                providedHostPackageName != null
-                        && providedHostPackageLabel != null
-                        && providedHostVersionCode != null
-                        && providedPackageName != null
-                        && providedPackageVersionName != null;
-
-        // We want to retrieve the original package installed to verify to host package name.
-        // In the case of the SDK Runtime, we would like to retrieve the package name loading the
-        // SDK.
-        String appInstalledPackageName = appContextPackageName;
-
-        if (hostInformationProvided) {
-            hostPackageName = providedHostPackageName;
-            hostPackageLabel = providedHostPackageLabel;
-            hostVersionCode = providedHostVersionCode;
-            versionName = providedPackageVersionName;
-            packageName = providedPackageName;
-
-            sBrowserApplicationInfo = appContext.getApplicationInfo();
-        } else {
-            // The SDK Qualified package name will retrieve the same information as
-            // appInstalledPackageName but prefix it with the SDK Sandbox process so that we can
-            // tell SDK Runtime data apart from regular data in our logs and metrics.
-            String sdkQualifiedName = appInstalledPackageName;
-
-            // TODO(bewise): There isn't currently an official API to grab the host package name
-            // with the SDK Runtime. We can work around this because SDKs loaded in the SDK
-            // Runtime have the host UID + 10000. This should be updated if a public API comes
-            // along that we can use.
-            // You can see more about this in the Android source:
-            // https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/os/Process.java;l=292;drc=47fffdd53115a9af1820e3f89d8108745be4b55d
-            if (ContextUtils.isSdkSandboxProcess()) {
-                final int hostId = Process.myUid() - 10000;
-                final String[] packageNames = pm.getPackagesForUid(hostId);
-
-                if (packageNames.length > 0) {
-                    // We could end up with more than one package name if the app used a
-                    // sharedUserId but these are deprecated so this is a safe bet to rely on the
-                    // first package name.
-                    appInstalledPackageName = packageNames[0];
-                    sdkQualifiedName += ":" + appInstalledPackageName;
-                }
-            }
-
-            PackageInfo pi = PackageUtils.getPackageInfo(appInstalledPackageName, 0);
-            hostPackageName = sdkQualifiedName;
-            hostPackageLabel = nullToEmpty(pm.getApplicationLabel(pi.applicationInfo));
-            hostVersionCode = packageVersionCode(pi);
-
-            if (sBrowserPackageInfo != null) {
-                packageName = sBrowserPackageInfo.packageName;
-                versionName = nullToEmpty(sBrowserPackageInfo.versionName);
-                sBrowserApplicationInfo = sBrowserPackageInfo.applicationInfo;
-                sBrowserPackageInfo = null;
-            } else {
-                packageName = appContextPackageName;
-                versionName = nullToEmpty(pi.versionName);
-                sBrowserApplicationInfo = appContext.getApplicationInfo();
-            }
-        }
-
-        installerPackageName = nullToEmpty(pm.getInstallerPackageName(appInstalledPackageName));
-
-        PackageInfo gmsPackageInfo = PackageUtils.getPackageInfo("com.google.android.gms", 0);
-        mGmsVersionCode =
-                gmsPackageInfo != null
-                        ? String.valueOf(packageVersionCode(gmsPackageInfo))
-                        : "gms versionCode not available.";
-
-        // Substratum is a theme engine that enables users to use custom themes provided
-        // by theme apps. Sometimes these can cause crashs if not installed correctly.
-        // These crashes can be difficult to debug, so knowing if the theme manager is
-        // present on the device is useful (http://crbug.com/820591).
-        customThemes = String.valueOf(PackageUtils.isPackageInstalled("projekt.substratum"));
-
-        String currentResourcesVersion = "Not Enabled";
-        // Controlled by target specific build flags.
-        if (BuildConfig.R_STRING_PRODUCT_VERSION != 0) {
-            try {
-                // This value can be compared with the actual product version to determine if
-                // corrupted resources were the cause of a crash. This can happen if the app
-                // loads resources from the outdated package  during an update
-                // (http://crbug.com/820591).
-                currentResourcesVersion =
-                        ContextUtils.getApplicationContext()
-                                .getString(BuildConfig.R_STRING_PRODUCT_VERSION);
-            } catch (Exception e) {
-                currentResourcesVersion = "Not found";
-            }
-        }
-        resourcesVersion = currentResourcesVersion;
-
-        abiString = TextUtils.join(", ", Build.SUPPORTED_ABIS);
-
-        // The value is truncated, as this is used for crash and UMA reporting.
-        androidBuildFingerprint =
-                Build.FINGERPRINT.substring(
-                        0, Math.min(Build.FINGERPRINT.length(), MAX_FINGERPRINT_LENGTH));
-
-        // See https://developer.android.com/training/tv/start/hardware.html#runtime-check.
-        UiModeManager uiModeManager = (UiModeManager) appContext.getSystemService(UI_MODE_SERVICE);
-        isTV =
-                uiModeManager != null
-                        && uiModeManager.getCurrentModeType()
-                                == Configuration.UI_MODE_TYPE_TELEVISION;
-
-        boolean isAutomotive;
-        try {
-            isAutomotive = pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
-        } catch (SecurityException e) {
-            Log.e(TAG, "Unable to query for Automotive system feature", e);
-
-            // `hasSystemFeature` can possibly throw an exception on modified instances of
-            // Android. In this case, assume the device is not a car since automotive vehicles
-            // should not have such a modification.
-            isAutomotive = false;
-        }
-        this.isAutomotive = isAutomotive;
-
-        // Detect whether device is foldable.
-        this.isFoldable =
-                Build.VERSION.SDK_INT >= VERSION_CODES.R
-                        && pm.hasSystemFeature(PackageManager.FEATURE_SENSOR_HINGE_ANGLE);
-
-        this.isDesktop = pm.hasSystemFeature(PackageManager.FEATURE_PC);
-
-        int vulkanLevel = 0;
-        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
-            FeatureInfo[] features = pm.getSystemAvailableFeatures();
-            if (features != null) {
-                for (FeatureInfo feature : features) {
-                    if (PackageManager.FEATURE_VULKAN_DEQP_LEVEL.equals(feature.name)) {
-                        vulkanLevel = feature.version;
-                        break;
-                    }
-                }
-            }
-        }
-        vulkanDeqpLevel = vulkanLevel;
+        hostPackageName = ApkInfo.getHostPackageName();
+        hostPackageLabel = ApkInfo.getHostPackageLabel();
+        hostVersionCode = ApkInfo.getHostVersionCode();
+        packageName = ApkInfo.getPackageName();
+        versionName = ApkInfo.getPackageVersionName();
+        installerPackageName = ApkInfo.getInstallerPackageName();
+        abiString = AndroidInfo.getAndroidSupportedAbis();
+        androidBuildFingerprint = AndroidInfo.getAndroidBuildFingerprint();
+        resourcesVersion = ApkInfo.getResourcesVersion();
+        isTV = DeviceInfo.isTV();
+        isAutomotive = DeviceInfo.isAutomotive();
+        isFoldable = DeviceInfo.isFoldable();
+        isDesktop = DeviceInfo.isDesktop();
+        vulkanDeqpLevel = DeviceInfo.getVulkanDeqpLevel();
     }
 
     /**
@@ -418,7 +200,7 @@
      * API {@code Build.IS_DEBUGGABLE}.
      */
     public static boolean isDebugAndroid() {
-        return "eng".equals(Build.TYPE) || "userdebug".equals(Build.TYPE);
+        return AndroidInfo.isDebugAndroid();
     }
 
     /*
@@ -426,13 +208,12 @@
      * In WebView, this refers to the host app.
      */
     public static boolean isDebugApp() {
-        int appFlags = ContextUtils.getApplicationContext().getApplicationInfo().flags;
-        return (appFlags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
+        return ApkInfo.isDebugApp();
     }
 
     /**
-     * Check if this is either a debuggable build of Android or of the host app.
-     * Use this to enable developer-only features.
+     * Check if this is either a debuggable build of Android or of the host app. Use this to enable
+     * developer-only features.
      */
     public static boolean isDebugAndroidOrApp() {
         return isDebugAndroid() || isDebugApp();
@@ -453,26 +234,15 @@
     }
 
     /**
-     * Checks if the application targets pre-release SDK U.
-     * This must be manually maintained as the SDK goes through finalization!
-     * Avoid depending on this if possible; this is only intended for WebView.
+     * Checks if the application targets pre-release SDK U. This must be manually maintained as the
+     * SDK goes through finalization! Avoid depending on this if possible; this is only intended for
+     * WebView.
      */
     public static boolean targetsAtLeastU() {
-        int target = ContextUtils.getApplicationContext().getApplicationInfo().targetSdkVersion;
-
-        // Logic for pre-API-finalization:
-        // return BuildCompat.isAtLeastU() && target == Build.VERSION_CODES.CUR_DEVELOPMENT;
-
-        // Logic for after API finalization but before public SDK release has to just hardcode the
-        // appropriate SDK integer. This will include Android builds with the finalized SDK, and
-        // also pre-API-finalization builds (because CUR_DEVELOPMENT == 10000).
-        // return target >= 34;
-
-        // Now that the public SDK is upstreamed we can use the defined constant. All users of this
-        // should now just inline this check themselves.
-        return target >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE;
+        return ApkInfo.targetsAtLeastU();
     }
 
+    @NullUnmarked
     public String getHostSigningCertSha256() {
         // We currently only make use of this certificate for calls from the storage access API
         // within WebView. So we rather lazy load this value to avoid impacting app startup.
@@ -513,7 +283,7 @@
         return PackageManager.GET_SIGNATURES;
     }
 
-    private Signature[] getPackageSignatures(PackageInfo pi) {
+    private Signature @Nullable [] getPackageSignatures(PackageInfo pi) {
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
             if (pi.signingInfo == null) {
                 return null;
diff --git a/tot/base/android/java/src/org/chromium/base/BundleUtils.java b/tot/base/android/java/src/org/chromium/base/BundleUtils.java
index b9862ac..d281702 100644
--- a/tot/base/android/java/src/org/chromium/base/BundleUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/BundleUtils.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.app.Activity;
 import android.content.Context;
 import android.content.ContextWrapper;
@@ -16,16 +18,17 @@
 import android.util.ArrayMap;
 import android.view.LayoutInflater;
 
-import androidx.annotation.Nullable;
 import androidx.annotation.RequiresApi;
 
 import dalvik.system.BaseDexClassLoader;
 import dalvik.system.PathClassLoader;
 
 import org.jni_zero.CalledByNative;
+import org.jni_zero.JniType;
 
 import org.chromium.base.metrics.RecordHistogram;
-import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.lang.reflect.Field;
 import java.util.ArrayList;
@@ -34,6 +37,7 @@
 import java.util.Map;
 
 /** Utils for working with android app bundles. */
+@NullMarked
 public class BundleUtils {
     private static final String TAG = "BundleUtils";
     private static final String LOADED_SPLITS_KEY = "split_compat_loaded_splits";
@@ -44,11 +48,13 @@
 
     private static final Map<String, ClassLoader> sInflationClassLoaders =
             Collections.synchronizedMap(new ArrayMap<>());
-    private static SplitCompatClassLoader sSplitCompatClassLoaderInstance;
+    private static @Nullable SplitCompatClassLoader sSplitCompatClassLoaderInstance;
 
     // List of splits that were loaded during the last run of chrome when
     // restoring from recents.
-    private static ArrayList<String> sSplitsToRestore;
+    private static @Nullable ArrayList<String> sSplitsToRestore;
+
+    private static @Nullable Boolean sIsBundle;
 
     public static void resetForTesting() {
         sCachedClassLoaders.clear();
@@ -58,12 +64,27 @@
     }
 
     @CalledByNative
-    private static boolean isBundleForNative() {
-        return BuildConfig.IS_BUNDLE;
+    public static boolean isBundle() {
+        if (sIsBundle == null) {
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+                ApplicationInfo appInfo = ContextUtils.getApplicationContext().getApplicationInfo();
+                String[] splitNames = appInfo.splitNames;
+                sIsBundle = splitNames != null && splitNames.length > 0;
+            } else {
+                sIsBundle = false;
+            }
+        }
+        return sIsBundle;
+    }
+
+    public static void setIsBundleForTesting(boolean newVal) {
+        Boolean oldVal = sIsBundle;
+        sIsBundle = newVal;
+        ResettersForTesting.register(() -> sIsBundle = oldVal);
     }
 
     @RequiresApi(api = Build.VERSION_CODES.O)
-    private static String getSplitApkPath(String splitName) {
+    private static @Nullable String getSplitApkPath(String splitName) {
         ApplicationInfo appInfo = ContextUtils.getApplicationContext().getApplicationInfo();
         String[] splitNames = appInfo.splitNames;
         if (splitNames == null) {
@@ -78,7 +99,7 @@
      * below O, where isolated splits are not supported.
      */
     public static boolean isIsolatedSplitInstalled(String splitName) {
-        if (!BuildConfig.IS_BUNDLE || Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
+        if (!isBundle() || Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
             return false;
         }
         return getSplitApkPath(splitName) != null;
@@ -92,7 +113,7 @@
      * from the base context will be returned.
      */
     public static Context createIsolatedSplitContext(String splitName) {
-        if (!BuildConfig.IS_BUNDLE) {
+        if (!isBundle()) {
             return ContextUtils.getApplicationContext();
         }
         try {
@@ -167,8 +188,8 @@
 
     /* Returns absolute path to a native library in a feature module. */
     @CalledByNative
-    @Nullable
-    public static String getNativeLibraryPath(String libraryName, String splitName) {
+    public static @Nullable @JniType("std::string") String getNativeLibraryPath(
+            @JniType("std::string") String libraryName, @JniType("std::string") String splitName) {
         try (StrictModeContext ignored = StrictModeContext.allowDiskReads()) {
             // Due to b/171269960 isolated split class loaders have an empty library path, so check
             // the base module class loader first which loaded BundleUtils. If the library is not
@@ -219,17 +240,13 @@
     }
 
     /**
-     * Constructs a new instance of the given class name. If the application context class loader
-     * can load the class, that class loader will be used, otherwise the class loader from the
-     * passed in context will be used.
+     * Constructs a new instance of the given class name. We create the classloader (or use a cached
+     * copy) of the split with the name passed in.
      */
-    public static Object newInstance(Context context, String className) {
-        Context appContext = ContextUtils.getApplicationContext();
-        if (appContext != null && canLoadClass(appContext.getClassLoader(), className)) {
-            context = appContext;
-        }
+    public static Object newInstance(String className, String splitName) {
+        ClassLoader classLoader = getOrCreateSplitClassLoader(splitName);
         try {
-            return context.getClassLoader().loadClass(className).newInstance();
+            return classLoader.loadClass(className).newInstance();
         } catch (ReflectiveOperationException e) {
             throw JavaUtils.throwUnchecked(e);
         }
@@ -266,7 +283,7 @@
      * Returns the ClassLoader for the given split, loading the split if it has not yet been loaded.
      */
     public static ClassLoader getOrCreateSplitClassLoader(String splitName) {
-        if (!BuildConfig.IS_BUNDLE) {
+        if (!isBundle()) {
             return BundleUtils.class.getClassLoader();
         }
         ClassLoader ret;
@@ -333,7 +350,8 @@
             Log.i(TAG, "Splits: %s", sSplitsToRestore);
         }
 
-        private Class<?> checkSplitsClassLoaders(String className) throws ClassNotFoundException {
+        private @Nullable Class<?> checkSplitsClassLoaders(String className)
+                throws ClassNotFoundException {
             for (ClassLoader cl : sInflationClassLoaders.values()) {
                 try {
                     return cl.loadClass(className);
@@ -375,7 +393,7 @@
 
         private void restoreSplitsClassLoaders() {
             // Load splits that were stored in the SavedInstanceState Bundle.
-            for (String splitName : sSplitsToRestore) {
+            for (String splitName : assumeNonNull(sSplitsToRestore)) {
                 if (!sInflationClassLoaders.containsKey(splitName)) {
                     registerSplitClassLoaderForInflation(splitName);
                 }
@@ -384,8 +402,7 @@
         }
     }
 
-    @Nullable
-    private static String getSplitApkLibraryPath(String libraryName, String splitName) {
+    private static @Nullable String getSplitApkLibraryPath(String libraryName, String splitName) {
         // If isolated splits aren't supported, the library should have already been found.
         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
             return null;
diff --git a/tot/base/android/java/src/org/chromium/base/Callback.java b/tot/base/android/java/src/org/chromium/base/Callback.java
index 8764426..4d56928 100644
--- a/tot/base/android/java/src/org/chromium/base/Callback.java
+++ b/tot/base/android/java/src/org/chromium/base/Callback.java
@@ -4,10 +4,11 @@
 
 package org.chromium.base;
 
-import androidx.annotation.Nullable;
-
 import org.jni_zero.CalledByNative;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.util.Optional;
 
 /**
@@ -15,8 +16,9 @@
  *
  * @param <T> The type of the computation's result.
  */
+@NullMarked
 @FunctionalInterface
-public interface Callback<T> {
+public interface Callback<T extends @Nullable Object> {
 
     /** Invoked with the result of a computation. */
     void onResult(T result);
@@ -41,7 +43,7 @@
      * @param callback The {@link Callback} to run.
      * @param object The payload to provide to the callback (may be null).
      */
-    static <T> void runNullSafe(@Nullable Callback<T> callback, @Nullable T object) {
+    static <T extends @Nullable Object> void runNullSafe(@Nullable Callback<T> callback, T object) {
         if (callback != null) callback.onResult(object);
     }
 
diff --git a/tot/base/android/java/src/org/chromium/base/CallbackController.java b/tot/base/android/java/src/org/chromium/base/CallbackController.java
index 8e8e07a..99a8208 100644
--- a/tot/base/android/java/src/org/chromium/base/CallbackController.java
+++ b/tot/base/android/java/src/org/chromium/base/CallbackController.java
@@ -4,12 +4,13 @@
 
 package org.chromium.base;
 
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
+import org.chromium.build.annotations.EnsuresNonNull;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+import org.chromium.build.annotations.RequiresNonNull;
 
 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
-import java.util.Objects;
 
 import javax.annotation.concurrent.GuardedBy;
 
@@ -79,6 +80,7 @@
  * mCallbackController = new CallbackController();  // Allows to start handing out new callbacks.
  * }</pre>
  */
+@NullMarked
 @SuppressWarnings({"NoSynchronizedThisCheck", "NoSynchronizedMethodCheck"})
 public final class CallbackController {
     /** Interface for cancelable objects tracked by this class. */
@@ -90,9 +92,9 @@
     /** Class wrapping a {@link Callback} interface with a {@link Cancelable} interface. */
     private class CancelableCallback<T> implements Cancelable, Callback<T> {
         @GuardedBy("CallbackController.this")
-        private Callback<T> mCallback;
+        private @Nullable Callback<T> mCallback;
 
-        private CancelableCallback(@NonNull Callback<T> callback) {
+        private CancelableCallback(Callback<T> callback) {
             mCallback = callback;
         }
 
@@ -115,9 +117,9 @@
     /** Class wrapping {@link Runnable} interface with a {@link Cancelable} interface. */
     private class CancelableRunnable implements Cancelable, Runnable {
         @GuardedBy("CallbackController.this")
-        private Runnable mRunnable;
+        private @Nullable Runnable mRunnable;
 
-        private CancelableRunnable(@NonNull Runnable runnable) {
+        private CancelableRunnable(Runnable runnable) {
             mRunnable = runnable;
         }
 
@@ -138,9 +140,8 @@
     }
 
     /** A list of cancelables created and cancelable by this object. */
-    @Nullable
     @GuardedBy("this")
-    private ArrayList<WeakReference<Cancelable>> mCancelables = new ArrayList<>();
+    private @Nullable ArrayList<WeakReference<Cancelable>> mCancelables = new ArrayList<>();
 
     /**
      * Wraps a provided {@link Callback} with a cancelable object that is tracked by this {@link
@@ -152,7 +153,7 @@
      * @param callback A callback that will be made cancelable.
      * @return A cancelable instance of the callback.
      */
-    public synchronized <T> Callback<T> makeCancelable(@NonNull Callback<T> callback) {
+    public synchronized <T> Callback<T> makeCancelable(Callback<T> callback) {
         checkNotCanceled();
         CancelableCallback<T> cancelable = new CancelableCallback<>(callback);
         addInternal(cancelable);
@@ -168,7 +169,7 @@
      * @param runnable A runnable that will be made cancelable.
      * @return A cancelable instance of the runnable.
      */
-    public synchronized Runnable makeCancelable(@NonNull Runnable runnable) {
+    public synchronized Runnable makeCancelable(Runnable runnable) {
         checkNotCanceled();
         CancelableRunnable cancelable = new CancelableRunnable(runnable);
         addInternal(cancelable);
@@ -176,6 +177,7 @@
     }
 
     @GuardedBy("this")
+    @RequiresNonNull("mCancelables")
     private void addInternal(Cancelable cancelable) {
         var cancelables = mCancelables;
         cancelables.add(new WeakReference<>(cancelable));
@@ -202,8 +204,8 @@
 
     /** If the cancelation already happened, throws an {@link IllegalStateException}. */
     @GuardedBy("this")
+    @EnsuresNonNull("mCancelables")
     private void checkNotCanceled() {
-        // Use NullPointerException because it optimizes well.
-        Objects.requireNonNull(mCancelables);
+        assert mCancelables != null;
     }
 }
diff --git a/tot/base/android/java/src/org/chromium/base/CallbackUtils.java b/tot/base/android/java/src/org/chromium/base/CallbackUtils.java
index 891dae7..fa6ab5d 100644
--- a/tot/base/android/java/src/org/chromium/base/CallbackUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/CallbackUtils.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Utilities for interacting with {@link Callback}s. */
+@NullMarked
 public class CallbackUtils {
     /**
      * @see #emptyCallback() to avoid unchecked generic checks.
diff --git a/tot/base/android/java/src/org/chromium/base/CancelableRunnable.java b/tot/base/android/java/src/org/chromium/base/CancelableRunnable.java
new file mode 100644
index 0000000..68163b8
--- /dev/null
+++ b/tot/base/android/java/src/org/chromium/base/CancelableRunnable.java
@@ -0,0 +1,40 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.base;
+
+import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
+/**
+ * CancelableRunnable is a Runnable class that can be canceled. A canceled task is not removed from
+ * the task queue - it instead becomes a noop.
+ *
+ * <p>This class is *not* threadsafe, and is only for canceling tasks from the thread on which it
+ * would be run.
+ */
+@NullMarked
+public class CancelableRunnable implements Runnable {
+    private @Nullable Runnable mRunnable;
+    private @Nullable Thread mExpectedThread;
+
+    public CancelableRunnable(Runnable runnable) {
+        mRunnable = runnable;
+    }
+
+    public void cancel() {
+        mRunnable = null;
+        if (BuildConfig.ENABLE_ASSERTS) {
+            mExpectedThread = Thread.currentThread();
+        }
+    }
+
+    @Override
+    public void run() {
+        assert mExpectedThread == null || Thread.currentThread() == mExpectedThread
+                : "Canceling thread: " + mExpectedThread.getName();
+        if (mRunnable != null) mRunnable.run();
+    }
+}
diff --git a/tot/base/android/java/src/org/chromium/base/CollectionUtil.java b/tot/base/android/java/src/org/chromium/base/CollectionUtil.java
index 01423d9..7b9769b 100644
--- a/tot/base/android/java/src/org/chromium/base/CollectionUtil.java
+++ b/tot/base/android/java/src/org/chromium/base/CollectionUtil.java
@@ -4,7 +4,7 @@
 
 package org.chromium.base;
 
-import androidx.annotation.NonNull;
+import org.chromium.build.annotations.NullMarked;
 
 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
@@ -13,10 +13,11 @@
 import java.util.List;
 
 /** Helpers for working with collections that do not already exist in JDK / Guava. */
+@NullMarked
 public final class CollectionUtil {
     private CollectionUtil() {}
 
-    public static int[] integerCollectionToIntArray(@NonNull Collection<Integer> collection) {
+    public static int[] integerCollectionToIntArray(Collection<Integer> collection) {
         int[] array = new int[collection.size()];
         int index = 0;
         for (int num : collection) {
diff --git a/tot/base/android/java/src/org/chromium/base/CommandLine.java b/tot/base/android/java/src/org/chromium/base/CommandLine.java
index 86bdccd..720e2d4 100644
--- a/tot/base/android/java/src/org/chromium/base/CommandLine.java
+++ b/tot/base/android/java/src/org/chromium/base/CommandLine.java
@@ -4,116 +4,52 @@
 
 package org.chromium.base;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.text.TextUtils;
 
-import androidx.annotation.Nullable;
 import androidx.annotation.VisibleForTesting;
 
 import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+import org.chromium.build.annotations.RequiresNonNull;
+
 import java.io.File;
 import java.io.FileReader;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
-import java.util.concurrent.atomic.AtomicReference;
 
 /**
  * Java mirror of base/command_line.h. Android applications don't have command line arguments.
  * Instead, they're "simulated" by reading a file at a specific location early during startup.
  * Applications each define their own files, e.g., ContentShellApplication.COMMAND_LINE_FILE.
  */
-public abstract class CommandLine {
-    // Public abstract interface, implemented in derived classes.
-    // All these methods reflect their native-side counterparts.
-    /**
-     *  Returns true if this command line contains the given switch.
-     *  (Switch names ARE case-sensitive).
-     */
-    public abstract boolean hasSwitch(String switchString);
-
-    /**
-     * Return the value associated with the given switch, or null.
-     *
-     * @param switchString The switch key to lookup. It should NOT start with '--' !
-     * @return switch value, or null if the switch is not set or set to empty.
-     */
-    public abstract @Nullable String getSwitchValue(String switchString);
-
-    /**
-     * Return the value associated with the given switch, or {@code defaultValue} if the switch was
-     * not specified.
-     *
-     * @param switchString The switch key to lookup. It should NOT start with '--' !
-     * @param defaultValue The default value to return if the switch isn't set.
-     * @return Switch value, or {@code defaultValue} if the switch is not set or set to empty.
-     */
-    public String getSwitchValue(String switchString, String defaultValue) {
-        String value = getSwitchValue(switchString);
-        return TextUtils.isEmpty(value) ? defaultValue : value;
-    }
-
-    /** Return a copy of all switches, along with their values. */
-    public abstract Map<String, String> getSwitches();
-
-    /**
-     * Append a switch to the command line. There is no guarantee this action happens before the
-     * switch is needed.
-     *
-     * @param switchString the switch to add. It should NOT start with '--' !
-     */
-    public abstract void appendSwitch(String switchString);
-
-    /**
-     * Append a switch and value to the command line.  There is no
-     * guarantee this action happens before the switch is needed.
-     * @param switchString the switch to add.  It should NOT start with '--' !
-     * @param value the value for this switch.
-     * For example, --foo=bar becomes 'foo', 'bar'.
-     */
-    public abstract void appendSwitchWithValue(String switchString, String value);
-
-    /**
-     * Append switch/value items in "command line" format (excluding argv[0] program name).
-     * E.g. { '--gofast', '--username=fred' }
-     * @param array an array of switch or switch/value items in command line format.
-     *   Unlike the other append routines, these switches SHOULD start with '--' .
-     *   Unlike init(), this does not include the program name in array[0].
-     */
-    public abstract void appendSwitchesAndArguments(String[] array);
-
-    /**
-     * Remove the switch from the command line.  If no such switch is present, this has no effect.
-     * @param switchString The switch key to lookup. It should NOT start with '--' !
-     */
-    public abstract void removeSwitch(String switchString);
-
-    /**
-     * Determine if the command line is bound to the native (JNI) implementation.
-     *
-     * @return true if the underlying implementation is delegating to the native command line.
-     */
-    public static boolean isNativeImplementationForTesting() {
-        return sCommandLine.get() instanceof NativeCommandLine;
-    }
-
-    private static final AtomicReference<CommandLine> sCommandLine = new AtomicReference<>();
+@NullMarked
+public class CommandLine {
+    private static final String TAG = "CommandLine";
+    private static final String SWITCH_PREFIX = "--";
+    private static final String SWITCH_TERMINATOR = SWITCH_PREFIX;
+    private static final String SWITCH_VALUE_SEPARATOR = "=";
+    private static @Nullable CommandLine sInstance;
 
     /**
      * @return true if the command line has already been initialized.
      */
     public static boolean isInitialized() {
-        return sCommandLine.get() != null;
+        return sInstance != null;
     }
 
     // Equivalent to CommandLine::ForCurrentProcess in C++.
     public static CommandLine getInstance() {
-        CommandLine commandLine = sCommandLine.get();
-        assert commandLine != null;
-        return commandLine;
+        assert sInstance != null;
+        return sInstance;
     }
 
     /**
@@ -122,9 +58,9 @@
      *
      * @param args command line flags in 'argv' format: args[0] is the program name.
      */
-    public static void init(@Nullable String[] args) {
-        assert !(sCommandLine.get() instanceof NativeCommandLine);
-        sCommandLine.set(new JavaCommandLine(args));
+    public static void init(String @Nullable [] args) {
+        assert sInstance == null || !sInstance.hasSwitchedToNative();
+        sInstance = new CommandLine(args);
     }
 
     /**
@@ -145,9 +81,9 @@
 
     /** For use by tests that test command-line functionality. */
     public static void resetForTesting(boolean initialize) {
-        CommandLine origCommandLine =
-                sCommandLine.getAndSet(initialize ? new JavaCommandLine(null) : null);
-        ResettersForTesting.register(() -> sCommandLine.set(origCommandLine));
+        CommandLine origCommandLine = sInstance;
+        sInstance = initialize ? new CommandLine(null) : null;
+        ResettersForTesting.register(() -> sInstance = origCommandLine);
     }
 
     /**
@@ -202,37 +138,31 @@
         return args.toArray(new String[args.size()]);
     }
 
-    private static final String TAG = "CommandLine";
-    private static final String SWITCH_PREFIX = "--";
-    private static final String SWITCH_TERMINATOR = SWITCH_PREFIX;
-    private static final String SWITCH_VALUE_SEPARATOR = "=";
-
     /**
      * Switch from Java->Native CommandLine implementation. If another thread is modifying the
      * command line when this happens, all bets are off (as per the native CommandLine).
      */
     public static void enableNativeProxy() {
-        JavaCommandLine prev = (JavaCommandLine) sCommandLine.get();
-        String[] args = prev == null ? new String[0] : prev.getCommandLineArguments();
-        CommandLineJni.get().init(args);
-        sCommandLine.set(new NativeCommandLine());
-        Log.v(TAG, "Switched to native command-line");
+        if (!isInitialized()) {
+            init(null);
+        }
+        getInstance().switchToNative();
     }
 
     /** Returns the list of current switches. Cannot be called after enableNativeProxy(). */
     public static String[] getJavaSwitchesForTesting() {
-        CommandLine commandLine = sCommandLine.get();
-        if (commandLine != null) {
-            return ((JavaCommandLine) commandLine).getCommandLineArguments();
+        CommandLine commandLine = sInstance;
+        if (commandLine == null) {
+            return new String[0];
         }
-        return new String[0];
+        return assumeNonNull(commandLine.mArgs).toArray(new String[0]);
     }
 
     /**
      * @param fileName the file to read in.
      * @return Array of chars read from the file, or null if the file cannot be read.
      */
-    private static char[] readFileAsUtf8(String fileName) {
+    private static char @Nullable [] readFileAsUtf8(String fileName) {
         File f = new File(fileName);
         try (FileReader reader = new FileReader(f)) {
             char[] buffer = new char[(int) f.length()];
@@ -244,181 +174,201 @@
         }
     }
 
-    private CommandLine() {}
+    private @Nullable HashMap<String, String> mSwitches = new HashMap<>();
+    private @Nullable ArrayList<String> mArgs = new ArrayList<>();
 
-    @VisibleForTesting
-    static class JavaCommandLine extends CommandLine {
-        private HashMap<String, String> mSwitches = new HashMap<String, String>();
-        private ArrayList<String> mArgs = new ArrayList<String>();
+    // The arguments begin at index 1, since index 0 contains the executable name.
+    private int mArgsBegin = 1;
 
-        // The arguments begin at index 1, since index 0 contains the executable name.
-        private int mArgsBegin = 1;
+    private CommandLine(String @Nullable [] args) {
+        assumeNonNull(mArgs); // https://github.com/uber/NullAway/issues/1135
+        // Invariant: we always have the argv[0] program name element.
+        if (args == null || args.length == 0 || args[0] == null) {
+            mArgs.add("");
+        } else {
+            mArgs.add(args[0]);
+            appendSwitchesInternal(args, 1);
+        }
+    }
 
-        JavaCommandLine(@Nullable String[] args) {
-            if (args == null || args.length == 0 || args[0] == null) {
-                mArgs.add("");
-            } else {
-                mArgs.add(args[0]);
-                appendSwitchesInternal(args, 1);
-            }
-            // Invariant: we always have the argv[0] program name element.
-            assert mArgs.size() > 0;
+    private void switchToNative() {
+        assert mArgs != null;
+        CommandLineJni.get().init(mArgs);
+        mArgs = null;
+        mSwitches = null;
+        Log.v(TAG, "Switched to native command-line");
+    }
+
+    /**
+     * Return the value associated with the given switch, or {@code defaultValue} if the switch was
+     * not specified.
+     *
+     * @param switchString The switch key to lookup. It should NOT start with '--' !
+     * @param defaultValue The default value to return if the switch isn't set.
+     * @return Switch value, or {@code defaultValue} if the switch is not set or set to empty.
+     */
+    public String getSwitchValue(String switchString, String defaultValue) {
+        String value = getSwitchValue(switchString);
+        return TextUtils.isEmpty(value) ? defaultValue : value;
+    }
+
+    /**
+     * Determine if the command line is bound to the native (JNI) implementation.
+     *
+     * @return true if the underlying implementation is delegating to the native command line.
+     */
+    public boolean hasSwitchedToNative() {
+        return mArgs == null;
+    }
+
+    /**
+     * Returns true if this command line contains the given switch. (Switch names ARE
+     * case-sensitive).
+     */
+    public boolean hasSwitch(String switchString) {
+        HashMap<String, String> switches = mSwitches;
+        return switches == null
+                ? CommandLineJni.get().hasSwitch(switchString)
+                : switches.containsKey(switchString);
+    }
+
+    /**
+     * Return the value associated with the given switch, or null.
+     *
+     * @param switchString The switch key to lookup. It should NOT start with '--' !
+     * @return switch value, or null if the switch is not set or set to empty.
+     */
+    public @Nullable String getSwitchValue(String switchString) {
+        HashMap<String, String> switches = mSwitches;
+        String ret =
+                switches == null
+                        ? CommandLineJni.get().getSwitchValue(switchString)
+                        : switches.get(switchString);
+        // Native does not distinguish empty values from key not present.
+        return TextUtils.isEmpty(ret) ? null : ret;
+    }
+
+    /** Return a copy of all switches, along with their values. */
+    public Map<String, String> getSwitches() {
+        HashMap<String, String> switches = mSwitches;
+        return switches == null ? CommandLineJni.get().getSwitches() : new HashMap<>(switches);
+    }
+
+    /**
+     * Append a switch to the command line. There is no guarantee this action happens before the
+     * switch is needed.
+     *
+     * @param switchString the switch to add. It should NOT start with '--' !
+     */
+    public void appendSwitch(String switchString) {
+        appendSwitchWithValue(switchString, null);
+    }
+
+    /**
+     * Append a switch and value to the command line. There is no guarantee this action happens
+     * before the switch is needed.
+     *
+     * @param switchString the switch to add. It should NOT start with '--' !
+     * @param value the value for this switch. For example, --foo=bar becomes 'foo', 'bar'.
+     */
+    public void appendSwitchWithValue(String switchString, @Nullable String value) {
+        if (value == null) {
+            value = "";
+        }
+        ArrayList<String> args = mArgs;
+        if (args == null) {
+            CommandLineJni.get().appendSwitchWithValue(switchString, value);
+            return;
+        }
+        assumeNonNull(mSwitches);
+        mSwitches.put(switchString, value);
+
+        // Append the switch and update the switches/arguments divider mArgsBegin.
+        String combinedSwitchString = SWITCH_PREFIX + switchString;
+        if (!value.isEmpty()) {
+            combinedSwitchString += SWITCH_VALUE_SEPARATOR + value;
         }
 
-        String[] getCommandLineArguments() {
-            return mArgs.toArray(new String[mArgs.size()]);
-        }
+        args.add(mArgsBegin++, combinedSwitchString);
+    }
 
-        @Override
-        public boolean hasSwitch(String switchString) {
-            return mSwitches.containsKey(switchString);
-        }
-
-        @Override
-        public @Nullable String getSwitchValue(String switchString) {
-            // This is slightly round about, but needed for consistency with the NativeCommandLine
-            // version which does not distinguish empty values from key not present.
-            String value = mSwitches.get(switchString);
-            return TextUtils.isEmpty(value) ? null : value;
-        }
-
-        @Override
-        public Map<String, String> getSwitches() {
-            return new HashMap<>(mSwitches);
-        }
-
-        @Override
-        public void appendSwitch(String switchString) {
-            appendSwitchWithValue(switchString, null);
-        }
-
-        /**
-         * Appends a switch to the current list.
-         *
-         * @param switchString the switch to add. It should NOT start with '--' !
-         * @param value the value for this switch.
-         */
-        @Override
-        public void appendSwitchWithValue(String switchString, @Nullable String value) {
-            mSwitches.put(switchString, value == null ? "" : value);
-
-            // Append the switch and update the switches/arguments divider mArgsBegin.
-            String combinedSwitchString = SWITCH_PREFIX + switchString;
-            if (value != null && !value.isEmpty()) {
-                combinedSwitchString += SWITCH_VALUE_SEPARATOR + value;
-            }
-
-            mArgs.add(mArgsBegin++, combinedSwitchString);
-        }
-
-        @Override
-        public void appendSwitchesAndArguments(String[] array) {
+    /**
+     * Append switch/value items in "command line" format (excluding argv[0] program name). E.g. {
+     * '--gofast', '--username=fred' }
+     *
+     * @param array an array of switch or switch/value items in command line format. Unlike the
+     *     other append routines, these switches SHOULD start with '--' . Unlike init(), this does
+     *     not include the program name in array[0].
+     */
+    public void appendSwitchesAndArguments(String[] array) {
+        if (mArgs == null) {
+            CommandLineJni.get().appendSwitchesAndArguments(array);
+        } else {
             appendSwitchesInternal(array, 0);
         }
+    }
 
-        // Add the specified arguments, but skipping the first |skipCount| elements.
-        private void appendSwitchesInternal(String[] array, int skipCount) {
-            boolean parseSwitches = true;
-            for (String arg : array) {
-                if (skipCount > 0) {
-                    --skipCount;
-                    continue;
-                }
-
-                if (arg.equals(SWITCH_TERMINATOR)) {
-                    parseSwitches = false;
-                }
-
-                if (parseSwitches && arg.startsWith(SWITCH_PREFIX)) {
-                    String[] parts = arg.split(SWITCH_VALUE_SEPARATOR, 2);
-                    String value = parts.length > 1 ? parts[1] : null;
-                    appendSwitchWithValue(parts[0].substring(SWITCH_PREFIX.length()), value);
-                } else {
-                    mArgs.add(arg);
-                }
+    // Add the specified arguments, but skipping the first |skipCount| elements.
+    @RequiresNonNull("mArgs")
+    private void appendSwitchesInternal(String[] array, int skipCount) {
+        boolean parseSwitches = true;
+        for (String arg : array) {
+            if (skipCount > 0) {
+                --skipCount;
+                continue;
             }
-        }
 
-        @Override
-        public void removeSwitch(String switchString) {
-            mSwitches.remove(switchString);
-            String combinedSwitchString = SWITCH_PREFIX + switchString;
+            if (arg.equals(SWITCH_TERMINATOR)) {
+                parseSwitches = false;
+            }
 
-            // Since we permit a switch to be added multiple times, we need to remove all instances
-            // from mArgs.
-            for (int i = mArgsBegin - 1; i > 0; i--) {
-                if (mArgs.get(i).equals(combinedSwitchString)
-                        || mArgs.get(i).startsWith(combinedSwitchString + SWITCH_VALUE_SEPARATOR)) {
-                    --mArgsBegin;
-                    mArgs.remove(i);
-                }
+            if (parseSwitches && arg.startsWith(SWITCH_PREFIX)) {
+                String[] parts = arg.split(SWITCH_VALUE_SEPARATOR, 2);
+                String value = parts.length > 1 ? parts[1] : null;
+                appendSwitchWithValue(parts[0].substring(SWITCH_PREFIX.length()), value);
+            } else {
+                mArgs.add(arg);
             }
         }
     }
 
-    private static class NativeCommandLine extends CommandLine {
-        @Override
-        public boolean hasSwitch(String switchString) {
-            return CommandLineJni.get().hasSwitch(switchString);
-        }
-
-        @Override
-        public @Nullable String getSwitchValue(String switchString) {
-            String ret = CommandLineJni.get().getSwitchValue(switchString);
-            return ret.isEmpty() ? null : ret;
-        }
-
-        @Override
-        public Map<String, String> getSwitches() {
-            HashMap<String, String> switches = new HashMap<String, String>();
-
-            // Iterate 2 array members at a time. JNI doesn't support returning Maps, but because
-            // key & value are both Strings, we can join them into a flattened String array:
-            // [ key1, value1, key2, value2, ... ]
-            String[] keysAndValues = CommandLineJni.get().getSwitchesFlattened();
-            assert keysAndValues.length % 2 == 0 : "must have same number of keys and values";
-            for (int i = 0; i < keysAndValues.length; i += 2) {
-                String key = keysAndValues[i];
-                String value = keysAndValues[i + 1];
-                switches.put(key, value);
-            }
-            return switches;
-        }
-
-        @Override
-        public void appendSwitch(String switchString) {
-            CommandLineJni.get().appendSwitch(switchString);
-        }
-
-        @Override
-        public void appendSwitchWithValue(String switchString, String value) {
-            CommandLineJni.get().appendSwitchWithValue(switchString, value == null ? "" : value);
-        }
-
-        @Override
-        public void appendSwitchesAndArguments(String[] array) {
-            CommandLineJni.get().appendSwitchesAndArguments(array);
-        }
-
-        @Override
-        public void removeSwitch(String switchString) {
+    /**
+     * Remove the switch from the command line. If no such switch is present, this has no effect.
+     *
+     * @param switchString The switch key to lookup. It should NOT start with '--' !
+     */
+    public void removeSwitch(String switchString) {
+        ArrayList<String> args = mArgs;
+        if (args == null) {
             CommandLineJni.get().removeSwitch(switchString);
+            return;
+        }
+        assumeNonNull(mSwitches);
+        mSwitches.remove(switchString);
+        String combinedSwitchString = SWITCH_PREFIX + switchString;
+
+        // Since we permit a switch to be added multiple times, we need to remove all instances
+        // from mArgs.
+        for (int i = mArgsBegin - 1; i > 0; i--) {
+            if (args.get(i).equals(combinedSwitchString)
+                    || args.get(i).startsWith(combinedSwitchString + SWITCH_VALUE_SEPARATOR)) {
+                --mArgsBegin;
+                args.remove(i);
+            }
         }
     }
 
     @NativeMethods
     interface Natives {
-        void init(@JniType("std::vector<std::string>") String[] args);
+        void init(@JniType("std::vector<std::string>") List<String> args);
 
         boolean hasSwitch(@JniType("std::string") String switchString);
 
         @JniType("std::string")
         String getSwitchValue(@JniType("std::string") String switchString);
 
-        @JniType("std::vector<std::string>")
-        String[] getSwitchesFlattened();
-
-        void appendSwitch(@JniType("std::string") String switchString);
+        @JniType("base::CommandLine::SwitchMap")
+        Map<String, String> getSwitches();
 
         void appendSwitchWithValue(
                 @JniType("std::string") String switchString, @JniType("std::string") String value);
diff --git a/tot/base/android/java/src/org/chromium/base/CommandLineInitUtil.java b/tot/base/android/java/src/org/chromium/base/CommandLineInitUtil.java
index 7ead455..73fe0a6 100644
--- a/tot/base/android/java/src/org/chromium/base/CommandLineInitUtil.java
+++ b/tot/base/android/java/src/org/chromium/base/CommandLineInitUtil.java
@@ -7,13 +7,14 @@
 import android.content.Context;
 import android.provider.Settings;
 
-import androidx.annotation.Nullable;
-
 import org.chromium.base.supplier.Supplier;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.io.File;
 
 /** Provides implementation of command line initialization for Android. */
+@NullMarked
 public final class CommandLineInitUtil {
     /**
      * The location of the command line file needs to be in a protected
@@ -33,7 +34,7 @@
     private static final String COMMAND_LINE_FILE_PATH_DEBUG_APP = "/data/local/tmp";
 
     /** The name of the command line file to pull arguments from. */
-    private static String sFilenameOverrideForTesting;
+    private static @Nullable String sFilenameOverrideForTesting;
 
     private CommandLineInitUtil() {}
 
@@ -78,7 +79,7 @@
         return context.getPackageName().equals(getDebugApp(context)) || BuildInfo.isDebugAndroid();
     }
 
-    private static String getDebugApp(Context context) {
+    private static @Nullable String getDebugApp(Context context) {
         boolean adbEnabled =
                 Settings.Global.getInt(context.getContentResolver(), Settings.Global.ADB_ENABLED, 0)
                         == 1;
diff --git a/tot/base/android/java/src/org/chromium/base/ContentUriUtils.java b/tot/base/android/java/src/org/chromium/base/ContentUriUtils.java
index 0d29c14..04166cf 100644
--- a/tot/base/android/java/src/org/chromium/base/ContentUriUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/ContentUriUtils.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.res.AssetFileDescriptor;
@@ -15,7 +17,6 @@
 import android.text.TextUtils;
 import android.webkit.MimeTypeMap;
 
-import androidx.annotation.Nullable;
 import androidx.documentfile.provider.DocumentFile;
 
 import org.jni_zero.CalledByNative;
@@ -23,11 +24,15 @@
 import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.io.IOException;
 import java.util.List;
 
 /** This class provides methods to access content URI schemes. */
 @JNINamespace("base")
+@NullMarked
 public abstract class ContentUriUtils {
     private static final String TAG = "ContentUriUtils";
     private static final String PATH_TREE = "tree";
@@ -103,6 +108,7 @@
      * @param nativeVector vector to populate with results via Natives#addFileInfoToVector(). Called
      *     only if file is found.
      */
+    @SuppressWarnings("NullAway") // Using broad try/catch to catch NullPointerException
     private static void populateFileInfo(String uriString, boolean listFiles, long nativeVector) {
         String[] columns = {
             DocumentsContract.Document.COLUMN_DOCUMENT_ID,
@@ -112,11 +118,10 @@
             DocumentsContract.Document.COLUMN_LAST_MODIFIED,
         };
 
+        Uri uri = Uri.parse(uriString);
         Uri queryUri = null;
         try {
-            DocumentFile file =
-                    DocumentFile.fromTreeUri(
-                            ContextUtils.getApplicationContext(), Uri.parse(uriString));
+            DocumentFile file = DocumentFile.fromTreeUri(ContextUtils.getApplicationContext(), uri);
             if (file != null) {
                 if (listFiles) {
                     String documentId = DocumentsContract.getDocumentId(file.getUri());
@@ -128,11 +133,17 @@
                 }
             }
         } catch (Exception e) {
-            Log.w(TAG, "Failed to get Documents URI for %s, listFiles=%s", uriString, listFiles);
+            // Ignore.
         }
+
         if (queryUri == null) {
-            // If URI is not a documents URI, then try to get size from AFD.
-            if (!listFiles) {
+            if (listFiles) {
+                return;
+            }
+            if (DocumentsContract.isDocumentUri(ContextUtils.getApplicationContext(), uri)) {
+                queryUri = uri;
+            } else {
+                // If URI is not a documents URI, then try to get size from AFD.
                 AssetFileDescriptor afd = getAssetFileDescriptor(uriString, "r");
                 if (afd != null) {
                     ContentUriUtilsJni.get()
@@ -140,19 +151,24 @@
                                     nativeVector, uriString, null, false, afd.getLength(), 0);
                     StreamUtil.closeQuietly(afd);
                 }
+                return;
             }
-            return;
         }
 
         ContentResolver resolver = ContextUtils.getApplicationContext().getContentResolver();
-        try (Cursor c = resolver.query(queryUri, columns, null, null, null)) {
+        try (Cursor c = assumeNonNull(resolver.query(queryUri, columns, null, null, null))) {
             while (c.moveToNext()) {
-                String uri =
-                        c.isNull(0)
-                                ? null
-                                : DocumentsContract.buildDocumentUriUsingTree(
-                                                queryUri, c.getString(0))
-                                        .toString();
+                String path = null;
+                if (listFiles) {
+                    path =
+                            c.isNull(0)
+                                    ? null
+                                    : DocumentsContract.buildDocumentUriUsingTree(
+                                                    queryUri, c.getString(0))
+                                            .toString();
+                } else {
+                    path = uriString;
+                }
                 String displayName = c.isNull(1) ? null : c.getString(1);
                 boolean isDirectory =
                         !c.isNull(2)
@@ -161,7 +177,7 @@
                 long lastModified = c.isNull(4) ? 0 : c.getLong(4);
                 ContentUriUtilsJni.get()
                         .addFileInfoToVector(
-                                nativeVector, uri, displayName, isDirectory, size, lastModified);
+                                nativeVector, path, displayName, isDirectory, size, lastModified);
             }
         } catch (Exception e) {
             Log.w(TAG, "Failed query for uri=" + uriString + ", listFiles=" + listFiles, e);
@@ -211,9 +227,9 @@
      * @param uriString the content URI to look up.
      * @return MIME type or null if the input params are empty or invalid.
      */
-    @Nullable
     @CalledByNative
-    public static String getMimeType(@JniType("std::string") String uriString) {
+    public static @Nullable @JniType("std::string") String getMimeType(
+            @JniType("std::string") String uriString) {
         ContentResolver resolver = ContextUtils.getApplicationContext().getContentResolver();
         Uri uri = Uri.parse(uriString);
         if (isVirtualDocument(uri)) {
@@ -232,8 +248,8 @@
      *     security issues.
      * @return AssetFileDescriptor of the content URI, or NULL if the file does not exist.
      */
-    @Nullable
-    private static AssetFileDescriptor getAssetFileDescriptor(String uriString, String mode) {
+    private static @Nullable AssetFileDescriptor getAssetFileDescriptor(
+            String uriString, String mode) {
         if ("w".equals(mode)) {
             Log.e(TAG, "Cannot open files with mode 'w'");
             return null;
@@ -272,6 +288,7 @@
      * @return the display name of the @code uri if present in the database or an empty string
      *     otherwise.
      */
+    @SuppressWarnings("NullAway") // Using broad try/catch to catch NullPointerException
     public static String getDisplayName(Uri uri, Context context, String columnField) {
         if (uri == null) return "";
 
@@ -328,9 +345,8 @@
      * @param uriString the content URI to look up.
      * @return the display name of the uri if present in the database or null otherwise.
      */
-    @Nullable
     @CalledByNative
-    public static String maybeGetDisplayName(@JniType("std::string") String uriString) {
+    public static @Nullable String maybeGetDisplayName(@JniType("std::string") String uriString) {
         Uri uri = Uri.parse(uriString);
 
         try {
@@ -435,9 +451,8 @@
      * @return uri
      * @see DocumentsContract#buildDocumentUriUsingTree(Uri, String)
      */
-    @Nullable
     @CalledByNative
-    public static String buildDocumentUriUsingTree(
+    public static @Nullable @JniType("std::string") String buildDocumentUriUsingTree(
             @JniType("std::string") String treeUri,
             @JniType("std::string") String encodedDocumentId) {
         try {
@@ -460,9 +475,8 @@
      * @param create set to true if document should be created if it doesn't exist.
      * @return Uri or null if no match is found and create is not set.
      */
-    @Nullable
     @CalledByNative
-    public static String getChildDocumentOrQuery(
+    public static @Nullable @JniType("std::string") String getChildDocumentOrQuery(
             @JniType("std::string") String parentUri,
             @JniType("std::string") String displayName,
             @JniType("std::string") String mimeType,
@@ -518,8 +532,8 @@
      * @param displayName the display name of the document to find.
      * @return the child document if found, or null.
      */
-    private static Uri findChild(
-            String authority, String tree, String parentDocumentId, String displayName) {
+    private static @Nullable Uri findChild(
+            @Nullable String authority, String tree, String parentDocumentId, String displayName) {
         ContentResolver resolver = ContextUtils.getApplicationContext().getContentResolver();
         String[] columns = {
             DocumentsContract.Document.COLUMN_DISPLAY_NAME,
@@ -530,7 +544,8 @@
         // Use a selection to match displayName, but don't trust that it actually works.
         String selection = String.format("%s = ?", DocumentsContract.Document.COLUMN_DISPLAY_NAME);
         String[] selectionArgs = {displayName};
-        try (Cursor c = resolver.query(queryUri, columns, selection, selectionArgs, null)) {
+        try (Cursor c =
+                assumeNonNull(resolver.query(queryUri, columns, selection, selectionArgs, null))) {
             while (c.moveToNext()) {
                 // Verify display-name matches, and we have a valid docid.
                 if (c.isNull(0) || c.isNull(1) || !displayName.equals(c.getString(0))) {
@@ -573,8 +588,9 @@
      * @param create if true, the document will be created if it does not exist.
      * @return The URI of the created document or null
      */
+    @SuppressWarnings("NullAway") // Using broad try/catch to catch NullPointerException
     @CalledByNative
-    private static String getDocumentFromQuery(
+    private static @Nullable @JniType("std::string") String getDocumentFromQuery(
             @JniType("std::string") String queryUriString, boolean create) {
         if (!isCreateChildDocumentQuery(queryUriString)) {
             return null;
@@ -613,8 +629,8 @@
     interface Natives {
         void addFileInfoToVector(
                 long vectorPointer,
-                String uri,
-                String displayName,
+                @Nullable @JniType("std::string") String uri,
+                @Nullable @JniType("std::string") String displayName,
                 boolean isDirectory,
                 long size,
                 long lastModified);
diff --git a/tot/base/android/java/src/org/chromium/base/ContextUtils.java b/tot/base/android/java/src/org/chromium/base/ContextUtils.java
index 5b33964..4c5ab6f 100644
--- a/tot/base/android/java/src/org/chromium/base/ContextUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/ContextUtils.java
@@ -17,23 +17,24 @@
 import android.os.Process;
 import android.preference.PreferenceManager;
 
-import androidx.annotation.Nullable;
-
 import org.jni_zero.JNINamespace;
 
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /** This class provides Android application context related utility methods. */
 @JNINamespace("base::android")
+@NullMarked
 public class ContextUtils {
     private static final String TAG = "ContextUtils";
-    private static Context sApplicationContext;
+    private static @Nullable Context sApplicationContext;
 
     /**
      * Flag for {@link Context#registerReceiver}: The receiver can receive broadcasts from other
      * Apps. Has the same behavior as marking a statically registered receiver with "exported=true".
      *
-     * TODO(mthiesse): Move to ApiHelperForT when we build against T SDK.
+     * <p>TODO(mthiesse): Move to ApiHelperForT when we build against T SDK.
      */
     public static final int RECEIVER_EXPORTED = 0x2;
 
@@ -48,16 +49,18 @@
     /**
      * Get the Android application context.
      *
-     * Under normal circumstances there is only one application context in a process, so it's safe
-     * to treat this as a global. In WebView it's possible for more than one app using WebView to be
-     * running in a single process, but this mechanism is rarely used and this is not the only
+     * <p>Under normal circumstances there is only one application context in a process, so it's
+     * safe to treat this as a global. In WebView it's possible for more than one app using WebView
+     * to be running in a single process, but this mechanism is rarely used and this is not the only
      * problem in that scenario, so we don't currently forbid using it as a global.
      *
-     * Do not downcast the context returned by this method to Application (or any subclass). It may
-     * not be an Application object; it may be wrapped in a ContextWrapper. The only assumption you
-     * may make is that it is a Context whose lifetime is the same as the lifetime of the process.
+     * <p>Do not downcast the context returned by this method to Application (or any subclass). It
+     * may not be an Application object; it may be wrapped in a ContextWrapper. The only assumption
+     * you may make is that it is a Context whose lifetime is the same as the lifetime of the
+     * process.
      */
     public static Context getApplicationContext() {
+        assert sApplicationContext != null;
         return sApplicationContext;
     }
 
@@ -88,7 +91,7 @@
         // This may need to create the prefs directory if we've never used shared prefs before, so
         // allow disk writes. This is rare but can happen if code used early in startup reads prefs.
         try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) {
-            return PreferenceManager.getDefaultSharedPreferences(sApplicationContext);
+            return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
         }
     }
 
@@ -216,14 +219,17 @@
      * <p>
      * You can unregister receivers using the normal {@link Context#unregisterReceiver} method.
      */
-    public static Intent registerProtectedBroadcastReceiver(
-            Context context, BroadcastReceiver receiver, IntentFilter filter) {
+    public static @Nullable Intent registerProtectedBroadcastReceiver(
+            Context context, @Nullable BroadcastReceiver receiver, IntentFilter filter) {
         return registerBroadcastReceiver(
                 context, receiver, filter, /* permission= */ null, /* scheduler= */ null, 0);
     }
 
-    public static Intent registerProtectedBroadcastReceiver(
-            Context context, BroadcastReceiver receiver, IntentFilter filter, Handler scheduler) {
+    public static @Nullable Intent registerProtectedBroadcastReceiver(
+            Context context,
+            @Nullable BroadcastReceiver receiver,
+            IntentFilter filter,
+            Handler scheduler) {
         return registerBroadcastReceiver(
                 context, receiver, filter, /* permission= */ null, scheduler, 0);
     }
@@ -240,8 +246,11 @@
      * <p>
      * You can unregister receivers using the normal {@link Context#unregisterReceiver} method.
      */
-    public static Intent registerExportedBroadcastReceiver(
-            Context context, BroadcastReceiver receiver, IntentFilter filter, String permission) {
+    public static @Nullable Intent registerExportedBroadcastReceiver(
+            Context context,
+            @Nullable BroadcastReceiver receiver,
+            IntentFilter filter,
+            @Nullable String permission) {
         return registerBroadcastReceiver(
                 context, receiver, filter, permission, /* scheduler= */ null, RECEIVER_EXPORTED);
     }
@@ -278,8 +287,8 @@
      * <p>
      * You can unregister receivers using the normal {@link Context#unregisterReceiver} method.
      */
-    public static Intent registerNonExportedBroadcastReceiver(
-            Context context, BroadcastReceiver receiver, IntentFilter filter) {
+    public static @Nullable Intent registerNonExportedBroadcastReceiver(
+            Context context, @Nullable BroadcastReceiver receiver, IntentFilter filter) {
         return registerBroadcastReceiver(
                 context,
                 receiver,
@@ -289,8 +298,11 @@
                 RECEIVER_NOT_EXPORTED);
     }
 
-    public static Intent registerNonExportedBroadcastReceiver(
-            Context context, BroadcastReceiver receiver, IntentFilter filter, Handler scheduler) {
+    public static @Nullable Intent registerNonExportedBroadcastReceiver(
+            Context context,
+            @Nullable BroadcastReceiver receiver,
+            IntentFilter filter,
+            @Nullable Handler scheduler) {
         return registerBroadcastReceiver(
                 context,
                 receiver,
@@ -300,12 +312,12 @@
                 RECEIVER_NOT_EXPORTED);
     }
 
-    private static Intent registerBroadcastReceiver(
+    private static @Nullable Intent registerBroadcastReceiver(
             Context context,
-            BroadcastReceiver receiver,
+            @Nullable BroadcastReceiver receiver,
             IntentFilter filter,
-            String permission,
-            Handler scheduler,
+            @Nullable String permission,
+            @Nullable Handler scheduler,
             int flags) {
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
             return context.registerReceiver(receiver, filter, permission, scheduler, flags);
diff --git a/tot/base/android/java/src/org/chromium/base/CpuFeatures.java b/tot/base/android/java/src/org/chromium/base/CpuFeatures.java
index b2d9fe1..dd918ab 100644
--- a/tot/base/android/java/src/org/chromium/base/CpuFeatures.java
+++ b/tot/base/android/java/src/org/chromium/base/CpuFeatures.java
@@ -7,6 +7,8 @@
 import org.jni_zero.JNINamespace;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+
 // The only purpose of this class is to allow sending CPU properties
 // from the browser process to sandboxed renderer processes. This is
 // needed because sandboxed processes cannot, on ARM, query the kernel
@@ -20,6 +22,7 @@
 // library. The exact CPU features bits are never used in Java so
 // there is no point in duplicating their definitions here.
 //
+@NullMarked
 @JNINamespace("base::android")
 public abstract class CpuFeatures {
     /** Return the number of CPU Cores on the device. */
diff --git a/tot/base/android/java/src/org/chromium/base/DeviceInfo.java b/tot/base/android/java/src/org/chromium/base/DeviceInfo.java
new file mode 100644
index 0000000..d4be4a6
--- /dev/null
+++ b/tot/base/android/java/src/org/chromium/base/DeviceInfo.java
@@ -0,0 +1,205 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.base;
+
+import static android.content.Context.UI_MODE_SERVICE;
+
+import android.app.UiModeManager;
+import android.content.Context;
+import android.content.pm.FeatureInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.res.Configuration;
+import android.os.Build;
+import android.os.Build.VERSION_CODES;
+
+import androidx.annotation.GuardedBy;
+
+import org.jni_zero.CalledByNative;
+import org.jni_zero.CalledByNativeForTesting;
+import org.jni_zero.JNINamespace;
+import org.jni_zero.JniType;
+import org.jni_zero.NativeMethods;
+
+import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
+/** DeviceInfo is a utility class to access the device-related information. */
+@JNINamespace("base::android::device_info")
+@NullMarked
+public final class DeviceInfo {
+    private static final String TAG = "DeviceInfo";
+
+    private static @Nullable String sGmsVersionCodeForTesting;
+    private static boolean sInitialized;
+
+    /** The versionCode of Play Services. Can be overridden in tests. */
+    private String mGmsVersionCode;
+
+    /** Whether we're running on Android TV or not */
+    private final boolean mIsTv;
+
+    /** Whether we're running on an Android Automotive OS device or not. */
+    private final boolean mIsAutomotive;
+
+    /** Whether we're running on an Android Foldable OS device or not. */
+    private final boolean mIsFoldable;
+
+    /** Whether we're running on an Android Desktop OS device or not. */
+    private final boolean mIsDesktop;
+
+    /**
+     * version of the FEATURE_VULKAN_DEQP_LEVEL, if available. Queried only on Android T or above
+     */
+    private final int mVulkanDeqpLevel;
+
+    @GuardedBy("CREATION_LOCK")
+    private static @Nullable DeviceInfo sInstance;
+
+    private static final Object CREATION_LOCK = new Object();
+
+    // Called by the native code to retrieve field values. There is no easy way to
+    // return several fields from Java to native, so instead this calls back into
+    // native, passing the fields as parameters to a native function.
+    // The native code expects native `fillFields()` to be called inline from this
+    // function.
+    @CalledByNative
+    private static void nativeReadyForFields() {
+        DeviceInfoJni.get()
+                .fillFields(
+                        /* gmsVersionCode= */ getGmsVersionCode(),
+                        /* isTV= */ isTV(),
+                        /* isAutomotive= */ isAutomotive(),
+                        /* isFoldable= */ isFoldable(),
+                        /* isDesktop= */ isDesktop(),
+                        /* vulkanDeqpLevel= */ getVulkanDeqpLevel());
+    }
+
+    public static String getGmsVersionCode() {
+        return sGmsVersionCodeForTesting == null
+                ? getInstance().mGmsVersionCode
+                : sGmsVersionCodeForTesting;
+    }
+
+    @CalledByNativeForTesting
+    public static void setGmsVersionCodeForTest(@JniType("std::string") String gmsVersionCode) {
+        sGmsVersionCodeForTesting = gmsVersionCode;
+    }
+
+    public static boolean isTV() {
+        return getInstance().mIsTv;
+    }
+
+    public static boolean isAutomotive() {
+        return getInstance().mIsAutomotive;
+    }
+
+    public static boolean isFoldable() {
+        return getInstance().mIsFoldable;
+    }
+
+    public static boolean isDesktop() {
+        return getInstance().mIsDesktop;
+    }
+
+    public static int getVulkanDeqpLevel() {
+        return getInstance().mVulkanDeqpLevel;
+    }
+
+    public static boolean isInitializedForTesting() {
+        return sInitialized;
+    }
+
+    private static DeviceInfo getInstance() {
+        // Some tests mock out things BuildInfo is based on, so disable caching in tests to ensure
+        // such mocking is not defeated by caching.
+        if (BuildConfig.IS_FOR_TEST) {
+            return new DeviceInfo();
+        }
+
+        synchronized (CREATION_LOCK) {
+            if (sInstance == null) {
+                sInstance = new DeviceInfo();
+            }
+            return sInstance;
+        }
+    }
+
+    /**
+     * Return the "long" version code of the given PackageInfo. Does the right thing for
+     * before/after Android P when this got wider.
+     */
+    public static long packageVersionCode(PackageInfo pi) {
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
+            return pi.getLongVersionCode();
+        } else {
+            return pi.versionCode;
+        }
+    }
+
+    private DeviceInfo() {
+        sInitialized = true;
+        PackageInfo gmsPackageInfo = PackageUtils.getPackageInfo("com.google.android.gms", 0);
+        mGmsVersionCode =
+                gmsPackageInfo != null
+                        ? String.valueOf(packageVersionCode(gmsPackageInfo))
+                        : "gms versionCode not available.";
+
+        Context appContext = ContextUtils.getApplicationContext();
+        PackageManager pm = appContext.getPackageManager();
+        // See https://developer.android.com/training/tv/start/hardware.html#runtime-check.
+        UiModeManager uiModeManager = (UiModeManager) appContext.getSystemService(UI_MODE_SERVICE);
+        mIsTv =
+                uiModeManager != null
+                        && uiModeManager.getCurrentModeType()
+                                == Configuration.UI_MODE_TYPE_TELEVISION;
+
+        boolean isAutomotive;
+        try {
+            isAutomotive = pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
+        } catch (SecurityException e) {
+            Log.e(TAG, "Unable to query for Automotive system feature", e);
+
+            // `hasSystemFeature` can possibly throw an exception on modified instances of
+            // Android. In this case, assume the device is not a car since automotive vehicles
+            // should not have such a modification.
+            isAutomotive = false;
+        }
+        mIsAutomotive = isAutomotive;
+
+        // Detect whether device is foldable.
+        mIsFoldable =
+                Build.VERSION.SDK_INT >= VERSION_CODES.R
+                        && pm.hasSystemFeature(PackageManager.FEATURE_SENSOR_HINGE_ANGLE);
+
+        mIsDesktop = pm.hasSystemFeature(PackageManager.FEATURE_PC);
+
+        int vulkanLevel = 0;
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+            FeatureInfo[] features = pm.getSystemAvailableFeatures();
+            if (features != null) {
+                for (FeatureInfo feature : features) {
+                    if (PackageManager.FEATURE_VULKAN_DEQP_LEVEL.equals(feature.name)) {
+                        vulkanLevel = feature.version;
+                        break;
+                    }
+                }
+            }
+        }
+        mVulkanDeqpLevel = vulkanLevel;
+    }
+
+    @NativeMethods
+    interface Natives {
+        void fillFields(
+                String gmsVersionCode,
+                boolean isTV,
+                boolean isAutomotive,
+                boolean isFoldable,
+                boolean isDesktop,
+                int vulkanDeqpLevel);
+    }
+}
diff --git a/tot/base/android/java/src/org/chromium/base/DiscardableReferencePool.java b/tot/base/android/java/src/org/chromium/base/DiscardableReferencePool.java
index 6a84e43..e69288c 100644
--- a/tot/base/android/java/src/org/chromium/base/DiscardableReferencePool.java
+++ b/tot/base/android/java/src/org/chromium/base/DiscardableReferencePool.java
@@ -4,7 +4,8 @@
 
 package org.chromium.base;
 
-import androidx.annotation.Nullable;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.Collections;
 import java.util.Set;
@@ -23,6 +24,7 @@
  * <p>This class and its references are not thread-safe and should not be used simultaneously by
  * multiple threads.
  */
+@NullMarked
 public class DiscardableReferencePool {
     /**
      * The underlying data storage. The wildcard type parameter allows using a single pool for
@@ -40,7 +42,7 @@
      * @param <T> The type of the object.
      */
     public static class DiscardableReference<T> {
-        @Nullable private T mPayload;
+        private @Nullable T mPayload;
 
         private DiscardableReference(T payload) {
             assert payload != null;
@@ -50,8 +52,7 @@
         /**
          * @return The referent, or null if the pool has been drained.
          */
-        @Nullable
-        public T get() {
+        public @Nullable T get() {
             return mPayload;
         }
 
diff --git a/tot/base/android/java/src/org/chromium/base/EarlyTraceEvent.java b/tot/base/android/java/src/org/chromium/base/EarlyTraceEvent.java
index d7510ac..fbf51ed 100644
--- a/tot/base/android/java/src/org/chromium/base/EarlyTraceEvent.java
+++ b/tot/base/android/java/src/org/chromium/base/EarlyTraceEvent.java
@@ -12,8 +12,13 @@
 
 import org.jni_zero.CalledByNative;
 import org.jni_zero.JNINamespace;
+import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.EnsuresNonNullIf;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.io.File;
 import java.util.ArrayList;
 import java.util.List;
@@ -23,20 +28,21 @@
 /**
  * Support for early tracing, before the native library is loaded.
  *
- * Note that arguments are not currently supported for early events, but could
- * be added in the future.
+ * <p>Note that arguments are not currently supported for early events, but could be added in the
+ * future.
  *
- * Events recorded here are buffered in Java until the native library is available, at which point
- * they are flushed to the native side and regular java tracing (TraceEvent) takes over.
+ * <p>Events recorded here are buffered in Java until the native library is available, at which
+ * point they are flushed to the native side and regular java tracing (TraceEvent) takes over.
  *
- * Locking: This class is threadsafe. It is enabled when general tracing is, and then disabled when
- *          tracing is enabled from the native side. At this point, buffered events are flushed to
- *          the native side and then early tracing is permanently disabled after dumping the events.
+ * <p>Locking: This class is threadsafe. It is enabled when general tracing is, and then disabled
+ * when tracing is enabled from the native side. At this point, buffered events are flushed to the
+ * native side and then early tracing is permanently disabled after dumping the events.
  *
- * Like the TraceEvent, the event name of the trace events must be a string literal or a |static
+ * <p>Like the TraceEvent, the event name of the trace events must be a string literal or a |static
  * final String| class member. Otherwise NoDynamicStringsInTraceEventCheck error will be thrown.
  */
 @JNINamespace("base::android")
+@NullMarked
 public class EarlyTraceEvent {
     /** Single trace event. */
     @VisibleForTesting
@@ -135,11 +141,11 @@
     // Not final because in many configurations these objects are not used.
     @GuardedBy("sLock")
     @VisibleForTesting
-    static List<Event> sEvents;
+    static @Nullable List<Event> sEvents;
 
     @GuardedBy("sLock")
     @VisibleForTesting
-    static List<AsyncEvent> sAsyncEvents;
+    static @Nullable List<AsyncEvent> sAsyncEvents;
 
     @GuardedBy("sLock")
     @VisibleForTesting
@@ -259,6 +265,8 @@
         }
     }
 
+    @EnsuresNonNullIf({"sEvents", "sAsyncEvents"})
+    @SuppressWarnings("NullAway")
     static boolean enabled() {
         return sState == STATE_ENABLED;
     }
@@ -351,6 +359,7 @@
     static List<Event> getMatchingCompletedEventsForTesting(String eventName) {
         synchronized (sLock) {
             List<Event> matchingEvents = new ArrayList<Event>();
+            if (!enabled()) return matchingEvents;
             for (Event evt : EarlyTraceEvent.sEvents) {
                 if (evt.mName.equals(eventName)) {
                     matchingEvents.add(evt);
@@ -416,17 +425,32 @@
 
     @NativeMethods
     interface Natives {
-        void recordEarlyBeginEvent(String name, long timeNanos, int threadId, long threadMillis);
+        void recordEarlyBeginEvent(
+                @JniType("std::string") String name,
+                long timeNanos,
+                int threadId,
+                long threadMillis);
 
-        void recordEarlyEndEvent(String name, long timeNanos, int threadId, long threadMillis);
+        void recordEarlyEndEvent(
+                @JniType("std::string") String name,
+                long timeNanos,
+                int threadId,
+                long threadMillis);
 
         void recordEarlyToplevelBeginEvent(
-                String name, long timeNanos, int threadId, long threadMillis);
+                @JniType("std::string") String name,
+                long timeNanos,
+                int threadId,
+                long threadMillis);
 
         void recordEarlyToplevelEndEvent(
-                String name, long timeNanos, int threadId, long threadMillis);
+                @JniType("std::string") String name,
+                long timeNanos,
+                int threadId,
+                long threadMillis);
 
-        void recordEarlyAsyncBeginEvent(String name, long id, long timeNanos);
+        void recordEarlyAsyncBeginEvent(
+                @JniType("std::string") String name, long id, long timeNanos);
 
         void recordEarlyAsyncEndEvent(long id, long timeNanos);
     }
diff --git a/tot/base/android/java/src/org/chromium/base/EventLog.java b/tot/base/android/java/src/org/chromium/base/EventLog.java
index 6f09010..979ade9 100644
--- a/tot/base/android/java/src/org/chromium/base/EventLog.java
+++ b/tot/base/android/java/src/org/chromium/base/EventLog.java
@@ -7,7 +7,10 @@
 import org.jni_zero.CalledByNative;
 import org.jni_zero.JNINamespace;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** A simple interface to Android's EventLog to be used by native code. */
+@NullMarked
 @JNINamespace("base::android")
 public class EventLog {
 
diff --git a/tot/base/android/java/src/org/chromium/base/FeatureList.java b/tot/base/android/java/src/org/chromium/base/FeatureList.java
index 1958639..28714e8 100644
--- a/tot/base/android/java/src/org/chromium/base/FeatureList.java
+++ b/tot/base/android/java/src/org/chromium/base/FeatureList.java
@@ -4,172 +4,35 @@
 
 package org.chromium.base;
 
-import android.util.ArrayMap;
-
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
 import androidx.annotation.VisibleForTesting;
 
 import org.jni_zero.JNINamespace;
 import org.jni_zero.NativeMethods;
 
 import org.chromium.base.library_loader.LibraryLoader;
+import org.chromium.build.annotations.NullMarked;
 
-import java.util.HashMap;
-import java.util.Map;
-
-/** Provides shared capabilities for feature flag support. */
+/** Provides the state of the native FeatureList. */
+@NullMarked
 @JNINamespace("base::android")
 public class FeatureList {
-    /** Test value overrides for tests without native. */
-    public static class TestValues {
-        private Map<String, Boolean> mFeatureFlags = new HashMap<>();
-        private Map<String, Map<String, String>> mFieldTrialParams = new HashMap<>();
-
-        /** Constructor. */
-        public TestValues() {}
-
-        /** Set overrides for feature flags. */
-        public void setFeatureFlagsOverride(Map<String, Boolean> featureFlags) {
-            mFeatureFlags = featureFlags;
-        }
-
-        /** Add an override for a feature flag. */
-        public void addFeatureFlagOverride(String featureName, boolean testValue) {
-            mFeatureFlags.put(featureName, testValue);
-        }
-
-        /** Add an override for a field trial parameter. */
-        public void addFieldTrialParamOverride(
-                String featureName, String paramName, String testValue) {
-            Map<String, String> featureParams = mFieldTrialParams.get(featureName);
-            if (featureParams == null) {
-                featureParams = new ArrayMap<>();
-                mFieldTrialParams.put(featureName, featureParams);
-            }
-            featureParams.put(paramName, testValue);
-        }
-
-        /**
-         * Add an override for a field trial parameter.
-         *
-         * @param param The param object that holds feature and param names.
-         * @param testValue The string value to override, which will later be parsed/converted into
-         *     the actual value.
-         */
-        public void addFieldTrialParamOverride(FeatureParam param, String testValue) {
-            addFieldTrialParamOverride(param.getFeatureName(), param.getName(), testValue);
-        }
-
-        Boolean getFeatureFlagOverride(String featureName) {
-            return mFeatureFlags.get(featureName);
-        }
-
-        String getFieldTrialParamOverride(String featureName, String paramName) {
-            Map<String, String> featureParams = mFieldTrialParams.get(featureName);
-            if (featureParams == null) return null;
-            return featureParams.get(paramName);
-        }
-
-        Map<String, String> getAllFieldTrialParamOverridesForFeature(String featureName) {
-            return mFieldTrialParams.get(featureName);
-        }
-
-        public void merge(TestValues testValuesToMerge, boolean replace) {
-            if (replace) {
-                mFeatureFlags.putAll(testValuesToMerge.mFeatureFlags);
-            } else {
-                for (Map.Entry<String, Boolean> toMerge :
-                        testValuesToMerge.mFeatureFlags.entrySet()) {
-                    mFeatureFlags.putIfAbsent(toMerge.getKey(), toMerge.getValue());
-                }
-            }
-
-            for (Map.Entry<String, Map<String, String>> e :
-                    testValuesToMerge.mFieldTrialParams.entrySet()) {
-                String featureName = e.getKey();
-                var fieldTrialParamsForFeature = mFieldTrialParams.get(featureName);
-                if (fieldTrialParamsForFeature == null) {
-                    fieldTrialParamsForFeature = new ArrayMap<>();
-                    mFieldTrialParams.put(featureName, fieldTrialParamsForFeature);
-                }
-
-                if (replace) {
-                    fieldTrialParamsForFeature.putAll(e.getValue());
-                } else {
-                    for (Map.Entry<String, String> toMerge : e.getValue().entrySet()) {
-                        fieldTrialParamsForFeature.putIfAbsent(
-                                toMerge.getKey(), toMerge.getValue());
-                    }
-                }
-            }
-        }
-
-        /**
-         * Returns a representation of the TestValues.
-         *
-         * <p>The format returned is:
-         *
-         * <pre>{FeatureA=true} + {FeatureA.Param1=Value1, FeatureA.ParamB=ValueB}</pre>
-         */
-        public String toDebugString() {
-            StringBuilder stringBuilder = new StringBuilder();
-            String separator = "";
-            stringBuilder.append("{");
-            for (var e : mFeatureFlags.entrySet()) {
-                String featureName = e.getKey();
-                boolean featureValue = e.getValue();
-                stringBuilder
-                        .append(separator)
-                        .append(featureName)
-                        .append("=")
-                        .append(featureValue);
-                separator = ", ";
-            }
-            stringBuilder.append("}");
-            if (!mFieldTrialParams.isEmpty()) {
-                stringBuilder.append(" + {");
-                for (var e : mFieldTrialParams.entrySet()) {
-                    String paramsAndValuesSeparator = "";
-                    String featureName = e.getKey();
-                    Map<String, String> paramsAndValues = e.getValue();
-                    for (var paramAndValue : paramsAndValues.entrySet()) {
-                        String paramName = paramAndValue.getKey();
-                        String paramValue = paramAndValue.getValue();
-                        stringBuilder
-                                .append(paramsAndValuesSeparator)
-                                .append(featureName)
-                                .append(".")
-                                .append(paramName)
-                                .append("=")
-                                .append(paramValue);
-                        paramsAndValuesSeparator = ", ";
-                    }
-                }
-                stringBuilder.append("}");
-            }
-            return stringBuilder.toString();
-        }
-
-        public boolean isEmpty() {
-            return mFeatureFlags.isEmpty() && mFieldTrialParams.isEmpty();
-        }
-    }
-
-    /** Map that stores substitution feature flags for tests. */
-    private static @Nullable TestValues sTestFeatures;
-
     /** Prevent access to default values of the native feature flag. */
     private static boolean sDisableNativeForTesting;
 
     private FeatureList() {}
 
     /**
-     * @deprecated Check specific flags (via Flag.isEnabled()) instead.
+     * TODO(crbug.com/345483622): Migrate usages and remove isInitialized().
+     *
+     * @deprecated For checking flags, use {@code MutableFlagWithSafeDefault} for flags that have a
+     *     pre-native default value. Use {@code CachedFlag} for flags that should use a disk-cached
+     *     value if checked pre-native. Otherwise, Use {@link #isNativeInitialized()} to check if
+     *     the native FeatureList is initialized.
      */
     @Deprecated
     public static boolean isInitialized() {
-        return (sDisableNativeForTesting && sTestFeatures != null) || isNativeInitialized();
+        return (sDisableNativeForTesting && FeatureOverrides.sTestFeatures != null)
+                || isNativeInitialized();
     }
 
     /**
@@ -188,162 +51,26 @@
         return FeatureListJni.get().isInitialized();
     }
 
-    /** Whether to block querying feature values from native. */
+    /**
+     * Block (or unblock) querying feature values from native and instead rely only on test values.
+     *
+     * <p>When native is disabled, calling {@link FeatureMap#isEnabledInNative(String)} will cause
+     * an exception to be thrown and calling {@link FeatureMap#getFieldTrialParamByFeature(String,
+     * String)} will cause the default value to be returned.
+     */
     public static void setDisableNativeForTesting(boolean value) {
         boolean prev = sDisableNativeForTesting;
         sDisableNativeForTesting = value;
         ResettersForTesting.register(() -> sDisableNativeForTesting = prev);
     }
 
-    /** Whether to pretend native isn't loaded. */
+    /**
+     * Whether to block querying feature values from native and instead rely only on test values.
+     */
     public static boolean getDisableNativeForTesting() {
         return sDisableNativeForTesting;
     }
 
-    /** Sets the feature flags to use in JUnit tests, since native calls are not available there. */
-    @VisibleForTesting
-    public static void setTestFeatures(@Nullable Map<String, Boolean> testFeatures) {
-        if (testFeatures == null) {
-            setTestValues(null);
-        } else {
-            TestValues testValues = new TestValues();
-            testValues.setFeatureFlagsOverride(testFeatures);
-            setTestValues(testValues);
-        }
-    }
-
-    /**
-     * Sets the feature flags and field trial parameters to use in JUnit tests, since native calls
-     * are not available there.
-     */
-    @VisibleForTesting
-    public static void setTestValues(@Nullable TestValues testValues) {
-        TestValues prevValues = sTestFeatures;
-        sTestFeatures = testValues;
-        ResettersForTesting.register(() -> sTestFeatures = prevValues);
-    }
-
-    /** For use by test runners. */
-    public static void setTestValuesNoResetForTesting(TestValues testValues) {
-        sTestFeatures = testValues;
-    }
-
-    /**
-     * Adds overrides to feature flags and field trial parameters in addition to existing ones.
-     *
-     * @param testValuesToMerge the TestValues to merge into existing ones
-     * @param replace if true, replaces existing values (e.g. from @EnableFeatures annotations)
-     */
-    public static void mergeTestValues(@NonNull TestValues testValuesToMerge, boolean replace) {
-        TestValues newTestValues = new TestValues();
-        if (sTestFeatures != null) {
-            newTestValues.merge(sTestFeatures, /* replace= */ true);
-        }
-        newTestValues.merge(testValuesToMerge, replace);
-        setTestValues(newTestValues);
-    }
-
-    /**
-     * @param featureName The name of the feature to query.
-     * @return Whether the feature has a test value configured.
-     */
-    public static boolean hasTestFeature(String featureName) {
-        // TODO(crbug.com/40264751)): Copy into a local reference to avoid race conditions
-        // like crbug.com/1494095 unsetting the test features. Locking down flag state will allow
-        // this mitigation to be removed.
-        TestValues testValues = sTestFeatures;
-        return testValues != null && testValues.mFeatureFlags.containsKey(featureName);
-    }
-
-    /**
-     * @param featureName The name of the feature the param is part of.
-     * @param paramName The name of the param to query.
-     * @return Whether the param has a test value configured.
-     */
-    public static boolean hasTestParam(String featureName, String paramName) {
-        TestValues testValues = sTestFeatures;
-        return testValues != null
-                && testValues.mFieldTrialParams.containsKey(featureName)
-                && testValues.mFieldTrialParams.get(featureName).containsKey(paramName);
-    }
-
-    /**
-     * Returns the test value of the feature with the given name.
-     *
-     * @param featureName The name of the feature to query.
-     * @return The test value set for the feature, or null if no test value has been set.
-     * @throws IllegalArgumentException if no test value was set and default values aren't allowed.
-     */
-    public static Boolean getTestValueForFeatureStrict(String featureName) {
-        Boolean testValue = getTestValueForFeature(featureName);
-        if (testValue == null && sDisableNativeForTesting) {
-            throw new IllegalArgumentException(
-                    "No test value configured for "
-                            + featureName
-                            + " and native is not available to provide a default value. Use"
-                            + " @EnableFeatures or @DisableFeatures to provide test values for"
-                            + " the flag.");
-        }
-        return testValue;
-    }
-
-    /**
-     * Returns the test value of the feature with the given name.
-     *
-     * @param featureName The name of the feature to query.
-     * @return The test value set for the feature, or null if no test value has been set.
-     */
-    public static Boolean getTestValueForFeature(String featureName) {
-        // TODO(crbug.com/40264751)): Copy into a local reference to avoid race conditions
-        // like crbug.com/1494095 unsetting the test features. Locking down flag state will allow
-        // this mitigation to be removed.
-        TestValues testValues = sTestFeatures;
-        if (testValues != null) {
-            Boolean override = testValues.getFeatureFlagOverride(featureName);
-            if (override != null) {
-                return override;
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Returns the test value of the field trial parameter.
-     *
-     * @param featureName The name of the feature to query.
-     * @param paramName The name of the field trial parameter to query.
-     * @return The test value set for the parameter, or null if no test value has been set.
-     */
-    public static String getTestValueForFieldTrialParam(String featureName, String paramName) {
-        // TODO(crbug.com/40264751)): Copy into a local reference to avoid race conditions
-        // like crbug.com/1494095 unsetting the test features. Locking down flag state will allow
-        // this mitigation to be removed.
-        TestValues testValues = sTestFeatures;
-        if (testValues != null) {
-            return testValues.getFieldTrialParamOverride(featureName, paramName);
-        }
-        return null;
-    }
-
-    /**
-     * Returns the test value of the all field trial parameters of a given feature.
-     *
-     * @param featureName The name of the feature to query all parameters.
-     * @return The test values set for the parameter, or null if no test values have been set (if
-     *     test values were set for other features, an empty Map will be returned, not null).
-     */
-    public static Map<String, String> getTestValuesForAllFieldTrialParamsForFeature(
-            String featureName) {
-        // TODO(crbug.com/40264751)): Copy into a local reference to avoid race conditions
-        // like crbug.com/1494095 unsetting the test features. Locking down flag state will allow
-        // this mitigation to be removed.
-        TestValues testValues = sTestFeatures;
-        if (testValues != null) {
-            return testValues.getAllFieldTrialParamOverridesForFeature(featureName);
-        }
-        return null;
-    }
-
     @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)
     @NativeMethods
     public interface Natives {
diff --git a/tot/base/android/java/src/org/chromium/base/FeatureMap.java b/tot/base/android/java/src/org/chromium/base/FeatureMap.java
index 115012e..638aed4 100644
--- a/tot/base/android/java/src/org/chromium/base/FeatureMap.java
+++ b/tot/base/android/java/src/org/chromium/base/FeatureMap.java
@@ -8,6 +8,8 @@
 import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
@@ -23,6 +25,7 @@
  * to get the pointer to the base::android::FeatureMap. The derived class will provide Java code
  * access to the list of base::Features passed to the base::android::FeatureMap.
  */
+@NullMarked
 @JNINamespace("base::android")
 public abstract class FeatureMap {
     private long mNativeMapPtr;
@@ -41,14 +44,15 @@
      * to be marked as active.
      *
      * <p>Should be called only after native is loaded. If {@link FeatureList#isInitialized()}
-     * returns true, this method is safe to call. In tests, this will return any values set through
-     * {@link FeatureList#setTestFeatures(Map)}, even before native is loaded.
+     * returns true, this method is safe to call. In tests, this will return any values set
+     * through @Enable/@DisableFeatures annotations or {@link FeatureOverrides}, even before native
+     * is loaded.
      *
      * @param featureName The name of the feature to query.
      * @return Whether the feature is enabled or not.
      */
     public boolean isEnabledInNative(String featureName) {
-        Boolean testValue = FeatureList.getTestValueForFeatureStrict(featureName);
+        Boolean testValue = FeatureOverrides.getTestValueForFeatureStrict(featureName);
         if (testValue != null) return testValue;
         ensureNativeMapInit();
         return FeatureMapJni.get().isEnabled(mNativeMapPtr, featureName);
@@ -60,10 +64,10 @@
      * @param featureName The name of the feature to retrieve a param for.
      * @param paramName The name of the param for which to get as an integer.
      * @return The parameter value as a String. The string is empty if the feature does not exist or
-     *   the specified parameter does not exist.
+     *     the specified parameter does not exist.
      */
     public String getFieldTrialParamByFeature(String featureName, String paramName) {
-        String testValue = FeatureList.getTestValueForFieldTrialParam(featureName, paramName);
+        String testValue = FeatureOverrides.getTestValueForFieldTrialParam(featureName, paramName);
         if (testValue != null) return testValue;
         if (FeatureList.getDisableNativeForTesting()) return "";
         ensureNativeMapInit();
@@ -78,11 +82,11 @@
      * @param paramName The name of the param for which to get as an integer.
      * @param defaultValue The boolean value to use if the param is not available.
      * @return The parameter value as a boolean. Default value if the feature does not exist or the
-     *         specified parameter does not exist or its string value is neither "true" nor "false".
+     *     specified parameter does not exist or its string value is neither "true" nor "false".
      */
     public boolean getFieldTrialParamByFeatureAsBoolean(
             String featureName, String paramName, boolean defaultValue) {
-        String testValue = FeatureList.getTestValueForFieldTrialParam(featureName, paramName);
+        String testValue = FeatureOverrides.getTestValueForFieldTrialParam(featureName, paramName);
         if (testValue != null) return Boolean.valueOf(testValue);
         if (FeatureList.getDisableNativeForTesting()) return defaultValue;
         ensureNativeMapInit();
@@ -98,11 +102,11 @@
      * @param paramName The name of the param for which to get as an integer.
      * @param defaultValue The integer value to use if the param is not available.
      * @return The parameter value as an int. Default value if the feature does not exist or the
-     *         specified parameter does not exist or its string value does not represent an int.
+     *     specified parameter does not exist or its string value does not represent an int.
      */
     public int getFieldTrialParamByFeatureAsInt(
             String featureName, String paramName, int defaultValue) {
-        String testValue = FeatureList.getTestValueForFieldTrialParam(featureName, paramName);
+        String testValue = FeatureOverrides.getTestValueForFieldTrialParam(featureName, paramName);
         if (testValue != null) return Integer.valueOf(testValue);
         if (FeatureList.getDisableNativeForTesting()) return defaultValue;
         ensureNativeMapInit();
@@ -118,11 +122,11 @@
      * @param paramName The name of the param for which to get as an integer.
      * @param defaultValue The double value to use if the param is not available.
      * @return The parameter value as a double. Default value if the feature does not exist or the
-     *         specified parameter does not exist or its string value does not represent a double.
+     *     specified parameter does not exist or its string value does not represent a double.
      */
     public double getFieldTrialParamByFeatureAsDouble(
             String featureName, String paramName, double defaultValue) {
-        String testValue = FeatureList.getTestValueForFieldTrialParam(featureName, paramName);
+        String testValue = FeatureOverrides.getTestValueForFieldTrialParam(featureName, paramName);
         if (testValue != null) return Double.valueOf(testValue);
         if (FeatureList.getDisableNativeForTesting()) return defaultValue;
         ensureNativeMapInit();
@@ -134,7 +138,7 @@
     /** Returns all the field trial parameters for the specified feature. */
     public Map<String, String> getFieldTrialParamsForFeature(String featureName) {
         Map<String, String> testValues =
-                FeatureList.getTestValuesForAllFieldTrialParamsForFeature(featureName);
+                FeatureOverrides.getTestValuesForAllFieldTrialParamsForFeature(featureName);
         if (testValues != null) return testValues;
         if (FeatureList.getDisableNativeForTesting()) return Collections.emptyMap();
 
diff --git a/tot/base/android/java/src/org/chromium/base/FeatureOverrides.java b/tot/base/android/java/src/org/chromium/base/FeatureOverrides.java
new file mode 100644
index 0000000..b44bcb3
--- /dev/null
+++ b/tot/base/android/java/src/org/chromium/base/FeatureOverrides.java
@@ -0,0 +1,455 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.base;
+
+import android.util.ArrayMap;
+
+import androidx.annotation.CheckResult;
+
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Allows overriding feature flags and parameters for tests. Prefer @Features annotations.
+ *
+ * <p>This is useful when the values set are dynamic, for example in parameterized tests or in tests
+ * that needs to change the flag/param values in the middle of the test rather than from the
+ * beginning.
+ *
+ * <p>The @Features.EnableFeatures and @Features.DisableFeatures annotations use FeatureOverrides,
+ * but also apply the changes more broadly; they include applying the override in native and they
+ * batch according to flag configuration.
+ */
+@NullMarked
+public class FeatureOverrides {
+    /** Map that stores substitution feature flags for tests. */
+    static @Nullable TestValues sTestFeatures;
+
+    /** Builder of overrides for overriding feature flags and field trial parameters. */
+    public static class Builder {
+        private final TestValues mTestValues = new TestValues();
+        private @Nullable String mLastFeatureName;
+
+        private Builder() {}
+
+        /**
+         * Apply overrides to feature flags and field trial parameters in addition to existing ones.
+         *
+         * <p>On conflict, overwrites the previous override.
+         */
+        public void apply() {
+            mergeTestValues(mTestValues, /* replace= */ true);
+        }
+
+        /**
+         * Apply overrides to feature flags and field trial parameters in addition to existing ones.
+         *
+         * <p>On conflict, the previous override is preserved.
+         */
+        public void applyWithoutOverwrite() {
+            mergeTestValues(mTestValues, /* replace= */ false);
+        }
+
+        /** For use by test runners. */
+        public void applyNoResetForTesting() {
+            setTestValuesNoResetForTesting(mTestValues);
+        }
+
+        /** Enable a feature flag. */
+        @CheckResult
+        public Builder enable(String featureName) {
+            mTestValues.addFeatureFlagOverride(featureName, true);
+            mLastFeatureName = featureName;
+            return this;
+        }
+
+        /** Disable a feature flag. */
+        @CheckResult
+        public Builder disable(String featureName) {
+            mTestValues.addFeatureFlagOverride(featureName, false);
+            mLastFeatureName = null;
+            return this;
+        }
+
+        /** Enable or disable a feature flag. */
+        @CheckResult
+        public Builder flag(String featureName, boolean value) {
+            mTestValues.addFeatureFlagOverride(featureName, value);
+            return this;
+        }
+
+        /** Override a boolean param for the last feature flag enabled. */
+        @CheckResult
+        public Builder param(String paramName, boolean value) {
+            return param(getLastFeatureName(), paramName, String.valueOf(value));
+        }
+
+        /** Override an int param for the last feature flag enabled. */
+        @CheckResult
+        public Builder param(String paramName, int value) {
+            return param(getLastFeatureName(), paramName, String.valueOf(value));
+        }
+
+        /** Override a double param for the last feature flag enabled. */
+        @CheckResult
+        public Builder param(String paramName, double value) {
+            return param(getLastFeatureName(), paramName, String.valueOf(value));
+        }
+
+        /** Override a String param for the last feature flag enabled. */
+        @CheckResult
+        public Builder param(String paramName, String value) {
+            return param(getLastFeatureName(), paramName, value);
+        }
+
+        private String getLastFeatureName() {
+            if (mLastFeatureName == null) {
+                throw new IllegalArgumentException(
+                        "param(paramName, value) should be used after enable()");
+            }
+            return mLastFeatureName;
+        }
+
+        /** Override a boolean param. */
+        @CheckResult
+        public Builder param(String featureName, String paramName, boolean value) {
+            return param(featureName, paramName, String.valueOf(value));
+        }
+
+        /** Override an int param. */
+        @CheckResult
+        public Builder param(String featureName, String paramName, int value) {
+            return param(featureName, paramName, String.valueOf(value));
+        }
+
+        /** Override a double param. */
+        @CheckResult
+        public Builder param(String featureName, String paramName, double value) {
+            return param(featureName, paramName, String.valueOf(value));
+        }
+
+        /** Override a String param. */
+        @CheckResult
+        public Builder param(String featureName, String paramName, String value) {
+            mTestValues.addFieldTrialParamOverride(featureName, paramName, value);
+            return this;
+        }
+
+        public boolean isEmpty() {
+            return mTestValues.isEmpty();
+        }
+    }
+
+    /** Maps with the actual test value overrides. */
+    private static class TestValues {
+        private final Map<String, Boolean> mFeatureFlags = new HashMap<>();
+        private final Map<String, Map<String, String>> mFieldTrialParams = new HashMap<>();
+
+        /** Add an override for a feature flag. */
+        void addFeatureFlagOverride(String featureName, boolean testValue) {
+            mFeatureFlags.put(featureName, testValue);
+        }
+
+        /** Add an override for a field trial parameter. */
+        void addFieldTrialParamOverride(String featureName, String paramName, String testValue) {
+            Map<String, String> featureParams = mFieldTrialParams.get(featureName);
+            if (featureParams == null) {
+                featureParams = new ArrayMap<>();
+                mFieldTrialParams.put(featureName, featureParams);
+            }
+            featureParams.put(paramName, testValue);
+        }
+
+        public @Nullable Boolean getFeatureFlagOverride(String featureName) {
+            return mFeatureFlags.get(featureName);
+        }
+
+        public @Nullable String getFieldTrialParamOverride(String featureName, String paramName) {
+            Map<String, String> featureParams = mFieldTrialParams.get(featureName);
+            if (featureParams == null) return null;
+            return featureParams.get(paramName);
+        }
+
+        public @Nullable Map<String, String> getAllFieldTrialParamOverridesForFeature(
+                String featureName) {
+            return mFieldTrialParams.get(featureName);
+        }
+
+        void merge(TestValues testValuesToMerge, boolean replace) {
+            if (replace) {
+                mFeatureFlags.putAll(testValuesToMerge.mFeatureFlags);
+            } else {
+                for (Map.Entry<String, Boolean> toMerge :
+                        testValuesToMerge.mFeatureFlags.entrySet()) {
+                    mFeatureFlags.putIfAbsent(toMerge.getKey(), toMerge.getValue());
+                }
+            }
+
+            for (Map.Entry<String, Map<String, String>> e :
+                    testValuesToMerge.mFieldTrialParams.entrySet()) {
+                String featureName = e.getKey();
+                var fieldTrialParamsForFeature = mFieldTrialParams.get(featureName);
+                if (fieldTrialParamsForFeature == null) {
+                    fieldTrialParamsForFeature = new ArrayMap<>();
+                    mFieldTrialParams.put(featureName, fieldTrialParamsForFeature);
+                }
+
+                if (replace) {
+                    fieldTrialParamsForFeature.putAll(e.getValue());
+                } else {
+                    for (Map.Entry<String, String> toMerge : e.getValue().entrySet()) {
+                        fieldTrialParamsForFeature.putIfAbsent(
+                                toMerge.getKey(), toMerge.getValue());
+                    }
+                }
+            }
+        }
+
+        /**
+         * Returns a representation of the TestValues.
+         *
+         * <p>The format returned is:
+         *
+         * <pre>{FeatureA=true} + {FeatureA.Param1=Value1, FeatureA.ParamB=ValueB}</pre>
+         */
+        @SuppressWarnings("UnusedMethod")
+        public String toDebugString() {
+            StringBuilder stringBuilder = new StringBuilder();
+            String separator = "";
+            stringBuilder.append("{");
+            for (var e : mFeatureFlags.entrySet()) {
+                String featureName = e.getKey();
+                boolean featureValue = e.getValue();
+                stringBuilder
+                        .append(separator)
+                        .append(featureName)
+                        .append("=")
+                        .append(featureValue);
+                separator = ", ";
+            }
+            stringBuilder.append("}");
+            if (!mFieldTrialParams.isEmpty()) {
+                stringBuilder.append(" + {");
+                for (var e : mFieldTrialParams.entrySet()) {
+                    String paramsAndValuesSeparator = "";
+                    String featureName = e.getKey();
+                    Map<String, String> paramsAndValues = e.getValue();
+                    for (var paramAndValue : paramsAndValues.entrySet()) {
+                        String paramName = paramAndValue.getKey();
+                        String paramValue = paramAndValue.getValue();
+                        stringBuilder
+                                .append(paramsAndValuesSeparator)
+                                .append(featureName)
+                                .append(".")
+                                .append(paramName)
+                                .append("=")
+                                .append(paramValue);
+                        paramsAndValuesSeparator = ", ";
+                    }
+                }
+                stringBuilder.append("}");
+            }
+            return stringBuilder.toString();
+        }
+
+        public boolean isEmpty() {
+            return mFeatureFlags.isEmpty() && mFieldTrialParams.isEmpty();
+        }
+
+        boolean hasFlagOverride(String featureName) {
+            return mFeatureFlags.containsKey(featureName);
+        }
+
+        boolean hasParamOverride(String featureName, String paramName) {
+            return mFieldTrialParams.containsKey(featureName)
+                    && mFieldTrialParams.get(featureName).containsKey(paramName);
+        }
+    }
+
+    /** Use {@link #newBuilder()}. */
+    private FeatureOverrides() {}
+
+    /** Create a Builder for overriding feature flags and field trial parameters. */
+    @CheckResult
+    public static FeatureOverrides.Builder newBuilder() {
+        return new FeatureOverrides.Builder();
+    }
+
+    /** Enable a feature flag for testing. */
+    public static void enable(String featureName) {
+        newBuilder().enable(featureName).apply();
+    }
+
+    /** Disable a feature flag for testing. */
+    public static void disable(String featureName) {
+        newBuilder().disable(featureName).apply();
+    }
+
+    /** Override a feature flag for testing. */
+    public static void overrideFlag(String featureName, boolean testValue) {
+        newBuilder().flag(featureName, testValue).apply();
+    }
+
+    /** Override a boolean feature param for testing. */
+    public static void overrideParam(String featureName, String paramName, boolean testValue) {
+        newBuilder().param(featureName, paramName, testValue).apply();
+    }
+
+    /** Override an int feature param for testing. */
+    public static void overrideParam(String featureName, String paramName, int testValue) {
+        newBuilder().param(featureName, paramName, testValue).apply();
+    }
+
+    /** Override a double feature param for testing. */
+    public static void overrideParam(String featureName, String paramName, double testValue) {
+        newBuilder().param(featureName, paramName, testValue).apply();
+    }
+
+    /** Override a feature param for testing. */
+    public static void overrideParam(String featureName, String paramName, String testValue) {
+        newBuilder().param(featureName, paramName, testValue).apply();
+    }
+
+    /**
+     * Rarely necessary. Remove all Java overrides to feature flags and field trial parameters.
+     *
+     * <p>You don't need to call this on tearDown() or at the end of a test. ResettersForTesting
+     * already resets test values.
+     *
+     * <p>@Features annotations and @CommandLineFlags --enable/disable-features are affected by
+     * this.
+     */
+    public static void removeAllIncludingAnnotations() {
+        overwriteTestValues(null);
+    }
+
+    private static void overwriteTestValues(@Nullable TestValues testValues) {
+        TestValues prevValues = sTestFeatures;
+        sTestFeatures = testValues;
+        ResettersForTesting.register(() -> sTestFeatures = prevValues);
+    }
+
+    private static void setTestValuesNoResetForTesting(TestValues testValues) {
+        sTestFeatures = testValues;
+    }
+
+    /**
+     * Adds overrides to feature flags and field trial parameters in addition to existing ones.
+     *
+     * @param testValuesToMerge the TestValues to merge into existing ones
+     * @param replace if true, replaces existing overrides; otherwise preserve them
+     */
+    private static void mergeTestValues(TestValues testValuesToMerge, boolean replace) {
+        TestValues newTestValues = new TestValues();
+        if (sTestFeatures != null) {
+            newTestValues.merge(sTestFeatures, /* replace= */ true);
+        }
+        newTestValues.merge(testValuesToMerge, replace);
+        overwriteTestValues(newTestValues);
+    }
+
+    /**
+     * @param featureName The name of the feature to query.
+     * @return Whether the feature has a test value configured.
+     */
+    public static boolean hasTestFeature(String featureName) {
+        // TODO(crbug.com/40264751)): Copy into a local reference to avoid race conditions
+        // like crbug.com/1494095 unsetting the test features. Locking down flag state will allow
+        // this mitigation to be removed.
+        TestValues testValues = sTestFeatures;
+        return testValues != null && testValues.hasFlagOverride(featureName);
+    }
+
+    /**
+     * @param featureName The name of the feature the param is part of.
+     * @param paramName The name of the param to query.
+     * @return Whether the param has a test value configured.
+     */
+    public static boolean hasTestParam(String featureName, String paramName) {
+        TestValues testValues = sTestFeatures;
+        return testValues != null && testValues.hasParamOverride(featureName, paramName);
+    }
+
+    /**
+     * Returns the test value of the feature with the given name.
+     *
+     * @param featureName The name of the feature to query.
+     * @return The test value set for the feature, or null if no test value has been set.
+     * @throws IllegalArgumentException if no test value was set and default values aren't allowed.
+     */
+    public static @Nullable Boolean getTestValueForFeatureStrict(String featureName) {
+        Boolean testValue = getTestValueForFeature(featureName);
+        if (testValue == null && FeatureList.getDisableNativeForTesting()) {
+            throw new IllegalArgumentException(
+                    "No test value configured for "
+                            + featureName
+                            + " and native is not available to provide a default value. Use"
+                            + " @EnableFeatures or @DisableFeatures to provide test values for"
+                            + " the flag.");
+        }
+        return testValue;
+    }
+
+    /**
+     * Returns the test value of the feature with the given name.
+     *
+     * @param featureName The name of the feature to query.
+     * @return The test value set for the feature, or null if no test value has been set.
+     */
+    public static @Nullable Boolean getTestValueForFeature(String featureName) {
+        // TODO(crbug.com/40264751)): Copy into a local reference to avoid race conditions
+        // like crbug.com/1494095 unsetting the test features. Locking down flag state will allow
+        // this mitigation to be removed.
+        TestValues testValues = sTestFeatures;
+        if (testValues != null) {
+            Boolean override = testValues.getFeatureFlagOverride(featureName);
+            if (override != null) {
+                return override;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Returns the test value of the field trial parameter.
+     *
+     * @param featureName The name of the feature to query.
+     * @param paramName The name of the field trial parameter to query.
+     * @return The test value set for the parameter, or null if no test value has been set.
+     */
+    public static @Nullable String getTestValueForFieldTrialParam(
+            String featureName, String paramName) {
+        // TODO(crbug.com/40264751)): Copy into a local reference to avoid race conditions
+        // like crbug.com/1494095 unsetting the test features. Locking down flag state will allow
+        // this mitigation to be removed.
+        TestValues testValues = sTestFeatures;
+        if (testValues != null) {
+            return testValues.getFieldTrialParamOverride(featureName, paramName);
+        }
+        return null;
+    }
+
+    /**
+     * Returns the test value of the all field trial parameters of a given feature.
+     *
+     * @param featureName The name of the feature to query all parameters.
+     * @return The test values set for the parameter, or null if no test values have been set (if
+     *     test values were set for other features, an empty Map will be returned, not null).
+     */
+    public static @Nullable Map<String, String> getTestValuesForAllFieldTrialParamsForFeature(
+            String featureName) {
+        // TODO(crbug.com/40264751)): Copy into a local reference to avoid race conditions
+        // like crbug.com/1494095 unsetting the test features. Locking down flag state will allow
+        // this mitigation to be removed.
+        TestValues testValues = sTestFeatures;
+        if (testValues != null) {
+            return testValues.getAllFieldTrialParamOverridesForFeature(featureName);
+        }
+        return null;
+    }
+}
diff --git a/tot/base/android/java/src/org/chromium/base/FeatureParam.java b/tot/base/android/java/src/org/chromium/base/FeatureParam.java
index b4fc105..e748399 100644
--- a/tot/base/android/java/src/org/chromium/base/FeatureParam.java
+++ b/tot/base/android/java/src/org/chromium/base/FeatureParam.java
@@ -6,11 +6,10 @@
 
 import android.util.Pair;
 
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-
 import org.chromium.build.BuildConfig;
 import org.chromium.build.annotations.CheckDiscard;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.HashMap;
 import java.util.Map;
@@ -22,6 +21,7 @@
  *
  * @param <T> The boxed type of data behind held.
  */
+@NullMarked
 @NotThreadSafe
 public abstract class FeatureParam<T> {
     @CheckDiscard("Only needed to reset tests. Production code shouldn't use.")
@@ -33,13 +33,10 @@
     protected final T mDefaultValue;
 
     // Null means this is not cached, and the feature map should be read from.
-    @Nullable protected T mInMemoryCachedValue;
+    protected @Nullable T mInMemoryCachedValue;
 
     public FeatureParam(
-            @NonNull FeatureMap featureMap,
-            @NonNull String featureName,
-            @NonNull String paramName,
-            @NonNull T defaultValue) {
+            FeatureMap featureMap, String featureName, String paramName, T defaultValue) {
         assert defaultValue != null;
         mFeatureMap = featureMap;
         mFeatureName = featureName;
diff --git a/tot/base/android/java/src/org/chromium/base/Features.java b/tot/base/android/java/src/org/chromium/base/Features.java
index a54d52b..0a84105 100644
--- a/tot/base/android/java/src/org/chromium/base/Features.java
+++ b/tot/base/android/java/src/org/chromium/base/Features.java
@@ -8,12 +8,15 @@
 import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
  * A class that serves as a bridge to native code to check the status of feature switches.
  *
  * <p>Each subclass represents a set of related features. Each instance of such a class correlates
  * to a single C++ Feature.
  */
+@NullMarked
 @JNINamespace("base::android")
 public abstract class Features {
     private final String mName;
@@ -30,7 +33,7 @@
     /** Returns true if the given feature is enabled. */
     public boolean isEnabled() {
         // FeatureFlags set for testing override the native default value.
-        Boolean testValue = FeatureList.getTestValueForFeatureStrict(getName());
+        Boolean testValue = FeatureOverrides.getTestValueForFeatureStrict(getName());
         if (testValue != null) return testValue;
         return FeaturesJni.get().isEnabled(getFeaturePointer());
     }
diff --git a/tot/base/android/java/src/org/chromium/base/FieldTrialList.java b/tot/base/android/java/src/org/chromium/base/FieldTrialList.java
index 5e2b0a6..ef5a09b 100644
--- a/tot/base/android/java/src/org/chromium/base/FieldTrialList.java
+++ b/tot/base/android/java/src/org/chromium/base/FieldTrialList.java
@@ -7,7 +7,10 @@
 import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Helper to get field trial information. */
+@NullMarked
 public class FieldTrialList {
 
     private FieldTrialList() {}
diff --git a/tot/base/android/java/src/org/chromium/base/FileProviderUtils.java b/tot/base/android/java/src/org/chromium/base/FileProviderUtils.java
index ac3b783..ecbd84a 100644
--- a/tot/base/android/java/src/org/chromium/base/FileProviderUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/FileProviderUtils.java
@@ -6,12 +6,16 @@
 
 import android.net.Uri;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.io.File;
 
 /** This class provides methods to access content URI schemes. */
+@NullMarked
 public abstract class FileProviderUtils {
     private static final String TAG = "FileProviderUtils";
-    private static FileProviderUtil sFileProviderUtil;
+    private static @Nullable FileProviderUtil sFileProviderUtil;
 
     // Guards access to sFileProviderUtil.
     private static final Object sLock = new Object();
@@ -47,7 +51,7 @@
      * @throws IllegalArgumentException when the given File is outside the paths supported by the
      *     provider.
      */
-    public static Uri getContentUriFromFile(File file) {
+    public static @Nullable Uri getContentUriFromFile(File file) {
         synchronized (sLock) {
             if (sFileProviderUtil != null) {
                 return sFileProviderUtil.getContentUriFromFile(file);
diff --git a/tot/base/android/java/src/org/chromium/base/FileUtils.java b/tot/base/android/java/src/org/chromium/base/FileUtils.java
index f47922d..8aea5c3 100644
--- a/tot/base/android/java/src/org/chromium/base/FileUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/FileUtils.java
@@ -10,13 +10,13 @@
 import android.net.Uri;
 import android.os.ParcelFileDescriptor;
 
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-
 import org.jni_zero.JNINamespace;
 import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileDescriptor;
@@ -28,6 +28,7 @@
 import java.util.function.Function;
 
 /** Helper methods for dealing with Files. */
+@NullMarked
 @JNINamespace("base::android")
 public class FileUtils {
     private static final String TAG = "FileUtils";
@@ -122,7 +123,6 @@
     }
 
     /** Reads inputStream into a byte array. */
-    @NonNull
     public static byte[] readStream(InputStream inputStream) throws IOException {
         ByteArrayOutputStream data = new ByteArrayOutputStream();
         FileUtils.copyStream(inputStream, data);
@@ -166,8 +166,7 @@
     }
 
     /** Queries and decodes bitmap from content provider. */
-    @Nullable
-    public static Bitmap queryBitmapFromContentProvider(Context context, Uri uri) {
+    public static @Nullable Bitmap queryBitmapFromContentProvider(Context context, Uri uri) {
         try (ParcelFileDescriptor parcelFileDescriptor =
                 context.getContentResolver().openFileDescriptor(uri, "r")) {
             if (parcelFileDescriptor == null) {
diff --git a/tot/base/android/java/src/org/chromium/base/Flag.java b/tot/base/android/java/src/org/chromium/base/Flag.java
index 4a1a4dd..f4560e6 100644
--- a/tot/base/android/java/src/org/chromium/base/Flag.java
+++ b/tot/base/android/java/src/org/chromium/base/Flag.java
@@ -5,6 +5,7 @@
 package org.chromium.base;
 
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
 
 import java.util.HashMap;
 
@@ -21,6 +22,7 @@
  *
  * <p>This class and its subclasses are not thread safe.
  */
+@NullMarked
 @NotThreadSafe
 public abstract class Flag {
     // Used to reset all flags between tests.
diff --git a/tot/base/android/java/src/org/chromium/base/ImportantFileWriterAndroid.java b/tot/base/android/java/src/org/chromium/base/ImportantFileWriterAndroid.java
index 1c3b0b0..f600755 100644
--- a/tot/base/android/java/src/org/chromium/base/ImportantFileWriterAndroid.java
+++ b/tot/base/android/java/src/org/chromium/base/ImportantFileWriterAndroid.java
@@ -10,10 +10,13 @@
 import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
  * This class provides an interface to the native class for writing important data files without
  * risking data loss.
  */
+@NullMarked
 @JNINamespace("base::android")
 public class ImportantFileWriterAndroid {
 
diff --git a/tot/base/android/java/src/org/chromium/base/InputHintChecker.java b/tot/base/android/java/src/org/chromium/base/InputHintChecker.java
index 3c789b5..7f3a394 100644
--- a/tot/base/android/java/src/org/chromium/base/InputHintChecker.java
+++ b/tot/base/android/java/src/org/chromium/base/InputHintChecker.java
@@ -8,12 +8,14 @@
 import android.os.Build.VERSION_CODES;
 import android.view.View;
 
-import androidx.annotation.Nullable;
-
 import org.jni_zero.JNINamespace;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /** This class allows native code to discover the root view of the current Window. */
+@NullMarked
 @JNINamespace("base::android")
 public class InputHintChecker {
 
@@ -97,7 +99,7 @@
 
     @NativeMethods
     public interface Natives {
-        void setView(Object view);
+        void setView(@Nullable Object view);
 
         void onCompositorViewHolderTouchEvent();
 
diff --git a/tot/base/android/java/src/org/chromium/base/IntStringCallback.java b/tot/base/android/java/src/org/chromium/base/IntStringCallback.java
index 2022d94..6664934 100644
--- a/tot/base/android/java/src/org/chromium/base/IntStringCallback.java
+++ b/tot/base/android/java/src/org/chromium/base/IntStringCallback.java
@@ -5,6 +5,9 @@
 package org.chromium.base;
 
 import org.jni_zero.CalledByNative;
+import org.jni_zero.JniType;
+
+import org.chromium.build.annotations.NullMarked;
 
 /**
  * A simple 2-argument callback with an int and a String as arguments.
@@ -17,6 +20,7 @@
  * 2-argument callback also adds a few code lines but it is clear and the compiler does the type
  * checking.
  */
+@NullMarked
 public interface IntStringCallback {
     /**
      * Invoked with the result of a computation.
@@ -25,5 +29,5 @@
      * @param string String part of the result.
      */
     @CalledByNative
-    void onResult(int number, String string);
+    void onResult(int number, @JniType("std::string") String string);
 }
diff --git a/tot/base/android/java/src/org/chromium/base/IntentUtils.java b/tot/base/android/java/src/org/chromium/base/IntentUtils.java
index 3cadec1..efb1318 100644
--- a/tot/base/android/java/src/org/chromium/base/IntentUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/IntentUtils.java
@@ -19,12 +19,14 @@
 import android.os.TransactionTooLargeException;
 import android.text.TextUtils;
 
-import androidx.annotation.Nullable;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.io.Serializable;
 import java.util.ArrayList;
 
 /** Utilities dealing with extracting information from intents and creating common intents. */
+@NullMarked
 public class IntentUtils {
     private static final String TAG = "IntentUtils";
 
@@ -35,7 +37,7 @@
     public static final String TRUSTED_APPLICATION_CODE_EXTRA = "trusted_application_code_extra";
 
     /** Fake ComponentName used in constructing TRUSTED_APPLICATION_CODE_EXTRA. */
-    private static ComponentName sFakeComponentName;
+    private static @Nullable ComponentName sFakeComponentName;
 
     private static final Object COMPONENT_NAME_LOCK = new Object();
 
@@ -107,7 +109,7 @@
     }
 
     /** Just like {@link Intent#getIntArrayExtra(String)} but doesn't throw exceptions. */
-    public static int[] safeGetIntArrayExtra(Intent intent, String name) {
+    public static int @Nullable [] safeGetIntArrayExtra(Intent intent, String name) {
         try {
             return intent.getIntArrayExtra(name);
         } catch (Throwable t) {
@@ -118,7 +120,7 @@
     }
 
     /** Just like {@link Bundle#getIntArray(String)} but doesn't throw exceptions. */
-    public static int[] safeGetIntArray(Bundle bundle, String name) {
+    public static int @Nullable [] safeGetIntArray(Bundle bundle, String name) {
         try {
             return bundle.getIntArray(name);
         } catch (Throwable t) {
@@ -129,7 +131,7 @@
     }
 
     /** Just like {@link Bundle#getFloatArray(String)} but doesn't throw exceptions. */
-    public static float[] safeGetFloatArray(Bundle bundle, String name) {
+    public static float @Nullable [] safeGetFloatArray(Bundle bundle, String name) {
         try {
             return bundle.getFloatArray(name);
         } catch (Throwable t) {
@@ -162,7 +164,7 @@
     }
 
     /** Just like {@link Intent#getStringExtra(String)} but doesn't throw exceptions. */
-    public static String safeGetStringExtra(Intent intent, String name) {
+    public static @Nullable String safeGetStringExtra(Intent intent, String name) {
         try {
             return intent.getStringExtra(name);
         } catch (Throwable t) {
@@ -173,7 +175,7 @@
     }
 
     /** Just like {@link Bundle#getString(String)} but doesn't throw exceptions. */
-    public static String safeGetString(Bundle bundle, String name) {
+    public static @Nullable String safeGetString(Bundle bundle, String name) {
         try {
             return bundle.getString(name);
         } catch (Throwable t) {
@@ -184,7 +186,7 @@
     }
 
     /** Just like {@link Intent#getBundleExtra(String)} but doesn't throw exceptions. */
-    public static Bundle safeGetBundleExtra(Intent intent, String name) {
+    public static @Nullable Bundle safeGetBundleExtra(Intent intent, String name) {
         try {
             return intent.getBundleExtra(name);
         } catch (Throwable t) {
@@ -195,7 +197,7 @@
     }
 
     /** Just like {@link Bundle#getBundle(String)} but doesn't throw exceptions. */
-    public static Bundle safeGetBundle(Bundle bundle, String name) {
+    public static @Nullable Bundle safeGetBundle(Bundle bundle, String name) {
         try {
             return bundle.getBundle(name);
         } catch (Throwable t) {
@@ -206,7 +208,7 @@
     }
 
     /** Just like {@link Bundle#getParcelable(String)} but doesn't throw exceptions. */
-    public static <T extends Parcelable> T safeGetParcelable(Bundle bundle, String name) {
+    public static <T extends Parcelable> @Nullable T safeGetParcelable(Bundle bundle, String name) {
         try {
             return bundle.getParcelable(name);
         } catch (Throwable t) {
@@ -217,7 +219,8 @@
     }
 
     /** Just like {@link Intent#getParcelableExtra(String)} but doesn't throw exceptions. */
-    public static <T extends Parcelable> T safeGetParcelableExtra(Intent intent, String name) {
+    public static <T extends Parcelable> @Nullable T safeGetParcelableExtra(
+            Intent intent, String name) {
         try {
             return intent.getParcelableExtra(name);
         } catch (Throwable t) {
@@ -230,7 +233,7 @@
     /**
      * Just link {@link Intent#getParcelableArrayListExtra(String)} but doesn't throw exceptions.
      */
-    public static <T extends Parcelable> ArrayList<T> getParcelableArrayListExtra(
+    public static <T extends Parcelable> @Nullable ArrayList<T> getParcelableArrayListExtra(
             Intent intent, String name) {
         try {
             return intent.getParcelableArrayListExtra(name);
@@ -242,7 +245,7 @@
     }
 
     /** Just link {@link Bundle#getParcelableArrayList(String)} but doesn't throw exceptions. */
-    public static <T extends Parcelable> ArrayList<T> safeGetParcelableArrayList(
+    public static <T extends Parcelable> @Nullable ArrayList<T> safeGetParcelableArrayList(
             Bundle bundle, String name) {
         try {
             return bundle.getParcelableArrayList(name);
@@ -254,7 +257,7 @@
     }
 
     /** Just like {@link Intent#getParcelableArrayExtra(String)} but doesn't throw exceptions. */
-    public static Parcelable[] safeGetParcelableArrayExtra(Intent intent, String name) {
+    public static Parcelable @Nullable [] safeGetParcelableArrayExtra(Intent intent, String name) {
         try {
             return intent.getParcelableArrayExtra(name);
         } catch (Throwable t) {
@@ -264,7 +267,8 @@
     }
 
     /** Just like {@link Intent#getStringArrayListExtra(String)} but doesn't throw exceptions. */
-    public static ArrayList<String> safeGetStringArrayListExtra(Intent intent, String name) {
+    public static @Nullable ArrayList<String> safeGetStringArrayListExtra(
+            Intent intent, String name) {
         try {
             return intent.getStringArrayListExtra(name);
         } catch (Throwable t) {
@@ -275,7 +279,7 @@
     }
 
     /** Just like {@link Intent#getByteArrayExtra(String)} but doesn't throw exceptions. */
-    public static byte[] safeGetByteArrayExtra(Intent intent, String name) {
+    public static byte @Nullable [] safeGetByteArrayExtra(Intent intent, String name) {
         try {
             return intent.getByteArrayExtra(name);
         } catch (Throwable t) {
@@ -287,7 +291,8 @@
 
     /** Just like {@link Intent#getSerializableExtra(String)} but doesn't throw exceptions. */
     @SuppressWarnings("unchecked")
-    public static <T extends Serializable> T safeGetSerializableExtra(Intent intent, String name) {
+    public static <T extends Serializable> @Nullable T safeGetSerializableExtra(
+            Intent intent, String name) {
         try {
             return (T) intent.getSerializableExtra(name);
         } catch (ClassCastException ex) {
@@ -307,7 +312,7 @@
      * @param name a key string
      * @return an IBinder value, or null
      */
-    public static IBinder safeGetBinder(Bundle bundle, String name) {
+    public static @Nullable IBinder safeGetBinder(@Nullable Bundle bundle, String name) {
         if (bundle == null) return null;
         try {
             return bundle.getBinder(name);
@@ -324,7 +329,7 @@
      * Creates a temporary copy of the extra Bundle, which is required as
      * Intent#getBinderExtra() doesn't exist, but Bundle.getBinder() does.
      */
-    public static IBinder safeGetBinderExtra(Intent intent, String name) {
+    public static @Nullable IBinder safeGetBinderExtra(Intent intent, String name) {
         if (!intent.hasExtra(name)) return null;
         Bundle extras = intent.getExtras();
         return safeGetBinder(extras, name);
@@ -416,7 +421,7 @@
      * make it safe to use.
      * @return A safe to use version of this intent.
      */
-    public static Intent sanitizeIntent(final Intent incomingIntent) {
+    public static @Nullable Intent sanitizeIntent(final Intent incomingIntent) {
         // On Android T+, items are only deserialized when the items themselves are queried, so the
         // code below is a no-op.
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) return incomingIntent;
@@ -463,17 +468,16 @@
     /**
      * Determines whether this app is the only possible handler for this Intent.
      *
-     * @param context Any context for this app.
      * @param intent The intent to check.
      * @return True if the intent targets this app.
      */
-    public static boolean intentTargetsSelf(Context context, Intent intent) {
+    public static boolean intentTargetsSelf(Intent intent) {
         boolean hasPackage = !TextUtils.isEmpty(intent.getPackage());
-        boolean matchesPackage = hasPackage && context.getPackageName().equals(intent.getPackage());
-        boolean hasComponent = intent.getComponent() != null;
+        String appPackage = BuildInfo.getInstance().hostPackageName;
+        boolean matchesPackage = hasPackage && appPackage.equals(intent.getPackage());
+        ComponentName componentName = intent.getComponent();
         boolean matchesComponent =
-                hasComponent
-                        && context.getPackageName().equals(intent.getComponent().getPackageName());
+                componentName != null && appPackage.equals(componentName.getPackageName());
 
         // Component takes precedence over PackageName when routing Intents if both are set, but to
         // be on the safe side, ensure that if we have both package and component set, that they
@@ -488,8 +492,8 @@
             return true;
         }
         if (matchesPackage) {
-            assert !hasComponent;
-            return !hasComponent;
+            assert componentName == null;
+            return true;
         }
         return false;
     }
@@ -522,8 +526,7 @@
     public static void addTrustedIntentExtras(Intent intent) {
         // It is crucial that we never leak the authentication token to other packages, because
         // then the other package could be used to impersonate us/do things as us.
-        boolean toSelf =
-                IntentUtils.intentTargetsSelf(ContextUtils.getApplicationContext(), intent);
+        boolean toSelf = IntentUtils.intentTargetsSelf(intent);
         assert toSelf;
         // For security reasons we have to check the asserted condition anyways.
         if (!toSelf) return;
diff --git a/tot/base/android/java/src/org/chromium/base/JNIUtils.java b/tot/base/android/java/src/org/chromium/base/JNIUtils.java
index db0b936..7c694f2 100644
--- a/tot/base/android/java/src/org/chromium/base/JNIUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/JNIUtils.java
@@ -5,11 +5,18 @@
 package org.chromium.base;
 
 import org.jni_zero.CalledByNative;
+import org.jni_zero.JNINamespace;
+import org.jni_zero.JniType;
+
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /** This class provides JNI-related methods to the native library. */
+@NullMarked
+@JNINamespace("base::android")
 public class JNIUtils {
     private static final String TAG = "JNIUtils";
-    private static ClassLoader sJniClassLoader;
+    private static final JniClassLoader sJniClassLoader = new JniClassLoader();
 
     /**
      * Returns a ClassLoader which can load Java classes from the specified split.
@@ -17,7 +24,7 @@
      * @param splitName Name of the split, or empty string for the base split.
      */
     @CalledByNative
-    private static ClassLoader getSplitClassLoader(String splitName) {
+    private static ClassLoader getSplitClassLoader(@JniType("std::string") String splitName) {
         if (!splitName.isEmpty()) {
             boolean isInstalled = BundleUtils.isIsolatedSplitInstalled(splitName);
             Log.i(TAG, "Init JNI Classloader for %s. isInstalled=%b", splitName, isInstalled);
@@ -32,7 +39,7 @@
                 // is very out of date.
             }
         }
-        return sJniClassLoader != null ? sJniClassLoader : JNIUtils.class.getClassLoader();
+        return sJniClassLoader;
     }
 
     /**
@@ -40,7 +47,30 @@
      *
      * @param classLoader the ClassLoader to use.
      */
-    public static void setClassLoader(ClassLoader classLoader) {
-        sJniClassLoader = classLoader;
+    public static void setDefaultClassLoader(ClassLoader classLoader) {
+        sJniClassLoader.mDelegate = classLoader;
+    }
+
+    /**
+     * Allows swapping out the underlying class loader to a an apk split's class loader without
+     * having to invalidate the native code's caching of the class loader (which may or may not
+     * have happened yet).
+     */
+    private static class JniClassLoader extends ClassLoader {
+        @Nullable ClassLoader mDelegate;
+
+        JniClassLoader() {
+            super(JNIUtils.class.getClassLoader());
+        }
+
+        // ClassLoader.loadClass() delegates to this method.
+        @Override
+        public Class<?> findClass(String cn) throws ClassNotFoundException {
+            ClassLoader delegate = mDelegate;
+            if (delegate != null) {
+                return delegate.loadClass(cn);
+            }
+            return super.findClass(cn);
+        }
     }
 }
diff --git a/tot/base/android/java/src/org/chromium/base/JavaExceptionReporter.java b/tot/base/android/java/src/org/chromium/base/JavaExceptionReporter.java
index ad636d6..0de0138 100644
--- a/tot/base/android/java/src/org/chromium/base/JavaExceptionReporter.java
+++ b/tot/base/android/java/src/org/chromium/base/JavaExceptionReporter.java
@@ -13,6 +13,9 @@
 import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /**
  * This UncaughtExceptionHandler will create a breakpad minidump when there is an uncaught
  * exception.
@@ -20,6 +23,7 @@
  * <p>The exception's stack trace will be added to the minidump's data. This allows java-only
  * crashes to be reported in the same way as other native crashes.
  */
+@NullMarked
 @JNINamespace("base::android")
 public class JavaExceptionReporter implements Thread.UncaughtExceptionHandler {
     private final Thread.UncaughtExceptionHandler mParent;
@@ -102,7 +106,7 @@
 
     @NativeMethods
     interface Natives {
-        void reportJavaException(boolean crashAfterReport, Throwable e);
+        void reportJavaException(boolean crashAfterReport, @Nullable Throwable e);
 
         void reportJavaStackTrace(@JniType("std::string") String stackTrace);
     }
diff --git a/tot/base/android/java/src/org/chromium/base/JavaHandlerThread.java b/tot/base/android/java/src/org/chromium/base/JavaHandlerThread.java
index 377eebd..80dc90b 100644
--- a/tot/base/android/java/src/org/chromium/base/JavaHandlerThread.java
+++ b/tot/base/android/java/src/org/chromium/base/JavaHandlerThread.java
@@ -13,14 +13,18 @@
 import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.lang.Thread.UncaughtExceptionHandler;
 
 /** Thread in Java with an Android Handler. This class is not thread safe. */
+@NullMarked
 @JNINamespace("base::android")
 public class JavaHandlerThread {
     private final HandlerThread mThread;
 
-    private Throwable mUnhandledException;
+    private @Nullable Throwable mUnhandledException;
 
     /**
      * Construct a java-only instance. Can be connected with native side later.
@@ -111,7 +115,7 @@
     }
 
     @CalledByNative
-    private Throwable getUncaughtExceptionIfAny() {
+    private @Nullable Throwable getUncaughtExceptionIfAny() {
         return mUnhandledException;
     }
 
diff --git a/tot/base/android/java/src/org/chromium/base/JavaUtils.java b/tot/base/android/java/src/org/chromium/base/JavaUtils.java
index a813eff..30939f3 100644
--- a/tot/base/android/java/src/org/chromium/base/JavaUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/JavaUtils.java
@@ -4,6 +4,9 @@
 
 package org.chromium.base;
 
+import org.chromium.build.annotations.NullMarked;
+
+@NullMarked
 public class JavaUtils {
     private JavaUtils() {}
 
diff --git a/tot/base/android/java/src/org/chromium/base/JniAndroid.java b/tot/base/android/java/src/org/chromium/base/JniAndroid.java
index 9cd89c1..c236109 100644
--- a/tot/base/android/java/src/org/chromium/base/JniAndroid.java
+++ b/tot/base/android/java/src/org/chromium/base/JniAndroid.java
@@ -5,8 +5,13 @@
 package org.chromium.base;
 
 import org.jni_zero.CalledByNative;
+import org.jni_zero.JniType;
+
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /** Provides Java-side code to back `jni_android` native logic. */
+@NullMarked
 public final class JniAndroid {
     private JniAndroid() {}
 
@@ -21,7 +26,8 @@
      * effort not to throw; instead, any failures will be surfaced through the returned string.
      */
     @CalledByNative
-    private static String sanitizedStacktraceForUnhandledException(Throwable throwable) {
+    private static @Nullable @JniType("std::string") String
+            sanitizedStacktraceForUnhandledException(Throwable throwable) {
         if (sSimulateOomInSanitizedStacktraceForTesting) {
             return null;
         }
@@ -75,7 +81,8 @@
      *     OutOfMemoryError exception, in which case that exception is returned.
      */
     @CalledByNative
-    private static Throwable handleException(Throwable throwable, String nativeStackTrace) {
+    private static @Nullable Throwable handleException(
+            Throwable throwable, @JniType("std::string") String nativeStackTrace) {
         try {
             // Try to make sure the exception details at least make their way to the log even if the
             // rest of this method goes horribly wrong.
diff --git a/tot/base/android/java/src/org/chromium/base/JniCallbackUtils.java b/tot/base/android/java/src/org/chromium/base/JniCallbackUtils.java
new file mode 100644
index 0000000..d5e99b6
--- /dev/null
+++ b/tot/base/android/java/src/org/chromium/base/JniCallbackUtils.java
@@ -0,0 +1,45 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.base;
+
+import org.jni_zero.JNINamespace;
+import org.jni_zero.NativeMethods;
+
+import org.chromium.build.annotations.NullMarked;
+
+@JNINamespace("base::android")
+@NullMarked
+final class JniCallbackUtils {
+
+    static void runNativeCallback(JniOnceCallback callback, Object result) {
+        assert callback.mNativePointer != 0;
+        JniCallbackUtilsJni.get().onResult(callback.mNativePointer, false, result);
+        callback.mNativePointer = 0;
+    }
+
+    static void runNativeCallback(JniRepeatingCallback callback, Object result) {
+        assert callback.mNativePointer != 0;
+        JniCallbackUtilsJni.get().onResult(callback.mNativePointer, true, result);
+    }
+
+    static void destroyNativeCallback(JniOnceCallback callback) {
+        assert callback.mNativePointer != 0;
+        JniCallbackUtilsJni.get().destroy(callback.mNativePointer, false);
+        callback.mNativePointer = 0;
+    }
+
+    static void destroyNativeCallback(JniRepeatingCallback callback) {
+        assert callback.mNativePointer != 0;
+        JniCallbackUtilsJni.get().destroy(callback.mNativePointer, true);
+        callback.mNativePointer = 0;
+    }
+
+    @NativeMethods
+    interface Natives {
+        void onResult(long callbackPtr, boolean isRepeating, Object result);
+
+        void destroy(long callbackPtr, boolean isRepeating);
+    }
+}
diff --git a/tot/base/android/java/src/org/chromium/base/JniOnceCallback.java b/tot/base/android/java/src/org/chromium/base/JniOnceCallback.java
new file mode 100644
index 0000000..d298bbd
--- /dev/null
+++ b/tot/base/android/java/src/org/chromium/base/JniOnceCallback.java
@@ -0,0 +1,53 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.base;
+
+import org.jni_zero.CalledByNative;
+import org.jni_zero.JNINamespace;
+
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
+/*
+ * A wrapper that owns a native side base::OnceCallback.
+ *
+ * You must call JniOnceCallback#destroy() if you never end up calling onResult
+ * so as to not leak the native callback.
+ *
+ * This class has no additional thread safety measures compared to
+ * base::RepeatingCallback.
+ */
+@JNINamespace("base::android")
+@NullMarked
+public final class JniOnceCallback<T extends @Nullable Object> implements Callback<T> {
+    private final @Nullable LifetimeAssert mLifetimeAssert = LifetimeAssert.create(this);
+    long mNativePointer;
+
+    @CalledByNative
+    private JniOnceCallback(long nativePointer) {
+        mNativePointer = nativePointer;
+    }
+
+    @Override
+    public void onResult(T result) {
+        if (mNativePointer != 0) {
+            JniCallbackUtils.runNativeCallback(this, result);
+            mNativePointer = 0;
+            LifetimeAssert.setSafeToGc(mLifetimeAssert, true);
+        } else {
+            // TODO(mheikal): maybe store destroy callstack to output here?
+            assert false : "Called destroyed callback";
+        }
+    }
+
+    /** Frees the owned base::OnceCallback's memory */
+    public void destroy() {
+        if (mNativePointer != 0) {
+            JniCallbackUtils.destroyNativeCallback(this);
+            mNativePointer = 0;
+        }
+        LifetimeAssert.setSafeToGc(mLifetimeAssert, true);
+    }
+}
diff --git a/tot/base/android/java/src/org/chromium/base/JniRepeatingCallback.java b/tot/base/android/java/src/org/chromium/base/JniRepeatingCallback.java
new file mode 100644
index 0000000..1f4f17c
--- /dev/null
+++ b/tot/base/android/java/src/org/chromium/base/JniRepeatingCallback.java
@@ -0,0 +1,51 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.base;
+
+import org.jni_zero.CalledByNative;
+import org.jni_zero.JNINamespace;
+
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
+/*
+ * A wrapper that owns a native side base::RepeatingCallback.
+ *
+ * You must call JniRepeatingCallback#destroy() when you are done with it to
+ * not leak the native callback.
+ *
+ * This class has no additional thread safety measures compared to
+ * base::RepeatingCallback.
+ */
+@JNINamespace("base::android")
+@NullMarked
+public class JniRepeatingCallback<T extends @Nullable Object> implements Callback<T> {
+    private final @Nullable LifetimeAssert mLifetimeAssert = LifetimeAssert.create(this);
+    long mNativePointer;
+
+    @CalledByNative
+    private JniRepeatingCallback(long nativePointer) {
+        mNativePointer = nativePointer;
+    }
+
+    @Override
+    public void onResult(T result) {
+        if (mNativePointer != 0) {
+            JniCallbackUtils.runNativeCallback(this, result);
+        } else {
+            // TODO(mheikal): maybe store destroy callstack to output here?
+            assert false : "Called destroyed callback";
+        }
+    }
+
+    /** Frees the owned base::RepeatingCallback's memory */
+    public void destroy() {
+        if (mNativePointer != 0) {
+            JniCallbackUtils.destroyNativeCallback(this);
+            mNativePointer = 0;
+        }
+        LifetimeAssert.setSafeToGc(mLifetimeAssert, true);
+    }
+}
diff --git a/tot/base/android/java/src/org/chromium/base/LifetimeAssert.java b/tot/base/android/java/src/org/chromium/base/LifetimeAssert.java
index ae5a60b..724285b 100644
--- a/tot/base/android/java/src/org/chromium/base/LifetimeAssert.java
+++ b/tot/base/android/java/src/org/chromium/base/LifetimeAssert.java
@@ -9,6 +9,8 @@
 import org.chromium.base.task.PostTask;
 import org.chromium.build.BuildConfig;
 import org.chromium.build.annotations.CheckDiscard;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.lang.ref.PhantomReference;
 import java.lang.ref.ReferenceQueue;
@@ -32,10 +34,11 @@
  * }
  * </pre>
  */
+@NullMarked
 @CheckDiscard("Lifetime assertions aren't used when DCHECK is off.")
 public class LifetimeAssert {
     interface TestHook {
-        void onCleaned(WrappedReference ref, String msg);
+        void onCleaned(WrappedReference ref, @Nullable String msg);
     }
 
     /** Thrown for failed assertions. */
@@ -53,7 +56,7 @@
     }
 
     // Used only for unit test.
-    static TestHook sTestHook;
+    static @Nullable TestHook sTestHook;
 
     @VisibleForTesting final WrappedReference mWrapper;
 
@@ -126,7 +129,7 @@
         mTarget = target;
     }
 
-    public static LifetimeAssert create(Object target) {
+    public static @Nullable LifetimeAssert create(Object target) {
         if (!BuildConfig.ENABLE_ASSERTS) {
             return null;
         }
@@ -134,7 +137,7 @@
                 new WrappedReference(target, new CreationException(), false), target);
     }
 
-    public static LifetimeAssert create(Object target, boolean safeToGc) {
+    public static @Nullable LifetimeAssert create(Object target, boolean safeToGc) {
         if (!BuildConfig.ENABLE_ASSERTS) {
             return null;
         }
@@ -142,8 +145,9 @@
                 new WrappedReference(target, new CreationException(), safeToGc), target);
     }
 
-    public static void setSafeToGc(LifetimeAssert asserter, boolean value) {
+    public static void setSafeToGc(@Nullable LifetimeAssert asserter, boolean value) {
         if (BuildConfig.ENABLE_ASSERTS) {
+            assert asserter != null;
             // This guaratees that the target object is reachable until after mSafeToGc value
             // is updated here. See comment on Reference.reachabilityFence and review comments
             // on https://chromium-review.googlesource.com/c/chromium/src/+/1887151 for a
diff --git a/tot/base/android/java/src/org/chromium/base/LocaleUtils.java b/tot/base/android/java/src/org/chromium/base/LocaleUtils.java
index 10999cb..6aeff65 100644
--- a/tot/base/android/java/src/org/chromium/base/LocaleUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/LocaleUtils.java
@@ -14,11 +14,15 @@
 import androidx.annotation.VisibleForTesting;
 
 import org.jni_zero.CalledByNative;
+import org.jni_zero.JniType;
+
+import org.chromium.build.annotations.NullMarked;
 
 import java.util.ArrayList;
 import java.util.Locale;
 
 /** This class provides the locale related methods. */
+@NullMarked
 public class LocaleUtils {
     /** Guards this class from being instantiated. */
     private LocaleUtils() {}
@@ -169,22 +173,20 @@
     }
 
     /**
-     * @return a language tag string that represents the default locale.
-     *         The language tag is well-formed IETF BCP 47 language tag with language and country
-     *         code.
+     * @return a language tag string that represents the default locale. The language tag is
+     *     well-formed IETF BCP 47 language tag with language and country code.
      */
     @CalledByNative
-    public static String getDefaultLocaleString() {
+    public static @JniType("std::string") String getDefaultLocaleString() {
         return toLanguageTag(Locale.getDefault());
     }
 
     /**
      * @return a comma separated language tags string that represents a default locale or locales.
-     *         Each language tag is well-formed IETF BCP 47 language tag with language and country
-     *         code.
+     *     Each language tag is well-formed IETF BCP 47 language tag with language and country code.
      */
     @CalledByNative
-    public static String getDefaultLocaleListString() {
+    public static @JniType("std::string") String getDefaultLocaleListString() {
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
             return toLanguageTags(LocaleList.getDefault());
         }
@@ -195,11 +197,11 @@
      * @return The default country code set during install.
      */
     @CalledByNative
-    public static String getDefaultCountryCode() {
+    public static @JniType("std::string") String getDefaultCountryCode() {
         CommandLine commandLine = CommandLine.getInstance();
-        return commandLine.hasSwitch(BaseSwitches.DEFAULT_COUNTRY_CODE_AT_INSTALL)
-                ? commandLine.getSwitchValue(BaseSwitches.DEFAULT_COUNTRY_CODE_AT_INSTALL)
-                : Locale.getDefault().getCountry();
+        String commandLineSwitch =
+                commandLine.getSwitchValue(BaseSwitches.DEFAULT_COUNTRY_CODE_AT_INSTALL);
+        return commandLineSwitch != null ? commandLineSwitch : Locale.getDefault().getCountry();
     }
 
     /**
diff --git a/tot/base/android/java/src/org/chromium/base/Log.java b/tot/base/android/java/src/org/chromium/base/Log.java
index 533f9c7..8a8c06f 100644
--- a/tot/base/android/java/src/org/chromium/base/Log.java
+++ b/tot/base/android/java/src/org/chromium/base/Log.java
@@ -4,10 +4,10 @@
 
 package org.chromium.base;
 
-import androidx.annotation.Nullable;
-
 import org.chromium.build.BuildConfig;
 import org.chromium.build.annotations.AlwaysInline;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.Locale;
 
@@ -20,6 +20,7 @@
  *
  * <p>Usage documentation: {@code //docs/android_logging.md}.
  */
+@NullMarked
 public class Log {
     /** Convenience property, same as {@link android.util.Log#ASSERT}. */
     public static final int ASSERT = android.util.Log.ASSERT;
@@ -45,7 +46,7 @@
 
     /** Returns a formatted log message, using the supplied format and arguments. */
     private static String formatLog(
-            String messageTemplate, @Nullable Throwable tr, @Nullable Object... params) {
+            String messageTemplate, @Nullable Throwable tr, @Nullable Object @Nullable [] params) {
         if ((params != null) && ((tr == null && params.length > 0) || params.length > 1)) {
             messageTemplate = String.format(Locale.US, messageTemplate, params);
         }
@@ -87,7 +88,7 @@
      * @param args Arguments referenced by the format specifiers in the format string. If the last
      *     one is a {@link Throwable}, its trace will be printed.
      */
-    public static void v(String tag, String messageTemplate, Object... args) {
+    public static void v(String tag, String messageTemplate, @Nullable Object @Nullable ... args) {
         if (!isLoggable(tag, VERBOSE)) return;
 
         Throwable tr = getThrowableToLog(args);
@@ -110,7 +111,7 @@
      * @param args Arguments referenced by the format specifiers in the format string. If the last
      *     one is a {@link Throwable}, its trace will be printed.
      */
-    public static void d(String tag, String messageTemplate, Object... args) {
+    public static void d(String tag, String messageTemplate, @Nullable Object @Nullable ... args) {
         if (!isLoggable(tag, DEBUG)) return;
 
         Throwable tr = getThrowableToLog(args);
@@ -133,7 +134,7 @@
      * @param args Arguments referenced by the format specifiers in the format string. If the last
      *             one is a {@link Throwable}, its trace will be printed.
      */
-    public static void i(String tag, String messageTemplate, Object... args) {
+    public static void i(String tag, String messageTemplate, @Nullable Object... args) {
         Throwable tr = getThrowableToLog(args);
         String message = formatLog(messageTemplate, tr, args);
         tag = normalizeTag(tag);
@@ -159,33 +160,42 @@
     }
 
     @AlwaysInline
-    public static void i(String tag, String messageTemplate, Object param1) {
+    public static void i(String tag, String messageTemplate, @Nullable Object param1) {
         tag = normalizeTag(tag);
         android.util.Log.i(tag, String.format(Locale.US, messageTemplate, param1));
     }
 
     @AlwaysInline
-    public static void i(String tag, String messageTemplate, Object param1, Throwable t) {
+    public static void i(String tag, String messageTemplate, @Nullable Object param1, Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.i(tag, String.format(Locale.US, messageTemplate, param1), t);
     }
 
     @AlwaysInline
-    public static void i(String tag, String messageTemplate, Object param1, Object param2) {
+    public static void i(
+            String tag, String messageTemplate, @Nullable Object param1, @Nullable Object param2) {
         tag = normalizeTag(tag);
         android.util.Log.i(tag, String.format(Locale.US, messageTemplate, param1, param2));
     }
 
     @AlwaysInline
     public static void i(
-            String tag, String messageTemplate, Object param1, Object param2, Throwable t) {
+            String tag,
+            String messageTemplate,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.i(tag, String.format(Locale.US, messageTemplate, param1, param2), t);
     }
 
     @AlwaysInline
     public static void i(
-            String tag, String messageTemplate, Object param1, Object param2, Object param3) {
+            String tag,
+            String messageTemplate,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3) {
         tag = normalizeTag(tag);
         android.util.Log.i(tag, String.format(Locale.US, messageTemplate, param1, param2, param3));
     }
@@ -194,9 +204,9 @@
     public static void i(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.i(
@@ -207,10 +217,10 @@
     public static void i(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4) {
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4) {
         tag = normalizeTag(tag);
         android.util.Log.i(
                 tag, String.format(Locale.US, messageTemplate, param1, param2, param3, param4));
@@ -220,10 +230,10 @@
     public static void i(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.i(
@@ -234,11 +244,11 @@
     public static void i(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5) {
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5) {
         tag = normalizeTag(tag);
         android.util.Log.i(
                 tag,
@@ -249,11 +259,11 @@
     public static void i(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.i(
@@ -266,12 +276,12 @@
     public static void i(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5,
-            Object param6) {
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5,
+            @Nullable Object param6) {
         tag = normalizeTag(tag);
         android.util.Log.i(
                 tag,
@@ -290,12 +300,12 @@
     public static void i(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5,
-            Object param6,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5,
+            @Nullable Object param6,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.i(
@@ -342,33 +352,42 @@
     }
 
     @AlwaysInline
-    public static void w(String tag, String messageTemplate, Object param1) {
+    public static void w(String tag, String messageTemplate, @Nullable Object param1) {
         tag = normalizeTag(tag);
         android.util.Log.w(tag, String.format(Locale.US, messageTemplate, param1));
     }
 
     @AlwaysInline
-    public static void w(String tag, String messageTemplate, Object param1, Throwable t) {
+    public static void w(String tag, String messageTemplate, @Nullable Object param1, Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.w(tag, String.format(Locale.US, messageTemplate, param1), t);
     }
 
     @AlwaysInline
-    public static void w(String tag, String messageTemplate, Object param1, Object param2) {
+    public static void w(
+            String tag, String messageTemplate, @Nullable Object param1, @Nullable Object param2) {
         tag = normalizeTag(tag);
         android.util.Log.w(tag, String.format(Locale.US, messageTemplate, param1, param2));
     }
 
     @AlwaysInline
     public static void w(
-            String tag, String messageTemplate, Object param1, Object param2, Throwable t) {
+            String tag,
+            String messageTemplate,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.w(tag, String.format(Locale.US, messageTemplate, param1, param2), t);
     }
 
     @AlwaysInline
     public static void w(
-            String tag, String messageTemplate, Object param1, Object param2, Object param3) {
+            String tag,
+            String messageTemplate,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3) {
         tag = normalizeTag(tag);
         android.util.Log.w(tag, String.format(Locale.US, messageTemplate, param1, param2, param3));
     }
@@ -377,9 +396,9 @@
     public static void w(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.w(
@@ -390,10 +409,10 @@
     public static void w(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4) {
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4) {
         tag = normalizeTag(tag);
         android.util.Log.w(
                 tag, String.format(Locale.US, messageTemplate, param1, param2, param3, param4));
@@ -403,10 +422,10 @@
     public static void w(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.w(
@@ -417,11 +436,11 @@
     public static void w(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5) {
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5) {
         tag = normalizeTag(tag);
         android.util.Log.w(
                 tag,
@@ -432,11 +451,11 @@
     public static void w(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.w(
@@ -449,12 +468,12 @@
     public static void w(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5,
-            Object param6) {
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5,
+            @Nullable Object param6) {
         tag = normalizeTag(tag);
         android.util.Log.w(
                 tag,
@@ -473,12 +492,12 @@
     public static void w(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5,
-            Object param6,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5,
+            @Nullable Object param6,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.w(
@@ -524,33 +543,42 @@
     }
 
     @AlwaysInline
-    public static void e(String tag, String messageTemplate, Object param1) {
+    public static void e(String tag, String messageTemplate, @Nullable Object param1) {
         tag = normalizeTag(tag);
         android.util.Log.e(tag, String.format(Locale.US, messageTemplate, param1));
     }
 
     @AlwaysInline
-    public static void e(String tag, String messageTemplate, Object param1, Throwable t) {
+    public static void e(String tag, String messageTemplate, @Nullable Object param1, Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.e(tag, String.format(Locale.US, messageTemplate, param1), t);
     }
 
     @AlwaysInline
-    public static void e(String tag, String messageTemplate, Object param1, Object param2) {
+    public static void e(
+            String tag, String messageTemplate, @Nullable Object param1, @Nullable Object param2) {
         tag = normalizeTag(tag);
         android.util.Log.e(tag, String.format(Locale.US, messageTemplate, param1, param2));
     }
 
     @AlwaysInline
     public static void e(
-            String tag, String messageTemplate, Object param1, Object param2, Throwable t) {
+            String tag,
+            String messageTemplate,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.e(tag, String.format(Locale.US, messageTemplate, param1, param2), t);
     }
 
     @AlwaysInline
     public static void e(
-            String tag, String messageTemplate, Object param1, Object param2, Object param3) {
+            String tag,
+            String messageTemplate,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3) {
         tag = normalizeTag(tag);
         android.util.Log.e(tag, String.format(Locale.US, messageTemplate, param1, param2, param3));
     }
@@ -559,9 +587,9 @@
     public static void e(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.e(
@@ -572,10 +600,10 @@
     public static void e(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4) {
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4) {
         tag = normalizeTag(tag);
         android.util.Log.e(
                 tag, String.format(Locale.US, messageTemplate, param1, param2, param3, param4));
@@ -585,10 +613,10 @@
     public static void e(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.e(
@@ -599,11 +627,11 @@
     public static void e(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5) {
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5) {
         tag = normalizeTag(tag);
         android.util.Log.e(
                 tag,
@@ -614,11 +642,11 @@
     public static void e(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.e(
@@ -631,12 +659,12 @@
     public static void e(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5,
-            Object param6) {
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5,
+            @Nullable Object param6) {
         tag = normalizeTag(tag);
         android.util.Log.e(
                 tag,
@@ -655,12 +683,12 @@
     public static void e(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5,
-            Object param6,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5,
+            @Nullable Object param6,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.e(
@@ -711,33 +739,43 @@
     }
 
     @AlwaysInline
-    public static void wtf(String tag, String messageTemplate, Object param1) {
+    public static void wtf(String tag, String messageTemplate, @Nullable Object param1) {
         tag = normalizeTag(tag);
         android.util.Log.wtf(tag, String.format(Locale.US, messageTemplate, param1));
     }
 
     @AlwaysInline
-    public static void wtf(String tag, String messageTemplate, Object param1, Throwable t) {
+    public static void wtf(
+            String tag, String messageTemplate, @Nullable Object param1, Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.wtf(tag, String.format(Locale.US, messageTemplate, param1), t);
     }
 
     @AlwaysInline
-    public static void wtf(String tag, String messageTemplate, Object param1, Object param2) {
+    public static void wtf(
+            String tag, String messageTemplate, @Nullable Object param1, @Nullable Object param2) {
         tag = normalizeTag(tag);
         android.util.Log.wtf(tag, String.format(Locale.US, messageTemplate, param1, param2));
     }
 
     @AlwaysInline
     public static void wtf(
-            String tag, String messageTemplate, Object param1, Object param2, Throwable t) {
+            String tag,
+            String messageTemplate,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.wtf(tag, String.format(Locale.US, messageTemplate, param1, param2), t);
     }
 
     @AlwaysInline
     public static void wtf(
-            String tag, String messageTemplate, Object param1, Object param2, Object param3) {
+            String tag,
+            String messageTemplate,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3) {
         tag = normalizeTag(tag);
         android.util.Log.wtf(
                 tag, String.format(Locale.US, messageTemplate, param1, param2, param3));
@@ -747,9 +785,9 @@
     public static void wtf(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.wtf(
@@ -760,10 +798,10 @@
     public static void wtf(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4) {
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4) {
         tag = normalizeTag(tag);
         android.util.Log.wtf(
                 tag, String.format(Locale.US, messageTemplate, param1, param2, param3, param4));
@@ -773,10 +811,10 @@
     public static void wtf(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.wtf(
@@ -787,11 +825,11 @@
     public static void wtf(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5) {
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5) {
         tag = normalizeTag(tag);
         android.util.Log.wtf(
                 tag,
@@ -802,11 +840,11 @@
     public static void wtf(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.wtf(
@@ -819,12 +857,12 @@
     public static void wtf(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5,
-            Object param6) {
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5,
+            @Nullable Object param6) {
         tag = normalizeTag(tag);
         android.util.Log.wtf(
                 tag,
@@ -843,12 +881,12 @@
     public static void wtf(
             String tag,
             String messageTemplate,
-            Object param1,
-            Object param2,
-            Object param3,
-            Object param4,
-            Object param5,
-            Object param6,
+            @Nullable Object param1,
+            @Nullable Object param2,
+            @Nullable Object param3,
+            @Nullable Object param4,
+            @Nullable Object param5,
+            @Nullable Object param6,
             Throwable t) {
         tag = normalizeTag(tag);
         android.util.Log.wtf(
@@ -863,7 +901,7 @@
         return android.util.Log.getStackTraceString(tr);
     }
 
-    private static @Nullable Throwable getThrowableToLog(Object[] args) {
+    private static @Nullable Throwable getThrowableToLog(@Nullable Object @Nullable [] args) {
         if (args == null || args.length == 0) return null;
 
         Object lastArg = args[args.length - 1];
diff --git a/tot/base/android/java/src/org/chromium/base/MathUtils.java b/tot/base/android/java/src/org/chromium/base/MathUtils.java
index 5d30785..80803d0 100644
--- a/tot/base/android/java/src/org/chromium/base/MathUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/MathUtils.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Contains various math utilities used throughout Chrome Mobile. */
+@NullMarked
 public class MathUtils {
     /** A minimum difference to use when comparing floats for equality. */
     public static final float EPSILON = 0.001f;
diff --git a/tot/base/android/java/src/org/chromium/base/MemoryPressureListener.java b/tot/base/android/java/src/org/chromium/base/MemoryPressureListener.java
index 576dfb7..63a63cc 100644
--- a/tot/base/android/java/src/org/chromium/base/MemoryPressureListener.java
+++ b/tot/base/android/java/src/org/chromium/base/MemoryPressureListener.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.app.Activity;
 import android.content.ComponentCallbacks2;
 import android.os.Handler;
@@ -15,6 +17,8 @@
 import org.chromium.base.library_loader.LibraryLoader;
 import org.chromium.base.memory.MemoryPressureCallback;
 import org.chromium.base.memory.SelfFreezeCallback;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /**
  * This class is Java equivalent of base::MemoryPressureListener: it distributes signals to
@@ -30,6 +34,7 @@
  * main thread for Chrome, but can be some other thread for WebView), except for the self freeze
  * calls, which are done on the launcher thread.
  */
+@NullMarked
 public class MemoryPressureListener {
     /**
      * Sending an intent with this action to Chrome will cause it to issue a call to onLowMemory
@@ -57,10 +62,10 @@
     private static final String ACTION_TRIM_MEMORY_MODERATE =
             "org.chromium.base.ACTION_TRIM_MEMORY_MODERATE";
 
-    private static ObserverList<MemoryPressureCallback> sCallbacks;
+    private static @Nullable ObserverList<MemoryPressureCallback> sCallbacks;
     // This is used only on the Launcher thread.
-    private static ObserverList<SelfFreezeCallback> sSelfFreezeCallbacks;
-    private static volatile Handler sSelfFreezeHandler;
+    private static @Nullable ObserverList<SelfFreezeCallback> sSelfFreezeCallbacks;
+    private static volatile @Nullable Handler sSelfFreezeHandler;
 
     /** Called by the native side to add native callback. */
     @CalledByNative
@@ -104,9 +109,8 @@
     }
 
     public static void removeSelfFreezeCallback(SelfFreezeCallback callback) {
-        assert sSelfFreezeCallbacks != null;
-        assert sSelfFreezeHandler.getLooper() == Looper.myLooper();
-        sSelfFreezeCallbacks.removeObserver(callback);
+        assert assumeNonNull(sSelfFreezeHandler).getLooper() == Looper.myLooper();
+        assumeNonNull(sSelfFreezeCallbacks).removeObserver(callback);
     }
 
     /**
diff --git a/tot/base/android/java/src/org/chromium/base/MutableBooleanParamWithSafeDefault.java b/tot/base/android/java/src/org/chromium/base/MutableBooleanParamWithSafeDefault.java
index fa38895..800bbf5 100644
--- a/tot/base/android/java/src/org/chromium/base/MutableBooleanParamWithSafeDefault.java
+++ b/tot/base/android/java/src/org/chromium/base/MutableBooleanParamWithSafeDefault.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Boolean {@link FeatureParam} that will return a default value before native is loaded. */
+@NullMarked
 public class MutableBooleanParamWithSafeDefault extends MutableParamWithSafeDefault<Boolean> {
     public MutableBooleanParamWithSafeDefault(
             FeatureMap featureMap, String featureName, String paramName, boolean defaultValue) {
diff --git a/tot/base/android/java/src/org/chromium/base/MutableFlagWithSafeDefault.java b/tot/base/android/java/src/org/chromium/base/MutableFlagWithSafeDefault.java
index 4f39576..f1910b3 100644
--- a/tot/base/android/java/src/org/chromium/base/MutableFlagWithSafeDefault.java
+++ b/tot/base/android/java/src/org/chromium/base/MutableFlagWithSafeDefault.java
@@ -4,6 +4,9 @@
 
 package org.chromium.base;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /**
  * Flags of this type are un-cached flags that may be called before native,
  * but not primarily. They have good default values to use before native is loaded,
@@ -13,9 +16,10 @@
  * or
  * if (!FeatureList.isInitialized() || SomeFeatureMap.isEnabled(featureName)).
  */
+@NullMarked
 public class MutableFlagWithSafeDefault extends Flag {
     private final boolean mDefaultValue;
-    private Boolean mInMemoryCachedValue;
+    private @Nullable Boolean mInMemoryCachedValue;
 
     public MutableFlagWithSafeDefault(
             FeatureMap featureMap, String featureName, boolean defaultValue) {
@@ -39,7 +43,7 @@
     @Override
     public boolean isEnabled() {
         if (mInMemoryCachedValue != null) return mInMemoryCachedValue;
-        if (FeatureList.hasTestFeature(mFeatureName)) {
+        if (FeatureOverrides.hasTestFeature(mFeatureName)) {
             return mFeatureMap.isEnabledInNative(mFeatureName);
         }
 
diff --git a/tot/base/android/java/src/org/chromium/base/MutableIntParamWithSafeDefault.java b/tot/base/android/java/src/org/chromium/base/MutableIntParamWithSafeDefault.java
index 1b2dbd6..a944141 100644
--- a/tot/base/android/java/src/org/chromium/base/MutableIntParamWithSafeDefault.java
+++ b/tot/base/android/java/src/org/chromium/base/MutableIntParamWithSafeDefault.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Boolean {@link FeatureParam} that will return a default value before native is loaded. */
+@NullMarked
 public class MutableIntParamWithSafeDefault extends MutableParamWithSafeDefault<Integer> {
     public MutableIntParamWithSafeDefault(
             FeatureMap featureMap, String featureName, String paramName, int defaultValue) {
diff --git a/tot/base/android/java/src/org/chromium/base/MutableParamWithSafeDefault.java b/tot/base/android/java/src/org/chromium/base/MutableParamWithSafeDefault.java
index 2adc1c9..63b71bf 100644
--- a/tot/base/android/java/src/org/chromium/base/MutableParamWithSafeDefault.java
+++ b/tot/base/android/java/src/org/chromium/base/MutableParamWithSafeDefault.java
@@ -4,7 +4,7 @@
 
 package org.chromium.base;
 
-import androidx.annotation.NonNull;
+import org.chromium.build.annotations.NullMarked;
 
 /**
  * Abstract class for params that have a safe default before native is loaded. Because param values
@@ -24,9 +24,10 @@
  *
  * @param <T> The boxed type of data behind held.
  */
+@NullMarked
 public abstract class MutableParamWithSafeDefault<T> extends FeatureParam<T> {
     public MutableParamWithSafeDefault(
-            FeatureMap featureMap, String featureName, String paramName, @NonNull T defaultValue) {
+            FeatureMap featureMap, String featureName, String paramName, T defaultValue) {
         super(featureMap, featureName, paramName, defaultValue);
     }
 
@@ -35,16 +36,16 @@
      * converts it to the correct data type. Should never return a null value, because caching
      * relies on null checks.
      */
-    protected abstract @NonNull T readValueFromFeatureMap();
+    protected abstract T readValueFromFeatureMap();
 
     /**
      * Returns the current value. Guaranteed to never be null. Subclasses should override this to
      * safely convert to their primitive type.
      */
-    protected @NonNull T getValueBoxed() {
+    protected T getValueBoxed() {
         if (mInMemoryCachedValue != null) return mInMemoryCachedValue;
 
-        if (FeatureList.hasTestParam(mFeatureName, mParamName)) {
+        if (FeatureOverrides.hasTestParam(mFeatureName, mParamName)) {
             return readValueFromFeatureMap();
         }
 
diff --git a/tot/base/android/java/src/org/chromium/base/ObserverList.java b/tot/base/android/java/src/org/chromium/base/ObserverList.java
index 1b383b3..75de4c2 100644
--- a/tot/base/android/java/src/org/chromium/base/ObserverList.java
+++ b/tot/base/android/java/src/org/chromium/base/ObserverList.java
@@ -4,6 +4,9 @@
 
 package org.chromium.base;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
@@ -26,10 +29,16 @@
  * This class is not threadsafe. Observers MUST be added, removed and will be notified on the same
  * thread this is created.
  *
+ * Normally this class would not need {@code extends @Nullable Object} for the template param E,
+ * but because addObserver and removeObserver take {@code @Nullable E obs} the annotation on the
+ * template param E is necessary for NullAway to work for users of this class. This can be removed
+ * in the future when NullAway improves its handling of generic template parameters.
+ *
  * @param <E> The type of observers that this list should hold.
  */
+@NullMarked
 @NotThreadSafe
-public class ObserverList<E> implements Iterable<E> {
+public class ObserverList<E extends @Nullable Object> implements Iterable<E> {
     /** Extended iterator interface that provides rewind functionality. */
     public interface RewindableIterator<E> extends Iterator<E> {
         /**
@@ -68,7 +77,7 @@
      *
      * @return true if the observer list changed as a result of the call.
      */
-    public boolean addObserver(E obs) {
+    public boolean addObserver(@Nullable E obs) {
         if (mEnableThreadAsserts) mThreadChecker.assertOnValidThread();
 
         // Avoid adding null elements to the list as they may be removed on a compaction.
@@ -90,7 +99,7 @@
      *
      * @return true if an element was removed as a result of this call.
      */
-    public boolean removeObserver(E obs) {
+    public boolean removeObserver(@Nullable E obs) {
         if (mEnableThreadAsserts) mThreadChecker.assertOnValidThread();
 
         if (obs == null) {
diff --git a/tot/base/android/java/src/org/chromium/base/PackageManagerUtils.java b/tot/base/android/java/src/org/chromium/base/PackageManagerUtils.java
index a467d72..85c04ea 100644
--- a/tot/base/android/java/src/org/chromium/base/PackageManagerUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/PackageManagerUtils.java
@@ -10,13 +10,19 @@
 import android.net.Uri;
 import android.os.TransactionTooLargeException;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.util.Collections;
 import java.util.List;
 
 /** This class provides Android PackageManager related utility methods. */
+@NullMarked
 public class PackageManagerUtils {
     public static final String XR_IMMERSIVE_FEATURE_NAME = "android.software.xr.immersive";
 
+    public static final String XR_OPENXR_FEATURE_NAME = "android.software.xr.api.openxr";
+
     private static final String TAG = "PackageManagerUtils";
 
     // This is the intent Android uses internally to detect browser apps.
@@ -38,7 +44,7 @@
      * @param flags The PackageManager flags to pass to resolveActivity().
      * @return       ResolveInfo of the Activity that will handle the Intent, or null if it failed.
      */
-    public static ResolveInfo resolveActivity(Intent intent, int flags) {
+    public static @Nullable ResolveInfo resolveActivity(Intent intent, int flags) {
         // On KitKat, calling PackageManager#resolveActivity() causes disk reads and
         // writes. Temporarily allow this while resolving the intent.
         try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) {
@@ -102,7 +108,7 @@
     /**
      * @return Default ResolveInfo to handle a VIEW intent for a url.
      */
-    public static ResolveInfo resolveDefaultWebBrowserActivity() {
+    public static @Nullable ResolveInfo resolveDefaultWebBrowserActivity() {
         return resolveActivity(BROWSER_INTENT, PackageManager.MATCH_DEFAULT_ONLY);
     }
 
diff --git a/tot/base/android/java/src/org/chromium/base/PackageUtils.java b/tot/base/android/java/src/org/chromium/base/PackageUtils.java
index 25bdfb6..eb13adc 100644
--- a/tot/base/android/java/src/org/chromium/base/PackageUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/PackageUtils.java
@@ -10,9 +10,11 @@
 import android.content.pm.Signature;
 import android.os.Build;
 
-import androidx.annotation.Nullable;
 import androidx.annotation.VisibleForTesting;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.io.ByteArrayInputStream;
 import java.io.InputStream;
 import java.lang.reflect.Method;
@@ -25,6 +27,7 @@
 import java.util.List;
 
 /** This class provides package checking related methods. */
+@NullMarked
 public class PackageUtils {
     private static final String TAG = "PackageUtils";
     private static final char[] HEX_CHAR_LOOKUP = "0123456789ABCDEF".toCharArray();
@@ -77,6 +80,18 @@
         return ret;
     }
 
+    /**
+     * Return the "long" version code of the given PackageInfo. Does the right thing for
+     * before/after Android P when this got wider.
+     */
+    public static long packageVersionCode(PackageInfo pi) {
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
+            return pi.getLongVersionCode();
+        } else {
+            return pi.versionCode;
+        }
+    }
+
     // Need to call an internal method to work around a framework bug.
     @SuppressWarnings("PrivateApi")
     public static void maybeWorkAroundWebViewPackageVisibility() {
@@ -109,7 +124,8 @@
      */
     @SuppressLint("PackageManagerGetSignatures")
     // https://stackoverflow.com/questions/39192844/android-studio-warning-when-using-packagemanager-get-signatures
-    public static List<String> getCertificateSHA256FingerprintForPackage(String packageName) {
+    public static @Nullable List<String> getCertificateSHA256FingerprintForPackage(
+            String packageName) {
         PackageInfo packageInfo = getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
 
         if (packageInfo == null) return null;
diff --git a/tot/base/android/java/src/org/chromium/base/PathService.java b/tot/base/android/java/src/org/chromium/base/PathService.java
index bbbe04d..7bdf868 100644
--- a/tot/base/android/java/src/org/chromium/base/PathService.java
+++ b/tot/base/android/java/src/org/chromium/base/PathService.java
@@ -8,7 +8,10 @@
 import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** This class provides java side access to the native PathService. */
+@NullMarked
 @JNINamespace("base::android")
 public abstract class PathService {
 
diff --git a/tot/base/android/java/src/org/chromium/base/PathUtils.java b/tot/base/android/java/src/org/chromium/base/PathUtils.java
index ab8cb7c..8e5f48e 100644
--- a/tot/base/android/java/src/org/chromium/base/PathUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/PathUtils.java
@@ -14,14 +14,18 @@
 import android.system.Os;
 import android.text.TextUtils;
 
-import androidx.annotation.NonNull;
 import androidx.annotation.RequiresApi;
 
 import org.jni_zero.CalledByNative;
+import org.jni_zero.JniType;
 
 import org.chromium.base.task.AsyncTask;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+import org.chromium.build.annotations.RequiresNonNull;
 
 import java.io.File;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
@@ -30,6 +34,8 @@
 import java.util.concurrent.atomic.AtomicBoolean;
 
 /** This class provides the path related methods for the native library. */
+@SuppressWarnings("NullAway") // Too hard to annotate this class.
+@NullMarked
 public abstract class PathUtils {
     private static final String TAG = "PathUtils";
     private static final String THUMBNAIL_DIRECTORY_NAME = "textures";
@@ -39,15 +45,15 @@
     private static final int CACHE_DIRECTORY = 2;
     private static final int NUM_DIRECTORIES = 3;
     private static final AtomicBoolean sInitializationStarted = new AtomicBoolean();
-    private static FutureTask<String[]> sDirPathFetchTask;
+    private static @Nullable FutureTask<String[]> sDirPathFetchTask;
 
     // If the FutureTask started in setPrivateDataDirectorySuffix() fails to complete by the time we
     // need the values, we will need the suffix so that we can restart the task synchronously on
     // the UI thread.
-    private static String sDataDirectorySuffix;
-    private static String sCacheSubDirectory;
-    private static String sDataDirectoryBasePath;
-    private static String sCacheDirectoryBasePath;
+    private static @Nullable String sDataDirectorySuffix;
+    private static @Nullable String sCacheSubDirectory;
+    private static @Nullable String sDataDirectoryBasePath;
+    private static @Nullable String sCacheDirectoryBasePath;
 
     // Prevent instantiation.
     private PathUtils() {}
@@ -69,6 +75,7 @@
      * above to guarantee thread-safety as part of the initialization-on-demand holder idiom.
      */
     private static String[] getOrComputeDirectoryPaths() {
+        assert sDirPathFetchTask != null : "setDataDirectorySuffix must be called first.";
         if (!sDirPathFetchTask.isDone()) {
             try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) {
                 // No-op if already ran.
@@ -98,8 +105,10 @@
         File dataDir = context.getDataDir();
         File externalDir = ContextUtils.getApplicationContext().getExternalFilesDir(null);
         try {
-            return (file.toPath().toRealPath().startsWith(dataDir.toPath().toRealPath())
-                    || file.toPath().toRealPath().startsWith(externalDir.toPath().toRealPath()));
+            Path fileRealPath = file.toPath().toRealPath();
+            return (fileRealPath.startsWith(dataDir.toPath().toRealPath())
+                    || (externalDir != null
+                            && fileRealPath.startsWith(externalDir.toPath().toRealPath())));
         } catch (Exception e) {
             return false;
         }
@@ -113,6 +122,7 @@
      *
      * @see Context#getDir(String, int)
      */
+    @RequiresNonNull("sDataDirectorySuffix")
     private static String[] setPrivateDirectoryPathInternal() {
         String[] paths = new String[NUM_DIRECTORIES];
         File dataDir = null;
@@ -170,7 +180,10 @@
      * @see Context#getDir(String, int)
      */
     public static void setPrivateDirectoryPath(
-            String dataBasePath, String cacheBasePath, String dataDirSuffix, String cacheSubDir) {
+            @Nullable String dataBasePath,
+            @Nullable String cacheBasePath,
+            String dataDirSuffix,
+            @Nullable String cacheSubDir) {
         // This method should only be called once, but many tests end up calling it multiple times,
         // so adding a guard here.
         if (!sInitializationStarted.getAndSet(true)) {
@@ -210,7 +223,7 @@
      * @param cacheSubDir The subdirectory in the cache directory to use, if non-null.
      * @see Context#getDir(String, int)
      */
-    public static void setPrivateDataDirectorySuffix(String suffix, String cacheSubDir) {
+    public static void setPrivateDataDirectorySuffix(String suffix, @Nullable String cacheSubDir) {
         setPrivateDirectoryPath(null, null, suffix, cacheSubDir);
     }
 
@@ -231,8 +244,7 @@
      * @return the private directory that is used to store application data.
      */
     @CalledByNative
-    public static String getDataDirectory() {
-        assert sDirPathFetchTask != null : "setDataDirectorySuffix must be called first.";
+    public static @JniType("std::string") String getDataDirectory() {
         return getDirectoryPath(DATA_DIRECTORY);
     }
 
@@ -240,16 +252,14 @@
      * @return the cache directory.
      */
     @CalledByNative
-    public static String getCacheDirectory() {
-        assert sDirPathFetchTask != null : "setDataDirectorySuffix must be called first.";
+    public static @JniType("std::string") String getCacheDirectory() {
         return getDirectoryPath(CACHE_DIRECTORY);
     }
 
     // Should not be called from WebView, since it does not support being used in a multiprocess
     // environment.
     @CalledByNative
-    public static String getThumbnailCacheDirectory() {
-        assert sDirPathFetchTask != null : "setDataDirectorySuffix must be called first.";
+    public static @JniType("std::string") String getThumbnailCacheDirectory() {
         return getDirectoryPath(THUMBNAIL_DIRECTORY);
     }
 
@@ -261,7 +271,7 @@
      */
     @SuppressWarnings("unused")
     @CalledByNative
-    public static @NonNull String getDownloadsDirectory() {
+    public static @JniType("std::string") String getDownloadsDirectory() {
         // TODO(crbug.com/41187555): Move calls to getDownloadsDirectory() to background thread.
         try (StrictModeContext ignored = StrictModeContext.allowDiskReads()) {
             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
@@ -285,7 +295,7 @@
      */
     @SuppressWarnings("unused")
     @CalledByNative
-    public static @NonNull String[] getAllPrivateDownloadsDirectories() {
+    public static String[] getAllPrivateDownloadsDirectories() {
         List<File> files = new ArrayList<>();
         try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) {
             File[] externalDirs =
@@ -304,7 +314,7 @@
      */
     @RequiresApi(Build.VERSION_CODES.R)
     @CalledByNative
-    public static @NonNull String[] getExternalDownloadVolumesNames() {
+    public static String[] getExternalDownloadVolumesNames() {
         ArrayList<File> files = new ArrayList<>();
         Set<String> volumes =
                 MediaStore.getExternalVolumeNames(ContextUtils.getApplicationContext());
@@ -336,7 +346,7 @@
         return toAbsolutePathStrings(files);
     }
 
-    private static @NonNull String[] toAbsolutePathStrings(@NonNull List<File> files) {
+    private static String[] toAbsolutePathStrings(List<File> files) {
         ArrayList<String> absolutePaths = new ArrayList<String>();
         for (File file : files) {
             if (file == null || TextUtils.isEmpty(file.getAbsolutePath())) continue;
@@ -351,7 +361,7 @@
      */
     @SuppressWarnings("unused")
     @CalledByNative
-    private static String getNativeLibraryDirectory() {
+    private static @JniType("std::string") String getNativeLibraryDirectory() {
         ApplicationInfo ai = ContextUtils.getApplicationContext().getApplicationInfo();
         if ((ai.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0
                 || (ai.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
@@ -366,7 +376,7 @@
      */
     @SuppressWarnings("unused")
     @CalledByNative
-    public static String getExternalStorageDirectory() {
+    public static @JniType("std::string") String getExternalStorageDirectory() {
         return Environment.getExternalStorageDirectory().getAbsolutePath();
     }
 }
diff --git a/tot/base/android/java/src/org/chromium/base/PiiElider.java b/tot/base/android/java/src/org/chromium/base/PiiElider.java
index 561b49a..9706830 100644
--- a/tot/base/android/java/src/org/chromium/base/PiiElider.java
+++ b/tot/base/android/java/src/org/chromium/base/PiiElider.java
@@ -7,10 +7,13 @@
 import android.text.TextUtils;
 import android.util.Patterns;
 
+import org.chromium.build.annotations.NullMarked;
+
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 /** Provides public methods for detecting and eliding sensitive PII. */
+@NullMarked
 public class PiiElider {
     private static final String EMAIL_ELISION = "XXX@EMAIL.ELIDED";
 
diff --git a/tot/base/android/java/src/org/chromium/base/PostNativeFlag.java b/tot/base/android/java/src/org/chromium/base/PostNativeFlag.java
index 031450c..5d40d2a 100644
--- a/tot/base/android/java/src/org/chromium/base/PostNativeFlag.java
+++ b/tot/base/android/java/src/org/chromium/base/PostNativeFlag.java
@@ -4,11 +4,15 @@
 
 package org.chromium.base;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /**
  * Flags of this type assume native is loaded and the value can be retrieved directly from native.
  */
+@NullMarked
 public class PostNativeFlag extends Flag {
-    private Boolean mInMemoryCachedValue;
+    private @Nullable Boolean mInMemoryCachedValue;
 
     public PostNativeFlag(FeatureMap featureMap, String featureName) {
         super(featureMap, featureName);
@@ -18,7 +22,7 @@
     public boolean isEnabled() {
         if (mInMemoryCachedValue != null) return mInMemoryCachedValue;
 
-        if (FeatureList.hasTestFeature(mFeatureName)) {
+        if (FeatureOverrides.hasTestFeature(mFeatureName)) {
             return mFeatureMap.isEnabledInNative(mFeatureName);
         }
 
diff --git a/tot/base/android/java/src/org/chromium/base/PowerMonitor.java b/tot/base/android/java/src/org/chromium/base/PowerMonitor.java
index 931f793..6bfe1de 100644
--- a/tot/base/android/java/src/org/chromium/base/PowerMonitor.java
+++ b/tot/base/android/java/src/org/chromium/base/PowerMonitor.java
@@ -19,11 +19,13 @@
 import org.chromium.base.power_monitor.BatteryPowerStatus;
 import org.chromium.base.task.PostTask;
 import org.chromium.base.task.TaskTraits;
+import org.chromium.build.annotations.NullMarked;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 
 /** Integrates native PowerMonitor with the java side. */
+@NullMarked
 @JNINamespace("base::android")
 public class PowerMonitor {
     private static boolean sIsInitRequested;
@@ -68,7 +70,7 @@
                     @Override
                     public void onReceive(Context context, Intent intent) {
                         PowerMonitor.onBatteryChargingChanged(
-                                intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED));
+                                Intent.ACTION_POWER_DISCONNECTED.equals(intent.getAction()));
                     }
                 },
                 powerConnectedFilter);
diff --git a/tot/base/android/java/src/org/chromium/base/PowerMonitorForQ.java b/tot/base/android/java/src/org/chromium/base/PowerMonitorForQ.java
index cebea1b..eed0732 100644
--- a/tot/base/android/java/src/org/chromium/base/PowerMonitorForQ.java
+++ b/tot/base/android/java/src/org/chromium/base/PowerMonitorForQ.java
@@ -9,11 +9,14 @@
 
 import androidx.annotation.RequiresApi;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
  * Utility class to use new APIs that were added in Q (API level 29). These need to exist in a
  * separate class so that Android framework can successfully verify the PowerMonitor class without
  * encountering the new APIs.
  */
+@NullMarked
 @RequiresApi(Build.VERSION_CODES.Q)
 public final class PowerMonitorForQ {
     private PowerMonitorForQ() {}
diff --git a/tot/base/android/java/src/org/chromium/base/Promise.java b/tot/base/android/java/src/org/chromium/base/Promise.java
index 5d8176d..d08419b 100644
--- a/tot/base/android/java/src/org/chromium/base/Promise.java
+++ b/tot/base/android/java/src/org/chromium/base/Promise.java
@@ -8,6 +8,10 @@
 
 import androidx.annotation.IntDef;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.NullUnmarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.util.LinkedList;
@@ -15,11 +19,13 @@
 import java.util.function.Function;
 
 /**
- * A Promise class to be used as a placeholder for a result that will be provided asynchronously.
- * It must only be accessed from a single thread.
+ * A Promise class to be used as a placeholder for a result that will be provided asynchronously. It
+ * must only be accessed from a single thread.
+ *
  * @param <T> The type the Promise will be fulfilled with.
  */
-public class Promise<T> {
+@NullMarked
+public class Promise<T extends @Nullable Object> {
     // TODO(peconn): Implement rejection handlers that can recover from rejection.
 
     @IntDef({PromiseState.UNFULFILLED, PromiseState.FULFILLED, PromiseState.REJECTED})
@@ -32,11 +38,11 @@
 
     @PromiseState private int mState = PromiseState.UNFULFILLED;
 
-    private T mResult;
+    private @Nullable T mResult;
     private final List<Callback<T>> mFulfillCallbacks = new LinkedList<>();
 
-    private Exception mRejectReason;
-    private final List<Callback<Exception>> mRejectCallbacks = new LinkedList<>();
+    private @Nullable Exception mRejectReason;
+    private final List<Callback<@Nullable Exception>> mRejectCallbacks = new LinkedList<>();
 
     private final Thread mThread = Thread.currentThread();
     private final Handler mHandler = new Handler();
@@ -55,7 +61,7 @@
      * to a subsequent Promise.
      */
     public static class UnhandledRejectionException extends RuntimeException {
-        public UnhandledRejectionException(String message, Throwable cause) {
+        public UnhandledRejectionException(String message, @Nullable Throwable cause) {
             super(message, cause);
         }
     }
@@ -79,7 +85,7 @@
                 : "Do not call the single argument Promise.then(Callback) on a Promise that already"
                         + " has a rejection handler.";
 
-        Callback<Exception> onReject =
+        Callback<@Nullable Exception> onReject =
                 reason -> {
                     throw new UnhandledRejectionException(
                             "Promise was rejected without a rejection handler.", reason);
@@ -95,10 +101,10 @@
      * iteration of the message loop.
      *
      * @param onFulfill The Callback to be called on fulfillment.
-     * @param onReject The Callback to be called on rejection. The argument to onReject will
-     *         may be null if the Promise was rejected manually.
+     * @param onReject The Callback to be called on rejection. The argument to onReject will may be
+     *     null if the Promise was rejected manually.
      */
-    public void then(Callback<T> onFulfill, Callback<Exception> onReject) {
+    public void then(Callback<T> onFulfill, Callback<@Nullable Exception> onReject) {
         checkThread();
         thenInner(onFulfill);
         exceptInner(onReject);
@@ -106,15 +112,16 @@
 
     /**
      * Adds a rejection handler to the Promise. This handler will be called if this Promise or any
-     * Promises this Promise depends on is rejected or fails. The {@link Callback} will be given
-     * the exception that caused the rejection, or null if the rejection was manual (caused by a
-     * call to {@link #reject()}.
+     * Promises this Promise depends on is rejected or fails. The {@link Callback} will be given the
+     * exception that caused the rejection, or null if the rejection was manual (caused by a call to
+     * {@link #reject()}.
      */
-    public void except(Callback<Exception> onReject) {
+    public void except(Callback<@Nullable Exception> onReject) {
         checkThread();
         exceptInner(onReject);
     }
 
+    @SuppressWarnings("NullAway") // Cannot specify that mResult is non-null when T is @NonNull.
     private void thenInner(Callback<T> onFulfill) {
         if (mState == PromiseState.FULFILLED) {
             postCallbackToLooper(onFulfill, mResult);
@@ -123,7 +130,7 @@
         }
     }
 
-    private void exceptInner(Callback<Exception> onReject) {
+    private void exceptInner(Callback<@Nullable Exception> onReject) {
         assert !mThrowingRejectionHandler
                 : "Do not add an exception handler to a Promise you have "
                         + "called the single argument Promise.then(Callback) on.";
@@ -139,7 +146,7 @@
      * Queues a {@link Function} to be run when the Promise is fulfilled. When this Promise is
      * fulfilled, the function will be run and its result will be place in the returned Promise.
      */
-    public <RT> Promise<RT> then(final Function<T, RT> function) {
+    public <RT extends @Nullable Object> Promise<RT> then(Function<T, RT> function) {
         checkThread();
 
         // Create a new Promise to store the result of the function.
@@ -169,7 +176,7 @@
      * Promise is fulfilled, the AsyncFunction will be run. When the result of the AsyncFunction is
      * available, it will be placed in the returned Promise.
      */
-    public <RT> Promise<RT> then(final AsyncFunction<T, RT> function) {
+    public <RT extends @Nullable Object> Promise<RT> then(AsyncFunction<T, RT> function) {
         checkThread();
 
         // Create a new Promise to be returned.
@@ -206,7 +213,7 @@
     public Promise<T> andFinally(Runnable runnable) {
         Callback<?> asCallback = unused -> runnable.run();
         thenInner((Callback<T>) asCallback);
-        exceptInner((Callback<Exception>) asCallback);
+        exceptInner((Callback<@Nullable Exception>) asCallback);
         return this;
     }
 
@@ -214,7 +221,7 @@
      * Fulfills the Promise with the result and passes it to any {@link Callback}s previously queued
      * on the next iteration of the message loop.
      */
-    public void fulfill(final T result) {
+    public void fulfill(T result) {
         checkThread();
         assert mState == PromiseState.UNFULFILLED;
 
@@ -235,14 +242,14 @@
      * important to make it explicit when a Promise may be rejected, so that users of that Promise
      * know to provide rejection handling.
      */
-    public void reject(final Exception reason) {
+    public void reject(final @Nullable Exception reason) {
         checkThread();
         assert mState == PromiseState.UNFULFILLED;
 
         mState = PromiseState.REJECTED;
         mRejectReason = reason;
 
-        for (final Callback<Exception> callback : mRejectCallbacks) {
+        for (final Callback<@Nullable Exception> callback : mRejectCallbacks) {
             postCallbackToLooper(callback, reason);
         }
         mRejectCallbacks.clear();
@@ -276,20 +283,23 @@
      *
      * @return The promised result.
      */
+    @SuppressWarnings("NullAway")
     public T getResult() {
         assert isFulfilled();
+        // SuppressWarnings necessary since mResult is @Nullable, but we cannot check that it's
+        // non-null because T might be @Nullable.
         return mResult;
     }
 
     /** Convenience method to return a Promise fulfilled with the given result. */
-    public static <T> Promise<T> fulfilled(T result) {
+    public static <T extends @Nullable Object> Promise<T> fulfilled(T result) {
         Promise<T> promise = new Promise<>();
         promise.fulfill(result);
         return promise;
     }
 
     /** Convenience method to return a rejected Promise. */
-    public static <T> Promise<T> rejected() {
+    public static <T extends @Nullable Object> Promise<T> rejected() {
         Promise<T> promise = new Promise<>();
         promise.reject();
         return promise;
@@ -300,7 +310,9 @@
     }
 
     // We use a different template parameter here so this can be used for both T and Throwables.
-    private <S> void postCallbackToLooper(final Callback<S> callback, final S result) {
+    @NullUnmarked // https://github.com/uber/NullAway/issues/1075
+    private <S extends @Nullable Object> void postCallbackToLooper(
+            final Callback<S> callback, S result) {
         // Post the callbacks to the Thread looper so we don't get a long chain of callbacks
         // holding up the thread.
         mHandler.post(callback.bind(result));
diff --git a/tot/base/android/java/src/org/chromium/base/RadioUtils.java b/tot/base/android/java/src/org/chromium/base/RadioUtils.java
index 117a53f..244e4ac 100644
--- a/tot/base/android/java/src/org/chromium/base/RadioUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/RadioUtils.java
@@ -20,13 +20,17 @@
 import org.jni_zero.CalledByNative;
 import org.jni_zero.JNINamespace;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /** Exposes radio related information about the current device. */
+@NullMarked
 @JNINamespace("base::android")
 public class RadioUtils {
     // Cached value indicating if app has ACCESS_NETWORK_STATE permission.
-    private static Boolean sHaveAccessNetworkState;
+    private static @Nullable Boolean sHaveAccessNetworkState;
     // Cached value indicating if app has ACCESS_WIFI_STATE permission.
-    private static Boolean sHaveAccessWifiState;
+    private static @Nullable Boolean sHaveAccessWifiState;
 
     private RadioUtils() {}
 
diff --git a/tot/base/android/java/src/org/chromium/base/RequiredCallback.java b/tot/base/android/java/src/org/chromium/base/RequiredCallback.java
index 20d847a..2533b2b 100644
--- a/tot/base/android/java/src/org/chromium/base/RequiredCallback.java
+++ b/tot/base/android/java/src/org/chromium/base/RequiredCallback.java
@@ -4,7 +4,8 @@
 
 package org.chromium.base;
 
-import androidx.annotation.NonNull;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /**
  * A simple single-argument callback to handle the result of a computation that must be called
@@ -12,12 +13,13 @@
  *
  * @param <T> The type of the computation's result.
  */
-public class RequiredCallback<T> implements Callback<T> {
+@NullMarked
+public class RequiredCallback<T extends @Nullable Object> implements Callback<T> {
     // Enforces (under test) that this callback is invoked before it is GC'd.
-    private final LifetimeAssert mLifetimeAssert = LifetimeAssert.create(this);
-    private Callback<T> mCallback;
+    private final @Nullable LifetimeAssert mLifetimeAssert = LifetimeAssert.create(this);
+    private @Nullable Callback<T> mCallback;
 
-    public RequiredCallback(@NonNull Callback<T> callback) {
+    public RequiredCallback(Callback<T> callback) {
         mCallback = callback;
     }
 
diff --git a/tot/base/android/java/src/org/chromium/base/ResettersForTesting.java b/tot/base/android/java/src/org/chromium/base/ResettersForTesting.java
index c9bdc39..8ef2a64 100644
--- a/tot/base/android/java/src/org/chromium/base/ResettersForTesting.java
+++ b/tot/base/android/java/src/org/chromium/base/ResettersForTesting.java
@@ -8,6 +8,8 @@
 import androidx.annotation.IntDef;
 
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.Initializer;
+import org.chromium.build.annotations.NullMarked;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -83,6 +85,7 @@
  * }
  * </code>
  */
+@NullMarked
 public class ResettersForTesting {
 
     @IntDef({
@@ -235,6 +238,7 @@
     }
 
     /** Enables calls to register(). */
+    @Initializer
     public static void enable() {
         assert BuildConfig.IS_FOR_TEST;
         synchronized (sLock) {
diff --git a/tot/base/android/java/src/org/chromium/base/ServiceLoaderUtil.java b/tot/base/android/java/src/org/chromium/base/ServiceLoaderUtil.java
index ea7f1f0..241e4f8 100644
--- a/tot/base/android/java/src/org/chromium/base/ServiceLoaderUtil.java
+++ b/tot/base/android/java/src/org/chromium/base/ServiceLoaderUtil.java
@@ -4,11 +4,13 @@
 
 package org.chromium.base;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.util.ArrayMap;
 
-import androidx.annotation.Nullable;
-
 import org.chromium.build.annotations.AlwaysInline;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.Map;
 import java.util.ServiceLoader;
@@ -43,8 +45,9 @@
  *
  * </pre>
  */
+@NullMarked
 public final class ServiceLoaderUtil {
-    private static Map<Class<?>, Object> sOverridesForTesting;
+    private static @Nullable Map<Class<?>, Object> sOverridesForTesting;
 
     private ServiceLoaderUtil() {}
 
@@ -75,6 +78,6 @@
             sOverridesForTesting = new ArrayMap<>();
         }
         sOverridesForTesting.put(clazz, instance);
-        ResettersForTesting.register(() -> sOverridesForTesting.remove(clazz));
+        ResettersForTesting.register(() -> assumeNonNull(sOverridesForTesting).remove(clazz));
     }
 }
diff --git a/tot/base/android/java/src/org/chromium/base/StreamUtil.java b/tot/base/android/java/src/org/chromium/base/StreamUtil.java
index d1cff59..fc61b03 100644
--- a/tot/base/android/java/src/org/chromium/base/StreamUtil.java
+++ b/tot/base/android/java/src/org/chromium/base/StreamUtil.java
@@ -4,17 +4,22 @@
 
 package org.chromium.base;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.io.Closeable;
 import java.io.IOException;
 
 /** Helper methods to deal with stream related tasks. */
+@NullMarked
 public class StreamUtil {
     /**
      * Handle closing a {@link java.io.Closeable} via {@link java.io.Closeable#close()} and catch
      * the potentially thrown {@link java.io.IOException}.
+     *
      * @param closeable The Closeable to be closed.
      */
-    public static void closeQuietly(Closeable closeable) {
+    public static void closeQuietly(@Nullable Closeable closeable) {
         if (closeable == null) return;
 
         try {
diff --git a/tot/base/android/java/src/org/chromium/base/StrictModeContext.java b/tot/base/android/java/src/org/chromium/base/StrictModeContext.java
index e694cd1..a3412fc 100644
--- a/tot/base/android/java/src/org/chromium/base/StrictModeContext.java
+++ b/tot/base/android/java/src/org/chromium/base/StrictModeContext.java
@@ -8,6 +8,8 @@
 import android.os.StrictMode;
 
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.io.Closeable;
 
@@ -24,12 +26,15 @@
  *     }
  * </pre>
  */
+@NullMarked
 public class StrictModeContext implements Closeable {
     private static class Impl extends StrictModeContext {
-        private final StrictMode.ThreadPolicy mThreadPolicy;
-        private final StrictMode.VmPolicy mVmPolicy;
+        private final StrictMode.@Nullable ThreadPolicy mThreadPolicy;
+        private final StrictMode.@Nullable VmPolicy mVmPolicy;
 
-        private Impl(StrictMode.ThreadPolicy threadPolicy, StrictMode.VmPolicy vmPolicy) {
+        private Impl(
+                StrictMode.@Nullable ThreadPolicy threadPolicy,
+                StrictMode.@Nullable VmPolicy vmPolicy) {
             mThreadPolicy = threadPolicy;
             mVmPolicy = vmPolicy;
         }
diff --git a/tot/base/android/java/src/org/chromium/base/SysUtils.java b/tot/base/android/java/src/org/chromium/base/SysUtils.java
index 725ae9e..0728c73 100644
--- a/tot/base/android/java/src/org/chromium/base/SysUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/SysUtils.java
@@ -14,6 +14,8 @@
 import org.jni_zero.NativeMethods;
 
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.io.BufferedReader;
 import java.io.FileReader;
@@ -21,14 +23,18 @@
 import java.util.regex.Pattern;
 
 /** Exposes system related information about the current device. */
+@NullMarked
 @JNINamespace("base::android")
 public class SysUtils {
     // A device reporting strictly more total memory in megabytes cannot be considered 'low-end'.
+    // Keep in sync with LOW_MEMORY_DEVICE_THRESHOLD_MB in C++.
+    // LINT.IfChange
     private static final int LOW_MEMORY_DEVICE_THRESHOLD_MB = 1024;
+    // LINT.ThenChange(//base/features.cc)
     private static final String TAG = "SysUtils";
 
-    private static Boolean sLowEndDevice;
-    private static Integer sAmountOfPhysicalMemoryKB;
+    private static @Nullable Boolean sLowEndDevice;
+    private static @Nullable Integer sAmountOfPhysicalMemoryKB;
 
     private SysUtils() {}
 
@@ -82,7 +88,6 @@
     /**
      * @return Whether or not this device should be considered a low end device.
      */
-    @CalledByNative
     public static boolean isLowEndDevice() {
         // Do not cache in tests since command-line flags can change.
         if (sLowEndDevice == null || BuildConfig.IS_FOR_TEST) {
@@ -94,7 +99,6 @@
     /**
      * @return amount of physical ram detected in KB, or 0 if detection failed.
      */
-    @CalledByNative
     public static int amountOfPhysicalMemoryKB() {
         if (sAmountOfPhysicalMemoryKB == null) {
             sAmountOfPhysicalMemoryKB = detectAmountOfPhysicalMemoryKB();
@@ -129,6 +133,8 @@
     }
 
     private static boolean detectLowEndDevice() {
+        // Keep in sync with the native implementation of this function.
+        // LINT.IfChange
         assert CommandLine.isInitialized();
         if (CommandLine.getInstance().hasSwitch(BaseSwitches.ENABLE_LOW_END_DEVICE_MODE)) {
             return true;
@@ -147,6 +153,7 @@
         }
 
         return isLowEnd;
+        // LINT.ThenChange(//base/system/sys_info.cc)
     }
 
     /**
diff --git a/tot/base/android/java/src/org/chromium/base/ThreadUtils.java b/tot/base/android/java/src/org/chromium/base/ThreadUtils.java
index 53036b9..a6d9766 100644
--- a/tot/base/android/java/src/org/chromium/base/ThreadUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/ThreadUtils.java
@@ -13,22 +13,25 @@
 import org.chromium.base.task.PostTask;
 import org.chromium.base.task.TaskTraits;
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.concurrent.Callable;
 import java.util.concurrent.FutureTask;
 
 /** Helper methods to deal with threading related tasks. */
+@NullMarked
 public class ThreadUtils {
 
     private static final Object sLock = new Object();
 
     private static volatile boolean sWillOverride;
 
-    private static volatile Handler sUiThreadHandler;
+    private static volatile @Nullable Handler sUiThreadHandler;
 
-    private static Throwable sUiThreadInitializer;
+    private static @Nullable Throwable sUiThreadInitializer;
     private static boolean sThreadAssertsDisabledForTesting;
-    private static Thread sInstrumentationThreadForTesting;
+    private static @Nullable Thread sInstrumentationThreadForTesting;
 
     /**
      * A helper object to ensure that interactions with a particular object only happens on a
@@ -48,7 +51,7 @@
      */
     // TODO(b/274802355): Add @CheckDiscard once R8 can remove this.
     public static class ThreadChecker {
-        private Thread mThread;
+        private @Nullable Thread mThread;
 
         public ThreadChecker() {
             resetThreadId();
@@ -161,6 +164,7 @@
             throw new RuntimeException("Did not yet override the UI thread");
         }
         setUiThread(Looper.getMainLooper());
+        assert sUiThreadHandler != null;
         return sUiThreadHandler;
     }
 
@@ -187,7 +191,7 @@
      * @param c The Callable to run
      * @return The result of the callable
      */
-    public static <T> T runOnUiThreadBlocking(Callable<T> c) {
+    public static <T extends @Nullable Object> T runOnUiThreadBlocking(Callable<T> c) {
         return PostTask.runSynchronously(TaskTraits.UI_DEFAULT, c);
     }
 
@@ -198,7 +202,7 @@
      * @param task The FutureTask to run
      * @return The queried task (to aid inline construction)
      */
-    public static <T> FutureTask<T> runOnUiThread(FutureTask<T> task) {
+    public static <T extends @Nullable Object> FutureTask<T> runOnUiThread(FutureTask<T> task) {
         PostTask.runOrPostTask(TaskTraits.UI_DEFAULT, task);
         return task;
     }
@@ -220,7 +224,7 @@
      * @param task The FutureTask to run
      * @return The queried task (to aid inline construction)
      */
-    public static <T> FutureTask<T> postOnUiThread(FutureTask<T> task) {
+    public static <T extends @Nullable Object> FutureTask<T> postOnUiThread(FutureTask<T> task) {
         PostTask.postTask(TaskTraits.UI_DEFAULT, task);
         return task;
     }
diff --git a/tot/base/android/java/src/org/chromium/base/TimeUtils.java b/tot/base/android/java/src/org/chromium/base/TimeUtils.java
index a5d9500..b914b1d 100644
--- a/tot/base/android/java/src/org/chromium/base/TimeUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/TimeUtils.java
@@ -7,11 +7,14 @@
 import android.os.SystemClock;
 
 import org.chromium.build.annotations.CheckDiscard;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /**
  * Utilities related to timestamps, including the ability to use fake time for tests via
  * FakeTimeTestRule.
  */
+@NullMarked
 public class TimeUtils {
     /**
      * Interval timer using SystemClock.uptimeMillis() (excludes deep sleep).
@@ -91,7 +94,7 @@
 
     // Used by FakeTimeTestRule. Visibility is restricted to ensure tests use the rule, which
     // restores the value to null in its clean-up logic.
-    static FakeClock sFakeClock;
+    static @Nullable FakeClock sFakeClock;
 
     /**
      * Wrapper for System.currentTimeMillis() (milliseconds since the epoch).
diff --git a/tot/base/android/java/src/org/chromium/base/TimezoneUtils.java b/tot/base/android/java/src/org/chromium/base/TimezoneUtils.java
index 606b72e..b8aa1a8 100644
--- a/tot/base/android/java/src/org/chromium/base/TimezoneUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/TimezoneUtils.java
@@ -9,8 +9,11 @@
 import org.jni_zero.CalledByNative;
 import org.jni_zero.JNINamespace;
 
+import org.chromium.build.annotations.NullMarked;
+
 import java.util.TimeZone;
 
+@NullMarked
 @JNINamespace("base::android")
 class TimezoneUtils {
     /** Guards this class from being instantiated. */
diff --git a/tot/base/android/java/src/org/chromium/base/Token.java b/tot/base/android/java/src/org/chromium/base/Token.java
index b6205f9..8bd974b 100644
--- a/tot/base/android/java/src/org/chromium/base/Token.java
+++ b/tot/base/android/java/src/org/chromium/base/Token.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base;
 
+import android.os.Bundle;
+
 import androidx.annotation.VisibleForTesting;
 
 import com.google.errorprone.annotations.DoNotMock;
@@ -13,10 +15,17 @@
 import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /** Java counterpart to the native base::Token. A {@link Token} is a random 128-bit integer. */
+@NullMarked
 @JNINamespace("base::android")
 @DoNotMock("This is a simple value object.")
 public final class Token extends TokenBase {
+    private static final String KEY_LOW = "low";
+    private static final String KEY_HIGH = "high";
+
     /** Returns a new random token using the native implementation. */
     public static Token createRandom() {
         return TokenJni.get().createRandom();
@@ -54,6 +63,28 @@
         return String.format("%016X%016X", mHigh, mLow);
     }
 
+    /**
+     * Converts this Token's data into a bundle {@link Bundle}.
+     *
+     * @return the bundle {@link Bundle} stores the Token's high and low values.
+     */
+    public Bundle toBundle() {
+        Bundle bundle = new Bundle();
+        bundle.putLong(KEY_HIGH, getHigh());
+        bundle.putLong(KEY_LOW, getLow());
+        return bundle;
+    }
+
+    /**
+     * @param bundle Bundle to be parsed.
+     * @return the deserialized Token object or null if the bundle is invalid.
+     */
+    public static @Nullable Token maybeCreateFromBundle(@Nullable Bundle bundle) {
+        if (bundle == null) return null;
+        if (!bundle.containsKey(KEY_HIGH) || !bundle.containsKey(KEY_LOW)) return null;
+        return new Token(bundle.getLong(KEY_HIGH), bundle.getLong(KEY_LOW));
+    }
+
     @NativeMethods
     @VisibleForTesting
     public interface Natives {
diff --git a/tot/base/android/java/src/org/chromium/base/TokenBase.java b/tot/base/android/java/src/org/chromium/base/TokenBase.java
index 8310de4..61c5289 100644
--- a/tot/base/android/java/src/org/chromium/base/TokenBase.java
+++ b/tot/base/android/java/src/org/chromium/base/TokenBase.java
@@ -4,12 +4,14 @@
 
 package org.chromium.base;
 
-import androidx.annotation.Nullable;
-
 import org.jni_zero.CalledByNative;
 import org.jni_zero.JNINamespace;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /** Base class for Token and UnguessableToken. */
+@NullMarked
 @JNINamespace("base::android")
 public abstract class TokenBase {
     protected final long mHigh;
diff --git a/tot/base/android/java/src/org/chromium/base/TraceEvent.java b/tot/base/android/java/src/org/chromium/base/TraceEvent.java
index a09bcb5..bbab4bf 100644
--- a/tot/base/android/java/src/org/chromium/base/TraceEvent.java
+++ b/tot/base/android/java/src/org/chromium/base/TraceEvent.java
@@ -22,6 +22,8 @@
 
 import org.chromium.base.task.PostTask;
 import org.chromium.base.task.TaskTraits;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.ArrayList;
 
@@ -41,6 +43,7 @@
  * It is OK to use tracing before the native library has loaded, in a slightly restricted fashion.
  * @see EarlyTraceEvent for details.
  */
+@NullMarked
 @JNINamespace("base::android")
 public class TraceEvent implements AutoCloseable {
     private static volatile boolean sEnabled; // True when tracing into Chrome's tracing service.
@@ -56,7 +59,7 @@
         static final String FILTERED_EVENT_NAME = LOOPER_TASK_PREFIX + "EVENT_NAME_FILTERED";
 
         private static final int SHORTEST_LOG_PREFIX_LENGTH = "<<<<< Finished to ".length();
-        private String mCurrentTarget;
+        private @Nullable String mCurrentTarget;
 
         @Override
         public void println(final String line) {
@@ -260,7 +263,7 @@
     private final String mName;
 
     /** Constructor used to support the "try with resource" construct. */
-    private TraceEvent(String name, String arg) {
+    private TraceEvent(String name, @Nullable String arg) {
         mName = name;
         begin(name, arg);
     }
@@ -285,7 +288,7 @@
      * @param arg The arguments of the event.
      * @return a TraceEvent, or null if tracing is not enabled.
      */
-    public static TraceEvent scoped(String name, String arg) {
+    public static @Nullable TraceEvent scoped(String name, @Nullable String arg) {
         if (!(EarlyTraceEvent.enabled() || enabled())) return null;
         return new TraceEvent(name, arg);
     }
@@ -299,13 +302,13 @@
      * @param arg An integer argument of the event.
      * @return a TraceEvent, or null if tracing is not enabled.
      */
-    public static TraceEvent scoped(String name, int arg) {
+    public static @Nullable TraceEvent scoped(String name, int arg) {
         if (!(EarlyTraceEvent.enabled() || enabled())) return null;
         return new TraceEvent(name, arg);
     }
 
     /** Similar to {@link #scoped(String, String arg)}, but uses null for |arg|. */
-    public static TraceEvent scoped(String name) {
+    public static @Nullable TraceEvent scoped(String name) {
         return scoped(name, null);
     }
 
@@ -439,15 +442,27 @@
     }
 
     /**
-     * Records 'WebView.Startup.CreationTime.Stage2.ProviderInit.Warm' and
-     * 'WebView.Startup.CreationTime.Stage2.ProviderInit.Cold' events depending on the value of
-     * `isColdStartup` with the 'android_webview.timeline' category starting at `startTimeMs` with
-     * the duration of `durationMs`.
+     * Records 'WebView.Startup.CreationTime.FirstInstanceWithGlobalStartup' or
+     * 'WebView.Startup.CreationTime.FirstInstanceWithoutGlobalStartup' events depending on the
+     * value of `includedGlobalStartup` with the 'android_webview.timeline' category starting at
+     * `startTimeMs` with the duration of `durationMs`.
      */
-    public static void webViewStartupStage2(
-            long startTimeMs, long durationMs, boolean isColdStartup) {
+    public static void webViewStartupFirstInstance(
+            long startTimeMs, long durationMs, boolean includedGlobalStartup) {
         if (sEnabled) {
-            TraceEventJni.get().webViewStartupStage2(startTimeMs, durationMs, isColdStartup);
+            TraceEventJni.get()
+                    .webViewStartupFirstInstance(startTimeMs, durationMs, includedGlobalStartup);
+        }
+    }
+
+    /**
+     * Records a 'WebView.Startup.CreationTime.NotFirstInstance' event with the
+     * 'android_webview.timeline' category starting at `startTimeMs` with the duration of
+     * `durationMs`.
+     */
+    public static void webViewStartupNotFirstInstance(long startTimeMs, long durationMs) {
+        if (sEnabled) {
+            TraceEventJni.get().webViewStartupNotFirstInstance(startTimeMs, durationMs);
         }
     }
 
@@ -560,7 +575,7 @@
      * @param name The name of the event.
      * @param arg  The arguments of the event.
      */
-    public static void begin(String name, String arg) {
+    public static void begin(String name, @Nullable String arg) {
         EarlyTraceEvent.begin(name, /* isToplevel= */ false);
         if (sEnabled) {
             TraceEventJni.get().begin(name, arg);
@@ -592,7 +607,7 @@
      * @param name The name of the event.
      * @param arg  The arguments of the event.
      */
-    public static void end(String name, String arg) {
+    public static void end(String name, @Nullable String arg) {
         end(name, arg, 0);
     }
 
@@ -602,7 +617,7 @@
      * @param arg  The arguments of the event.
      * @param flow The flow ID to associate with this event (0 is treated as invalid).
      */
-    public static void end(String name, String arg, long flow) {
+    public static void end(String name, @Nullable String arg, long flow) {
         EarlyTraceEvent.end(name, /* isToplevel= */ false);
         if (sEnabled) {
             TraceEventJni.get().end(arg, flow);
@@ -630,13 +645,13 @@
     interface Natives {
         void registerEnabledObserver();
 
-        void instant(String name, String arg);
+        void instant(String name, @Nullable String arg);
 
-        void begin(String name, String arg);
+        void begin(String name, @Nullable String arg);
 
         void beginWithIntArg(String name, int arg);
 
-        void end(String arg, long flow);
+        void end(@Nullable String arg, long flow);
 
         void beginToplevel(String target);
 
@@ -669,7 +684,10 @@
 
         void webViewStartupStage1(long startTimeMs, long durationMs);
 
-        void webViewStartupStage2(long startTimeMs, long durationMs, boolean isColdStartup);
+        void webViewStartupFirstInstance(
+                long startTimeMs, long durationMs, boolean includedGlobalStartup);
+
+        void webViewStartupNotFirstInstance(long startTimeMs, long durationMs);
 
         void webViewStartupStartChromiumLocked(
                 long startTimeMs, long durationMs, int callSite, boolean fromUIThread);
@@ -793,8 +811,7 @@
      */
     private static final class ViewHierarchyDumper implements MessageQueue.IdleHandler {
         private static final long MIN_VIEW_DUMP_INTERVAL_MILLIS = 1000L;
-        private static boolean sEnabled;
-        private static ViewHierarchyDumper sInstance;
+        private static @Nullable ViewHierarchyDumper sInstance;
         private long mLastDumpTs;
 
         @Override
@@ -812,18 +829,7 @@
         public static void updateEnabledState() {
             PostTask.runOrPostTask(
                     TaskTraits.UI_DEFAULT,
-                    () -> {
-                        if (TraceEventJni.get().viewHierarchyDumpEnabled()) {
-                            if (sInstance == null) {
-                                sInstance = new ViewHierarchyDumper();
-                            }
-                            enable();
-                        } else {
-                            if (sInstance != null) {
-                                disable();
-                            }
-                        }
-                    });
+                    () -> setEnabled(TraceEventJni.get().viewHierarchyDumpEnabled()));
         }
 
         private static void dumpView(ActivityInfo collection, int parentId, View v) {
@@ -846,19 +852,14 @@
             }
         }
 
-        private static void enable() {
+        private static void setEnabled(boolean value) {
             ThreadUtils.assertOnUiThread();
-            if (!sEnabled) {
+            if (sInstance == null && value) {
+                sInstance = new ViewHierarchyDumper();
                 Looper.myQueue().addIdleHandler(sInstance);
-                sEnabled = true;
-            }
-        }
-
-        private static void disable() {
-            ThreadUtils.assertOnUiThread();
-            if (sEnabled) {
+            } else if (sInstance != null && !value) {
                 Looper.myQueue().removeIdleHandler(sInstance);
-                sEnabled = false;
+                sInstance = null;
             }
         }
     }
diff --git a/tot/base/android/java/src/org/chromium/base/UnguessableToken.java b/tot/base/android/java/src/org/chromium/base/UnguessableToken.java
index 0d98e60..3da95d3 100644
--- a/tot/base/android/java/src/org/chromium/base/UnguessableToken.java
+++ b/tot/base/android/java/src/org/chromium/base/UnguessableToken.java
@@ -12,6 +12,9 @@
 import org.jni_zero.CalledByNative;
 import org.jni_zero.JNINamespace;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /**
  * This class mirrors unguessable_token.h. Since tokens are passed by value, we don't bother to
  * maintain a native token. This implements Parcelable so that it may be sent via binder.
@@ -19,13 +22,14 @@
  * <p>To get one of these from native, one must start with a base::UnguessableToken, then create a
  * Java object from it. See unguessable_token_android.h for information.
  */
+@NullMarked
 @DoNotMock("This is a simple value object.")
 @JNINamespace("base::android")
 public final class UnguessableToken extends TokenBase implements Parcelable {
     private static int sCounterForTesting;
 
     public static UnguessableToken createForTesting() {
-        return new UnguessableToken(sCounterForTesting++, sCounterForTesting++);
+        return new UnguessableToken(++sCounterForTesting, ++sCounterForTesting);
     }
 
     @CalledByNative
@@ -47,7 +51,7 @@
     public static final Parcelable.Creator<UnguessableToken> CREATOR =
             new Parcelable.Creator<UnguessableToken>() {
                 @Override
-                public UnguessableToken createFromParcel(Parcel source) {
+                public @Nullable UnguessableToken createFromParcel(Parcel source) {
                     long high = source.readLong();
                     long low = source.readLong();
                     if (high == 0 || low == 0) {
diff --git a/tot/base/android/java/src/org/chromium/base/UnownedUserData.java b/tot/base/android/java/src/org/chromium/base/UnownedUserData.java
index bc8c7bb..64ffcdb 100644
--- a/tot/base/android/java/src/org/chromium/base/UnownedUserData.java
+++ b/tot/base/android/java/src/org/chromium/base/UnownedUserData.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
  * Marker interface to be implemented by classes which makes them attachable to a host class that
  * holds {@link UnownedUserDataHost} entries.
@@ -19,6 +21,7 @@
  * @see UnownedUserDataHost for more details on ownership and typical usage.
  * @see UnownedUserDataKey for information about the type of key that is required.
  */
+@NullMarked
 public interface UnownedUserData {
     /**
      * Invoked whenever the particular UnownedUserData has been removed from a particular host. If
diff --git a/tot/base/android/java/src/org/chromium/base/UnownedUserDataHost.java b/tot/base/android/java/src/org/chromium/base/UnownedUserDataHost.java
index ec14532..6c64412 100644
--- a/tot/base/android/java/src/org/chromium/base/UnownedUserDataHost.java
+++ b/tot/base/android/java/src/org/chromium/base/UnownedUserDataHost.java
@@ -4,14 +4,18 @@
 
 package org.chromium.base;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.os.Handler;
 import android.os.Looper;
 
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
 import androidx.annotation.VisibleForTesting;
 
 import org.chromium.base.lifetime.DestroyChecker;
+import org.chromium.build.annotations.EnsuresNonNull;
+import org.chromium.build.annotations.EnsuresNonNullIf;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.lang.ref.WeakReference;
 import java.util.HashMap;
@@ -141,6 +145,7 @@
  * @see UnownedUserDataKey for information about the type of key that is required.
  * @see UnownedUserData for the marker interface used for this type of data.
  */
+@NullMarked
 public final class UnownedUserDataHost {
     private static Looper retrieveNonNullLooperOrThrow() {
         Looper looper = Looper.myLooper();
@@ -155,10 +160,10 @@
      * Handler to use to post {@link UnownedUserData#onDetachedFromHost(UnownedUserDataHost)}
      * invocations to.
      */
-    private Handler mHandler;
+    private @Nullable Handler mHandler;
 
     /** The core data structure within this host. */
-    private HashMap<UnownedUserDataKey<?>, WeakReference<? extends UnownedUserData>>
+    private @Nullable HashMap<UnownedUserDataKey<?>, WeakReference<? extends UnownedUserData>>
             mUnownedUserDataMap = new HashMap<>();
 
     public UnownedUserDataHost() {
@@ -179,8 +184,7 @@
      * @param newValue the object to store.
      * @param <T> the type of {@link UnownedUserData}.
      */
-    /* package */ <T extends UnownedUserData> void set(
-            @NonNull UnownedUserDataKey<T> key, @NonNull T newValue) {
+    /* package */ <T extends UnownedUserData> void set(UnownedUserDataKey<T> key, T newValue) {
         checkState();
 
         // If we already have data, we might want to detach that first.
@@ -200,8 +204,8 @@
      * @param <T> the type of {@link UnownedUserData}.
      * @return the stored version or {@code null} if it is not stored or has been garbage collected.
      */
-    @Nullable
-    /* package */ <T extends UnownedUserData> T get(@NonNull UnownedUserDataKey<T> key) {
+
+    /* package */ <T extends UnownedUserData> @Nullable T get(UnownedUserDataKey<T> key) {
         checkState();
 
         WeakReference<? extends UnownedUserData> valueWeakRef = mUnownedUserDataMap.get(key);
@@ -221,7 +225,7 @@
      * @param key the key to use for the object.
      * @param <T> the type of {@link UnownedUserData}.
      */
-    /* package */ <T extends UnownedUserData> void remove(@NonNull UnownedUserDataKey<T> key) {
+    /* package */ <T extends UnownedUserData> void remove(UnownedUserDataKey<T> key) {
         checkState();
 
         WeakReference<? extends UnownedUserData> valueWeakRef = mUnownedUserDataMap.remove(key);
@@ -250,7 +254,7 @@
         mThreadChecker.assertOnValidThread();
 
         // Protect against potential races.
-        if (mDestroyChecker.isDestroyed()) return;
+        if (isDestroyed()) return;
 
         // Create a shallow copy of all keys to ensure each held object can safely remove itself
         // from the map while iterating over their keys.
@@ -272,12 +276,23 @@
         return mUnownedUserDataMap.size();
     }
 
+    @EnsuresNonNullIf(
+            value = {"mUnownedUserDataMap", "mHandler"},
+            result = false)
     /* package */ boolean isDestroyed() {
-        return mDestroyChecker.isDestroyed();
+        if (!mDestroyChecker.isDestroyed()) {
+            assumeNonNull(mUnownedUserDataMap);
+            assumeNonNull(mHandler);
+            return false;
+        }
+        return true;
     }
 
+    @EnsuresNonNull({"mUnownedUserDataMap", "mHandler"})
     private void checkState() {
         mThreadChecker.assertOnValidThread();
         mDestroyChecker.checkNotDestroyed();
+        assumeNonNull(mUnownedUserDataMap);
+        assumeNonNull(mHandler);
     }
 }
diff --git a/tot/base/android/java/src/org/chromium/base/UnownedUserDataKey.java b/tot/base/android/java/src/org/chromium/base/UnownedUserDataKey.java
index 9a6b5b6..9d9f979 100644
--- a/tot/base/android/java/src/org/chromium/base/UnownedUserDataKey.java
+++ b/tot/base/android/java/src/org/chromium/base/UnownedUserDataKey.java
@@ -4,11 +4,11 @@
 
 package org.chromium.base;
 
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
 import androidx.annotation.VisibleForTesting;
 
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -61,8 +61,9 @@
  * @see UnownedUserDataHost for more details on ownership and typical usage.
  * @see UnownedUserData for the marker interface used for this type of data.
  */
+@NullMarked
 public final class UnownedUserDataKey<T extends UnownedUserData> {
-    @NonNull private final Class<T> mClazz;
+    private final Class<T> mClazz;
     // A Set that uses WeakReference<UnownedUserDataHost> internally.
     private final Set<UnownedUserDataHost> mWeakHostAttachments =
             Collections.newSetFromMap(new WeakHashMap<>());
@@ -72,11 +73,10 @@
      *
      * @param clazz The particular {@link UnownedUserData} class.
      */
-    public UnownedUserDataKey(@NonNull Class<T> clazz) {
+    public UnownedUserDataKey(Class<T> clazz) {
         mClazz = clazz;
     }
 
-    @NonNull
     /* package */ final Class<T> getValueClass() {
         return mClazz;
     }
@@ -88,7 +88,7 @@
      * @param host   The host to attach the {@code object} to.
      * @param object The object to attach.
      */
-    public final void attachToHost(@NonNull UnownedUserDataHost host, @NonNull T object) {
+    public final void attachToHost(UnownedUserDataHost host, T object) {
         Objects.requireNonNull(object);
         // Setting a new value might lead to detachment of previously attached data, including
         // re-entry to this key, to happen before we update the {@link #mHostAttachments}.
@@ -108,8 +108,7 @@
      * @param host The host to retrieve the {@link UnownedUserData} from.
      * @return The current {@link UnownedUserData} stored in the {@code host}, or {@code null}.
      */
-    @Nullable
-    public final T retrieveDataFromHost(@NonNull UnownedUserDataHost host) {
+    public final @Nullable T retrieveDataFromHost(UnownedUserDataHost host) {
         assertNoDestroyedAttachments();
         for (UnownedUserDataHost attachedHost : mWeakHostAttachments) {
             if (host.equals(attachedHost)) {
@@ -125,7 +124,7 @@
      *
      * @param host The host to detach from.
      */
-    public final void detachFromHost(@NonNull UnownedUserDataHost host) {
+    public final void detachFromHost(UnownedUserDataHost host) {
         assertNoDestroyedAttachments();
         for (UnownedUserDataHost attachedHost : new ArrayList<>(mWeakHostAttachments)) {
             if (host.equals(attachedHost)) {
@@ -140,7 +139,7 @@
      *
      * @param object The object to detach from all hosts.
      */
-    public final void detachFromAllHosts(@NonNull T object) {
+    public final void detachFromAllHosts(T object) {
         assertNoDestroyedAttachments();
         for (UnownedUserDataHost attachedHost : new ArrayList<>(mWeakHostAttachments)) {
             if (object.equals(attachedHost.get(this))) {
@@ -155,7 +154,7 @@
      * @param host The host to check if the {@link UnownedUserData} is attached to.
      * @return true if currently attached, false otherwise.
      */
-    public final boolean isAttachedToHost(@NonNull UnownedUserDataHost host) {
+    public final boolean isAttachedToHost(UnownedUserDataHost host) {
         T t = retrieveDataFromHost(host);
         return t != null;
     }
@@ -163,12 +162,12 @@
     /**
      * @return Whether the {@link UnownedUserData} is currently attached to any hosts with this key.
      */
-    public final boolean isAttachedToAnyHost(@NonNull T object) {
+    public final boolean isAttachedToAnyHost(T object) {
         return getHostAttachmentCount(object) > 0;
     }
 
     @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
-    /* package */ int getHostAttachmentCount(@NonNull T object) {
+    /* package */ int getHostAttachmentCount(T object) {
         assertNoDestroyedAttachments();
         int ret = 0;
         for (UnownedUserDataHost attachedHost : mWeakHostAttachments) {
diff --git a/tot/base/android/java/src/org/chromium/base/UserData.java b/tot/base/android/java/src/org/chromium/base/UserData.java
index 53d8f29..7060d6a 100644
--- a/tot/base/android/java/src/org/chromium/base/UserData.java
+++ b/tot/base/android/java/src/org/chromium/base/UserData.java
@@ -4,10 +4,13 @@
 
 package org.chromium.base;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
  * Interface to be implemented by the classes make themselves attacheable to
  * a host class that holds {@link UserDataHost}.
  */
+@NullMarked
 public interface UserData {
     /**
      * Called when {@link UserData} object needs to be destroyed.
diff --git a/tot/base/android/java/src/org/chromium/base/UserDataHost.java b/tot/base/android/java/src/org/chromium/base/UserDataHost.java
index aa173cb..a9673cd 100644
--- a/tot/base/android/java/src/org/chromium/base/UserDataHost.java
+++ b/tot/base/android/java/src/org/chromium/base/UserDataHost.java
@@ -4,7 +4,12 @@
 
 package org.chromium.base;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import org.chromium.base.ThreadUtils.ThreadChecker;
+import org.chromium.build.annotations.EnsuresNonNull;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.HashMap;
 
@@ -48,18 +53,13 @@
  *
  * </code>
  */
+@NullMarked
 public final class UserDataHost {
     private final ThreadChecker mThreadChecker = new ThreadChecker();
 
-    private HashMap<Class<? extends UserData>, UserData> mUserDataMap = new HashMap<>();
+    private @Nullable HashMap<Class<? extends UserData>, UserData> mUserDataMap = new HashMap<>();
 
-    private static void checkArgument(boolean condition) {
-        if (!condition) {
-            throw new IllegalArgumentException(
-                    "Neither key nor object of UserDataHost can be null.");
-        }
-    }
-
+    @EnsuresNonNull("mUserDataMap")
     private void checkThreadAndState() {
         mThreadChecker.assertOnValidThread();
         if (mUserDataMap == null) {
@@ -71,14 +71,18 @@
      * Associates the specified object with the specified key.
      * @param key Type token with which the specified object is to be associated.
      * @param object Object to be associated with the specified key.
-     * @return the object just stored, or {@code null} if storing the object failed.
+     * @return the object just stored.
      */
     public <T extends UserData> T setUserData(Class<T> key, T object) {
         checkThreadAndState();
-        checkArgument(key != null && object != null);
+        if (key == null || object == null) {
+            throw new IllegalArgumentException();
+        }
 
         mUserDataMap.put(key, object);
-        return getUserData(key);
+
+        // Since we just .put the object in the HashMap, a subsequent .get will always succeed.
+        return assumeNonNull(getUserData(key));
     }
 
     /**
@@ -88,9 +92,11 @@
      * @return the value to which the specified key is mapped, or null if this map
      *         contains no mapping for {@code key}.
      */
-    public <T extends UserData> T getUserData(Class<T> key) {
+    public <T extends UserData> @Nullable T getUserData(Class<T> key) {
         checkThreadAndState();
-        checkArgument(key != null);
+        if (key == null) {
+            throw new IllegalArgumentException();
+        }
 
         return key.cast(mUserDataMap.get(key));
     }
@@ -103,12 +109,15 @@
      */
     public <T extends UserData> T removeUserData(Class<T> key) {
         checkThreadAndState();
-        checkArgument(key != null);
+        if (key == null) {
+            throw new IllegalArgumentException();
+        }
 
-        if (!mUserDataMap.containsKey(key)) {
+        UserData ret = mUserDataMap.remove(key);
+        if (ret == null) {
             throw new IllegalStateException("UserData for the key is not present.");
         }
-        return key.cast(mUserDataMap.remove(key));
+        return key.cast(ret);
     }
 
     /**
diff --git a/tot/base/android/java/src/org/chromium/base/ValueChangedCallback.java b/tot/base/android/java/src/org/chromium/base/ValueChangedCallback.java
index 4317cf6..ce62ebf 100644
--- a/tot/base/android/java/src/org/chromium/base/ValueChangedCallback.java
+++ b/tot/base/android/java/src/org/chromium/base/ValueChangedCallback.java
@@ -4,10 +4,9 @@
 
 package org.chromium.base;
 
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-
 import org.chromium.base.supplier.ObservableSupplier;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.Objects;
 
@@ -21,6 +20,7 @@
  *
  * @param <T> The type to observe.
  */
+@NullMarked
 public class ValueChangedCallback<T> implements Callback<T> {
     /**
      * Interface for observers that care about monitoring both the old and new values when a
@@ -40,13 +40,13 @@
         public void onValueChanged(@Nullable T newValue, @Nullable T oldValue);
     }
 
-    private final @NonNull ValueChangedObserver<T> mValueChangedObserver;
+    private final ValueChangedObserver<T> mValueChangedObserver;
     private @Nullable T mLastValue;
 
     /**
      * @param onValueChangedObserver The {@link ValueChangedObserver} that receives updates.
      */
-    public ValueChangedCallback(@NonNull ValueChangedObserver<T> onValueChangedObserver) {
+    public ValueChangedCallback(ValueChangedObserver<T> onValueChangedObserver) {
         mValueChangedObserver = onValueChangedObserver;
     }
 
diff --git a/tot/base/android/java/src/org/chromium/base/WrappedClassLoader.java b/tot/base/android/java/src/org/chromium/base/WrappedClassLoader.java
index 45a6bb0..4d64225 100644
--- a/tot/base/android/java/src/org/chromium/base/WrappedClassLoader.java
+++ b/tot/base/android/java/src/org/chromium/base/WrappedClassLoader.java
@@ -6,10 +6,14 @@
 
 import dalvik.system.BaseDexClassLoader;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /**
  * This class wraps two given ClassLoader objects and delegates findClass() and findLibrary() calls
  * to the first one that returns a match.
  */
+@NullMarked
 public class WrappedClassLoader extends ClassLoader {
     private final ClassLoader mPrimaryClassLoader;
     private final ClassLoader mSecondaryClassLoader;
@@ -34,7 +38,7 @@
     }
 
     @Override
-    public String findLibrary(String name) {
+    public @Nullable String findLibrary(String name) {
         String path = null;
         // BaseDexClassLoader has a public findLibrary method, but ClassLoader's is protected
         // so we can only do this for classloaders that actually do extend BaseDexClassLoader.
diff --git a/tot/base/android/java/src/org/chromium/base/cached_flags/ValuesReturned.java b/tot/base/android/java/src/org/chromium/base/cached_flags/ValuesReturned.java
index a64813f..a777327 100644
--- a/tot/base/android/java/src/org/chromium/base/cached_flags/ValuesReturned.java
+++ b/tot/base/android/java/src/org/chromium/base/cached_flags/ValuesReturned.java
@@ -9,11 +9,13 @@
 import androidx.annotation.GuardedBy;
 
 import org.chromium.base.supplier.Supplier;
+import org.chromium.build.annotations.NullMarked;
 
 import java.util.HashMap;
 import java.util.Map;
 
 /** Keeps track of values returned for cached flags and field trial parameters. */
+@NullMarked
 public abstract class ValuesReturned {
     @GuardedBy("sBoolValues")
     private static final Map<String, Boolean> sBoolValues = new HashMap<>();
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/FrameMetricsListener.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/FrameMetricsListener.java
index 30c7aec..e429f78 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/FrameMetricsListener.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/FrameMetricsListener.java
@@ -18,6 +18,7 @@
 import org.chromium.base.ContextUtils;
 import org.chromium.base.TimeUtils;
 import org.chromium.base.TraceEvent;
+import org.chromium.build.annotations.NullMarked;
 
 import java.util.concurrent.atomic.AtomicBoolean;
 
@@ -25,6 +26,7 @@
  * This class receives OnFrameMetricsAvailableListener.onFrameMetricsAvailable() callbacks and
  * records frame durations in a FrameMetricsStore instance.
  */
+@NullMarked
 @RequiresApi(api = VERSION_CODES.N)
 public class FrameMetricsListener implements OnFrameMetricsAvailableListener {
     private class DisplayListenerBackend implements DisplayListener {
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/FrameMetricsStore.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/FrameMetricsStore.java
index 0643b76..c7db03b 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/FrameMetricsStore.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/FrameMetricsStore.java
@@ -8,6 +8,7 @@
 import org.chromium.base.TimeUtils;
 import org.chromium.base.TraceEvent;
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -17,6 +18,7 @@
 /**
  * This class stores relevant metrics from FrameMetrics between the calls to UMA reporting methods.
  */
+@NullMarked
 public class FrameMetricsStore {
     private final ThreadChecker mThreadChecker = new ThreadChecker();
     // An arbitrary value from which to create a trace event async track. The only risk if this
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankActivityTracker.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankActivityTracker.java
index 25286eb..9857c8d 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankActivityTracker.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankActivityTracker.java
@@ -14,6 +14,7 @@
 import org.chromium.base.ApplicationStatus.ActivityStateListener;
 import org.chromium.base.ThreadUtils.ThreadChecker;
 import org.chromium.base.lifetime.DestroyChecker;
+import org.chromium.build.annotations.NullMarked;
 
 import java.lang.ref.WeakReference;
 
@@ -22,6 +23,7 @@
  * periodic jank metric reporting and frame metric recording based on the Activity's lifecycle
  * events.
  */
+@NullMarked
 @RequiresApi(api = VERSION_CODES.N)
 class JankActivityTracker extends JankTrackerStateController implements ActivityStateListener {
     private final ThreadChecker mThreadChecker = new ThreadChecker();
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankEndScenarioTime.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankEndScenarioTime.java
index d2d1a9e..d6033bc 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankEndScenarioTime.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankEndScenarioTime.java
@@ -4,16 +4,20 @@
 
 package org.chromium.base.jank_tracker;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /**
  * A simple Data structure that holds a uptimeNanos that we wish to have data up until, and a delay
  * to wait for this data from the Android FrameMetrics API.
  */
+@NullMarked
 public final class JankEndScenarioTime {
     public final long endScenarioTimeNs;
     // 100ms should be long enough to receive frame metric timeline if they haven't been dropped.
     public final long timeoutDelayMs = 100;
 
-    public static JankEndScenarioTime endAt(long uptimeNanos) {
+    public static @Nullable JankEndScenarioTime endAt(long uptimeNanos) {
         if (uptimeNanos <= 0) {
             return null;
         }
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java
index 5512f7e..5709e7a 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankMetricUMARecorder.java
@@ -7,7 +7,10 @@
 import org.jni_zero.JNINamespace;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Sends Android jank metrics to native to be recorded using UMA. */
+@NullMarked
 @JNINamespace("base::android")
 public class JankMetricUMARecorder {
     public static void recordJankMetricsToUMA(
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankMetrics.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankMetrics.java
index 62daec4..7820769 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankMetrics.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankMetrics.java
@@ -4,10 +4,13 @@
 
 package org.chromium.base.jank_tracker;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
  * This class is a container for jank metrics, which are processed FrameMetrics ready to be uploaded
  * to UMA.
  */
+@NullMarked
 class JankMetrics {
     public final long[] timestampsNs;
     public final long[] durationsNs;
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankReportingRunnable.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankReportingRunnable.java
index 15cf69e..51e707d 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankReportingRunnable.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankReportingRunnable.java
@@ -7,12 +7,15 @@
 import android.os.Handler;
 
 import org.chromium.base.TraceEvent;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /**
  * This runnable receives a FrameMetricsStore instance and starts/stops tracking a given scenario.
  * When a scenario stops it takes its metrics and sends them to native to be recorded in UMA.
  * This is executed by JankReportingScheduler on its own thread.
  */
+@NullMarked
 class JankReportingRunnable implements Runnable {
     private final FrameMetricsStore mMetricsStore;
     private final JankScenario mScenario;
@@ -21,7 +24,7 @@
     private final Handler mHandler;
     // If metrics should be collected based on the state (scrolling) specify a
     // JankEndScenarioTime.
-    private final JankEndScenarioTime mJankEndScenarioTime;
+    private final @Nullable JankEndScenarioTime mJankEndScenarioTime;
 
     // When a JankEndScenarioTime is specified we don't immediately collect the metrics but instead
     // post a task (this runnable). However to keep code reuse the same between delay/no-delay we
@@ -67,7 +70,7 @@
             JankScenario scenario,
             boolean isStartingTracking,
             Handler handler,
-            JankEndScenarioTime endScenarioTime) {
+            @Nullable JankEndScenarioTime endScenarioTime) {
         mMetricsStore = metricsStore;
         mScenario = scenario;
         mIsStartingTracking = isStartingTracking;
@@ -92,13 +95,10 @@
                 mMetricsStore.startTrackingScenario(mScenario);
                 return;
             }
-            boolean dataIsReady =
-                    mJankEndScenarioTime == null
-                            || (mJankEndScenarioTime != null
-                                    && mMetricsStore.hasReceivedMetricsPast(
-                                            mJankEndScenarioTime.endScenarioTimeNs));
-
-            if (dataIsReady) {
+            if (mJankEndScenarioTime == null
+                    || mMetricsStore.hasReceivedMetricsPast(
+                            mJankEndScenarioTime.endScenarioTimeNs)) {
+                // Data is ready.
                 new FinalReportingRunnable().run();
             } else {
                 mHandler.postDelayed(
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankReportingScheduler.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankReportingScheduler.java
index d90c83b..2158d2d 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankReportingScheduler.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankReportingScheduler.java
@@ -7,12 +7,16 @@
 import android.os.Handler;
 import android.os.HandlerThread;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
  * This class receives requests to start and stop jank scenario tracking and runs them in a
  * HandlerThread it creates. In addition it handles the recording of periodic jank metrics.
  */
+@NullMarked
 public class JankReportingScheduler {
     private static final long PERIODIC_METRIC_DELAY_MS = 5_000;
     private final FrameMetricsStore mFrameMetricsStore;
@@ -77,7 +81,8 @@
         finishTrackingScenario(scenario, JankEndScenarioTime.endAt(endScenarioTimeNs));
     }
 
-    public void finishTrackingScenario(JankScenario scenario, JankEndScenarioTime endScenarioTime) {
+    public void finishTrackingScenario(
+            JankScenario scenario, @Nullable JankEndScenarioTime endScenarioTime) {
         // We store the stop task in case the delay is greater than zero and we start this scenario
         // again.
         JankReportingRunnable runnable =
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankScenario.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankScenario.java
index 42e7b4c..6827d5d 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankScenario.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankScenario.java
@@ -6,10 +6,13 @@
 
 import androidx.annotation.IntDef;
 
+import org.chromium.build.annotations.NullMarked;
+
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.util.Objects;
 
+@NullMarked
 public class JankScenario {
     /**
      * A list of jank scenarios to be tracked, each scenario corresponds to a specific user journey
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankTracker.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankTracker.java
index b3f22ce..e3344c4 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankTracker.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankTracker.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base.jank_tracker;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Interface for Android UI jank tracking. */
+@NullMarked
 public interface JankTracker {
     /**
      * Starts tracking UI jank for a specific use scenario (e.g. Tab switcher, Omnibox, etc.),
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankTrackerImpl.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankTrackerImpl.java
index dbef27b..27a4d23 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankTrackerImpl.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankTrackerImpl.java
@@ -9,6 +9,9 @@
 
 import org.chromium.base.task.PostTask;
 import org.chromium.base.task.TaskTraits;
+import org.chromium.build.annotations.EnsuresNonNullIf;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.lang.ref.WeakReference;
 
@@ -19,15 +22,14 @@
  * based on activity state. When the activity is being destroyed {@link #destroy()} should be called
  * to clear the activity state observer. All methods should be called from the UI thread.
  */
+@NullMarked
 public class JankTrackerImpl implements JankTracker {
     // We use the DEADLINE field in the Android FrameMetrics which was added in S.
     private static final boolean IS_TRACKING_ENABLED =
             Build.VERSION.SDK_INT >= Build.VERSION_CODES.S;
 
-    private boolean mIsInitialized;
-    private JankTrackerStateController mController;
-    private JankReportingScheduler mReportingScheduler;
-    private boolean mDestroyed;
+    private @Nullable JankTrackerStateController mController;
+    private @Nullable JankReportingScheduler mReportingScheduler;
 
     /**
      * Creates a new JankTracker instance tracking UI rendering of an activity. Metric recording
@@ -44,7 +46,9 @@
                     public void run() {
                         // If we've been destroyed or the Activity is gone early out.
                         Activity innerActivity = ref.get();
-                        if (mDestroyed || innerActivity == null || innerActivity.isDestroyed()) {
+                        if (mController == null
+                                || innerActivity == null
+                                || innerActivity.isDestroyed()) {
                             return;
                         }
 
@@ -78,6 +82,7 @@
         constructInternalFinal(controller);
     }
 
+    @EnsuresNonNullIf("mReportingScheduler")
     private boolean constructInternalPreController(JankReportingScheduler scheduler) {
         if (!IS_TRACKING_ENABLED) {
             mReportingScheduler = null;
@@ -88,15 +93,23 @@
         return true;
     }
 
+    @EnsuresNonNullIf({"mController", "mReportingScheduler"})
+    private boolean isInitialized() {
+        if (mController == null) {
+            return false;
+        }
+        assert mReportingScheduler != null;
+        return true;
+    }
+
     private void constructInternalFinal(JankTrackerStateController controller) {
         mController = controller;
         mController.initialize();
-        mIsInitialized = true;
     }
 
     @Override
     public void startTrackingScenario(JankScenario scenario) {
-        if (!IS_TRACKING_ENABLED || !mIsInitialized) return;
+        if (!isInitialized()) return;
 
         mReportingScheduler.startTrackingScenario(scenario);
     }
@@ -108,7 +121,7 @@
 
     @Override
     public void finishTrackingScenario(JankScenario scenario, long endScenarioTimeNs) {
-        if (!IS_TRACKING_ENABLED || !mIsInitialized) return;
+        if (!isInitialized()) return;
 
         mReportingScheduler.finishTrackingScenario(scenario, endScenarioTimeNs);
     }
@@ -116,8 +129,8 @@
     /** Stops listening for Activity state changes. */
     @Override
     public void destroy() {
-        mDestroyed = true;
-        if (!IS_TRACKING_ENABLED || !mIsInitialized) return;
+        if (!isInitialized()) return;
         mController.destroy();
+        mController = null;
     }
 }
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankTrackerStateController.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankTrackerStateController.java
index 2de3d2c..28bc35e 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/JankTrackerStateController.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/JankTrackerStateController.java
@@ -7,6 +7,8 @@
 import android.view.Window;
 
 import org.chromium.base.Log;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /**
  * A simple holder class to enable easy starting and stopping of metric listening as well as
@@ -14,6 +16,7 @@
  * should be hooked up to some sort of listener to when to start/stop listening and periodic
  * metrics.
  */
+@NullMarked
 public class JankTrackerStateController {
     private static final String TAG = "JankTracker";
     protected final FrameMetricsListener mFrameMetricsListener;
@@ -33,7 +36,7 @@
         mReportingScheduler.stopReportingPeriodicMetrics();
     }
 
-    public void startMetricCollection(Window window) {
+    public void startMetricCollection(@Nullable Window window) {
         mFrameMetricsListener.setIsListenerRecording(true);
         if (window != null) {
             window.addOnFrameMetricsAvailableListener(
@@ -41,7 +44,7 @@
         }
     }
 
-    public void stopMetricCollection(Window window) {
+    public void stopMetricCollection(@Nullable Window window) {
         mFrameMetricsListener.setIsListenerRecording(false);
         if (window != null) {
             try {
diff --git a/tot/base/android/java/src/org/chromium/base/jank_tracker/PlaceholderJankTracker.java b/tot/base/android/java/src/org/chromium/base/jank_tracker/PlaceholderJankTracker.java
index 1fd9124..5b2cd29 100644
--- a/tot/base/android/java/src/org/chromium/base/jank_tracker/PlaceholderJankTracker.java
+++ b/tot/base/android/java/src/org/chromium/base/jank_tracker/PlaceholderJankTracker.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base.jank_tracker;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Placeholder implementation of JankTracker. */
+@NullMarked
 public class PlaceholderJankTracker implements JankTracker {
     @Override
     public void startTrackingScenario(JankScenario scenario) {}
diff --git a/tot/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java b/tot/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java
index 8ca2fc3..a752ab7 100644
--- a/tot/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java
+++ b/tot/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java
@@ -16,8 +16,6 @@
 import androidx.annotation.VisibleForTesting;
 
 import org.jni_zero.JNINamespace;
-import org.jni_zero.NativeLibraryLoadedStatus;
-import org.jni_zero.NativeLibraryLoadedStatus.NativeLibraryLoadedStatusProvider;
 import org.jni_zero.NativeMethods;
 
 import org.chromium.base.BaseSwitches;
@@ -34,6 +32,8 @@
 import org.chromium.base.metrics.UmaRecorderHolder;
 import org.chromium.build.BuildConfig;
 import org.chromium.build.NativeLibraries;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -52,6 +52,7 @@
  * <p>See also base/android/library_loader/library_loader_hooks.cc, which contains the native
  * counterpart to this class.
  */
+@NullMarked
 @JNINamespace("base::android")
 public class LibraryLoader {
     private static final String TAG = "LibraryLoader";
@@ -119,10 +120,10 @@
     // Always accessed via getLinker() because the choice of the class can be influenced by
     // public setLinkerImplementation() below.
     @GuardedBy("mLock")
-    private Linker mLinker;
+    private @Nullable Linker mLinker;
 
     @GuardedBy("mLock")
-    private NativeLibraryPreloader mLibraryPreloader;
+    private @Nullable NativeLibraryPreloader mLibraryPreloader;
 
     @GuardedBy("mLock")
     private boolean mLibraryPreloaderCalled;
@@ -152,7 +153,7 @@
     @VisibleForTesting public static boolean sOverrideNativeLibraryCannotBeLoadedForTesting;
 
     // Allow embedders to register a callback to handle native library load failures.
-    public static Callback<UnsatisfiedLinkError> sLoadFailedCallback;
+    public static @Nullable Callback<UnsatisfiedLinkError> sLoadFailedCallback;
 
     // Returns true when sharing RELRO between the browser process and the app zygote should *not*
     // be attempted.
@@ -417,15 +418,6 @@
         if (DEBUG) {
             logLinkerUsed();
         }
-        if (BuildConfig.ENABLE_ASSERTS) {
-            NativeLibraryLoadedStatus.setProvider(
-                    new NativeLibraryLoadedStatusProvider() {
-                        @Override
-                        public boolean areNativeMethodsReady() {
-                            return isMainDexLoaded();
-                        }
-                    });
-        }
     }
 
     /**
diff --git a/tot/base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java b/tot/base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java
index 15d5cc1..00f2d0b 100644
--- a/tot/base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java
+++ b/tot/base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java
@@ -13,6 +13,7 @@
 import org.chromium.base.TraceEvent;
 import org.chromium.base.task.PostTask;
 import org.chromium.base.task.TaskTraits;
+import org.chromium.build.annotations.NullMarked;
 
 import java.util.concurrent.atomic.AtomicBoolean;
 
@@ -22,6 +23,7 @@
  * See also base/android/library_loader/library_prefetcher_hooks.cc, which contains
  * the native counterpart to this class.
  */
+@NullMarked
 @JNINamespace("base::android")
 public class LibraryPrefetcher {
 
@@ -76,13 +78,21 @@
                 });
     }
 
+    public static void prefetchNativeLibraryForWebView() {
+        LibraryPrefetcherJni.get().prefetchNativeLibraryForWebView();
+    }
+
     @NativeMethods
     interface Natives {
         // Finds the ranges corresponding to the native library pages, forks a new
         // process to prefetch these pages and waits for it. The new process then
         // terminates. This is blocking.
+        // On some devices, this prefetches only the ordered part of the library.
         void forkAndPrefetchNativeLibrary();
 
+        // Similar to the above function, but always prefetches the whole library.
+        void prefetchNativeLibraryForWebView();
+
         // Returns the percentage of the native library code page that are currently reseident in
         // memory.
         int percentageOfResidentNativeLibraryCode();
diff --git a/tot/base/android/java/src/org/chromium/base/library_loader/Linker.java b/tot/base/android/java/src/org/chromium/base/library_loader/Linker.java
index 70b176b..7be4710 100644
--- a/tot/base/android/java/src/org/chromium/base/library_loader/Linker.java
+++ b/tot/base/android/java/src/org/chromium/base/library_loader/Linker.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base.library_loader;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.annotation.SuppressLint;
 import android.os.Bundle;
 import android.os.Parcel;
@@ -11,7 +13,6 @@
 import android.os.Parcelable;
 
 import androidx.annotation.IntDef;
-import androidx.annotation.NonNull;
 import androidx.annotation.VisibleForTesting;
 
 import org.jni_zero.AccessedByNative;
@@ -19,6 +20,8 @@
 import org.chromium.base.Log;
 import org.chromium.base.StreamUtil;
 import org.chromium.base.metrics.RecordHistogram;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -68,6 +71,7 @@
  *   available to then send the Bundle to Linkers in other processes, consumed
  *   by takeSharedRelrosFromBundle().
  */
+@NullMarked
 class Linker {
     private static final String TAG = "Linker";
 
@@ -93,12 +97,12 @@
     // process is a "RELRO producer".
     @GuardedBy("mLock")
     @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
-    protected LibInfo mLocalLibInfo;
+    protected @Nullable LibInfo mLocalLibInfo;
 
     // The library info that was transferred from another process. Only useful if it contains RELRO
     // FD.
     @GuardedBy("mLock")
-    private LibInfo mRemoteLibInfo;
+    private @Nullable LibInfo mRemoteLibInfo;
 
     // Whether this Linker instance should potentially create the RELRO region. Even if true, the
     // library loading can fall back to the system linker without producing the region. The default
@@ -153,7 +157,7 @@
         }
     }
 
-    private static Linker sLinkerForAssert;
+    private static @Nullable Linker sLinkerForAssert;
 
     Linker() {
         // Only one instance is allowed in a given process because effects of loading a library are
@@ -246,7 +250,10 @@
             if (mState != State.UNINITIALIZED) return;
             chooseAndReserveMemoryRange(asRelroProducer, preference, addressHint);
             if (DEBUG) {
-                Log.i(TAG, "ensureInitialized: chose address=0x%x", mLocalLibInfo.mLoadAddress);
+                Log.i(
+                        TAG,
+                        "ensureInitialized: chose address=0x%x",
+                        assumeNonNull(mLocalLibInfo).mLoadAddress);
             }
             mState = State.INITIALIZED;
         }
@@ -333,7 +340,7 @@
             // being ignored in native anyway. It seems the only effect of removing this check here
             // will be extra added samples to the RelroSharingStatus2 histogram. This will be a tiny
             // bit smoother to do after M99.
-            return mLocalLibInfo.mLoadAddress != 0;
+            return assumeNonNull(mLocalLibInfo).mLoadAddress != 0;
         }
         return false;
     }
@@ -386,7 +393,7 @@
                 Log.w(TAG, "Failed to load native library with shared RELRO, retrying without");
                 try {
                     // Retry without relocation sharing.
-                    mLocalLibInfo.mLoadAddress = 0;
+                    assumeNonNull(mLocalLibInfo).mLoadAddress = 0;
                     attemptLoadLibraryLocked(library, RelroSharingMode.NO_SHARING);
                 } catch (UnsatisfiedLinkError e2) {
                     Log.w(TAG, "Failed to load native library without RELRO sharing");
@@ -406,10 +413,11 @@
             if (DEBUG) Log.i(TAG, "putSharedRelrosToBundle: state=%d", mState);
             if (mState == State.DONE_PROVIDE_RELRO) {
                 assert mRelroProducer;
-                relros = mLocalLibInfo.toBundle();
+                relros = assumeNonNull(mLocalLibInfo).toBundle();
             }
             bundle.putBundle(SHARED_RELROS, relros);
             if (DEBUG && relros != null) {
+                assert mLocalLibInfo != null;
                 Log.i(
                         TAG,
                         "putSharedRelrosToBundle() puts mLoadAddress=0x%x, mLoadSize=%d, "
@@ -474,6 +482,7 @@
     @GuardedBy("mLock")
     private void loadWithoutProducingRelro(String libFilePath) {
         assert mRemoteLibInfo == null || libFilePath.equals(mRemoteLibInfo.mLibFilePath);
+        assert mLocalLibInfo != null;
         if (!getLinkerJni()
                 .loadLibrary(libFilePath, mLocalLibInfo, /* spawnRelroRegion= */ false)) {
             resetAndThrow(String.format("Unable to load library: %s", libFilePath), null);
@@ -485,22 +494,23 @@
     // System.loadLibrary() is useful. Records a histogram to count failures.
     @GuardedBy("mLock")
     private void loadAndProduceSharedRelro(String libFilePath) {
-        mLocalLibInfo.mLibFilePath = libFilePath;
-        if (getLinkerJni().loadLibrary(libFilePath, mLocalLibInfo, /* spawnRelroRegion= */ true)) {
+        var localLibInfo = assumeNonNull(mLocalLibInfo);
+        localLibInfo.mLibFilePath = libFilePath;
+        if (getLinkerJni().loadLibrary(libFilePath, localLibInfo, /* spawnRelroRegion= */ true)) {
             if (DEBUG) {
                 Log.i(
                         TAG,
                         "Successfully spawned RELRO: mLoadAddress=0x%x, mLoadSize=%d",
-                        mLocalLibInfo.mLoadAddress,
-                        mLocalLibInfo.mLoadSize);
+                        localLibInfo.mLoadAddress,
+                        localLibInfo.mLoadSize);
             }
         } else {
             Log.e(TAG, "Unable to load with Linker, using the system linker instead");
             // System.loadLibrary() below implements the fallback.
-            mLocalLibInfo.mRelroFd = -1;
+            localLibInfo.mRelroFd = -1;
         }
         RecordHistogram.recordBooleanHistogram(
-                "ChromiumAndroidLinker.RelroProvidedSuccessfully", mLocalLibInfo.mRelroFd != -1);
+                "ChromiumAndroidLinker.RelroProvidedSuccessfully", localLibInfo.mRelroFd != -1);
     }
 
     /**
@@ -567,18 +577,18 @@
      */
     @GuardedBy("mLock")
     private void atomicReplaceRelroLocked(boolean relroAvailableImmediately) {
-        assert mRemoteLibInfo != null;
         assert mState == State.DONE;
-        if (mRemoteLibInfo.mRelroFd == -1) return;
+        var remoteLibInfo = assumeNonNull(mRemoteLibInfo);
+        if (remoteLibInfo.mRelroFd == -1) return;
         if (DEBUG) {
             Log.i(
                     TAG,
                     "Received mRemoteLibInfo: mLoadAddress=0x%x, mLoadSize=%d",
-                    mRemoteLibInfo.mLoadAddress,
-                    mRemoteLibInfo.mLoadSize);
+                    remoteLibInfo.mLoadAddress,
+                    remoteLibInfo.mLoadSize);
         }
         if (mLocalLibInfo == null) return;
-        getLinkerJni().useRelros(mLocalLibInfo.mLoadAddress, mRemoteLibInfo);
+        getLinkerJni().useRelros(mLocalLibInfo.mLoadAddress, remoteLibInfo);
         // *Not* closing the RELRO FD after using it because the FD may need to be transferred to
         // another process after this point.
         if (DEBUG) Log.i(TAG, "Immediate RELRO availability: %b", relroAvailableImmediately);
@@ -619,7 +629,7 @@
     }
 
     @GuardedBy("mLock")
-    private void resetAndThrow(String message, UnsatisfiedLinkError cause) {
+    private void resetAndThrow(String message, @Nullable UnsatisfiedLinkError cause) {
         mState = State.INITIALIZED;
         Log.e(TAG, message);
         var e = new UnsatisfiedLinkError(message);
@@ -670,7 +680,7 @@
             }
         }
 
-        public static LibInfo fromBundle(Bundle bundle) {
+        public static @Nullable LibInfo fromBundle(Bundle bundle) {
             bundle.setClassLoader(Linker.class.getClassLoader());
             return bundle.getParcelable(EXTRA_LINKER_LIB_INFO);
         }
@@ -721,7 +731,7 @@
                     }
                 };
 
-        public String mLibFilePath;
+        public @Nullable String mLibFilePath;
 
         // IMPORTANT: Don't change these fields without modifying the
         // native code that accesses them directly!
@@ -743,7 +753,7 @@
          * @param libInfo holds the output values: |mLoadAddress| and |mLoadSize|. On failure sets
          *                the |libInfo.mLoadAddress| to 0.
          */
-        void findMemoryRegionAtRandomAddress(@NonNull LibInfo libInfo);
+        void findMemoryRegionAtRandomAddress(LibInfo libInfo);
 
         /**
          * Reserves the fixed address range starting at |libInfo.mLoadAddress| big enough to load
@@ -754,7 +764,7 @@
          *                returns the size in |libInfo.mLoadSize|. On failure sets the
          *                |libInfo.mLoadAddress| to 0.
          */
-        void reserveMemoryForLibrary(@NonNull LibInfo libInfo);
+        void reserveMemoryForLibrary(LibInfo libInfo);
 
         /**
          * Finds the (named) address range reservation made by the system zygote and dedicated for
@@ -765,7 +775,7 @@
          *                the start address and the size of the webview memory reservation to them.
          * @return whether the region was found.
          */
-        boolean findRegionReservedByWebViewZygote(@NonNull LibInfo libInfo);
+        boolean findRegionReservedByWebViewZygote(LibInfo libInfo);
 
         /**
          * Load the native library.
@@ -796,7 +806,7 @@
         int getRelroSharingResult();
     }
 
-    private static Linker.Natives sNativesInstance;
+    private static Linker.@Nullable Natives sNativesInstance;
 
     static void setLinkerNativesForTesting(Natives instance) {
         sNativesInstance = instance;
diff --git a/tot/base/android/java/src/org/chromium/base/library_loader/LinkerJni.java b/tot/base/android/java/src/org/chromium/base/library_loader/LinkerJni.java
index 981650d..d1c77a5 100644
--- a/tot/base/android/java/src/org/chromium/base/library_loader/LinkerJni.java
+++ b/tot/base/android/java/src/org/chromium/base/library_loader/LinkerJni.java
@@ -4,7 +4,7 @@
 
 package org.chromium.base.library_loader;
 
-import androidx.annotation.NonNull;
+import org.chromium.build.annotations.NullMarked;
 
 /**
  * Mockable stub for all native methods in Linker.
@@ -12,19 +12,20 @@
  * This functionality is usually generated from @NativeMethods, which cannot be used for the
  * auxiliary native library used by classes in Linker and other classes in this package.
  */
+@NullMarked
 class LinkerJni implements Linker.Natives {
     @Override
-    public void findMemoryRegionAtRandomAddress(@NonNull Linker.LibInfo libInfo) {
+    public void findMemoryRegionAtRandomAddress(Linker.LibInfo libInfo) {
         nativeFindMemoryRegionAtRandomAddress(libInfo);
     }
 
     @Override
-    public void reserveMemoryForLibrary(@NonNull Linker.LibInfo libInfo) {
+    public void reserveMemoryForLibrary(Linker.LibInfo libInfo) {
         nativeReserveMemoryForLibrary(libInfo);
     }
 
     @Override
-    public boolean findRegionReservedByWebViewZygote(@NonNull Linker.LibInfo libInfo) {
+    public boolean findRegionReservedByWebViewZygote(Linker.LibInfo libInfo) {
         return nativeFindRegionReservedByWebViewZygote(libInfo);
     }
 
@@ -46,13 +47,11 @@
 
     // Does not use JNI Generator because the native side is in libchromium_linker.so rather
     // libmonochrome.so
-    private static native void nativeFindMemoryRegionAtRandomAddress(
-            @NonNull Linker.LibInfo libInfo);
+    private static native void nativeFindMemoryRegionAtRandomAddress(Linker.LibInfo libInfo);
 
-    private static native void nativeReserveMemoryForLibrary(@NonNull Linker.LibInfo libInfo);
+    private static native void nativeReserveMemoryForLibrary(Linker.LibInfo libInfo);
 
-    private static native boolean nativeFindRegionReservedByWebViewZygote(
-            @NonNull Linker.LibInfo libInfo);
+    private static native boolean nativeFindRegionReservedByWebViewZygote(Linker.LibInfo libInfo);
 
     private static native boolean nativeLoadLibrary(
             String libFilePath, Linker.LibInfo libInfo, boolean spawnRelroRegion);
diff --git a/tot/base/android/java/src/org/chromium/base/library_loader/LoaderErrors.java b/tot/base/android/java/src/org/chromium/base/library_loader/LoaderErrors.java
index 43523bb..bd36e2f 100644
--- a/tot/base/android/java/src/org/chromium/base/library_loader/LoaderErrors.java
+++ b/tot/base/android/java/src/org/chromium/base/library_loader/LoaderErrors.java
@@ -6,10 +6,13 @@
 
 import androidx.annotation.IntDef;
 
+import org.chromium.build.annotations.NullMarked;
+
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 
 /** These are the possible failures from the LibraryLoader */
+@NullMarked
 @IntDef({
     LoaderErrors.NORMAL_COMPLETION,
     LoaderErrors.FAILED_TO_REGISTER_JNI,
diff --git a/tot/base/android/java/src/org/chromium/base/library_loader/NativeLibraryPreloader.java b/tot/base/android/java/src/org/chromium/base/library_loader/NativeLibraryPreloader.java
index f476014..1f05768 100644
--- a/tot/base/android/java/src/org/chromium/base/library_loader/NativeLibraryPreloader.java
+++ b/tot/base/android/java/src/org/chromium/base/library_loader/NativeLibraryPreloader.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base.library_loader;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
  * This is interface to preload the native library before calling System.loadLibrary.
  *
@@ -13,6 +15,7 @@
  * dlopen() later called by System.loadLibrary() becomes a noop. This is what the
  * only subclass (WebViewLibraryPreloader) is doing.
  */
+@NullMarked
 public abstract class NativeLibraryPreloader {
     public abstract int loadLibrary(String packageName);
 }
diff --git a/tot/base/android/java/src/org/chromium/base/library_loader/ProcessInitException.java b/tot/base/android/java/src/org/chromium/base/library_loader/ProcessInitException.java
index 6e7f422..4724f4c 100644
--- a/tot/base/android/java/src/org/chromium/base/library_loader/ProcessInitException.java
+++ b/tot/base/android/java/src/org/chromium/base/library_loader/ProcessInitException.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base.library_loader;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** The exception that is thrown when the initialization of a process has failed. */
+@NullMarked
 public class ProcessInitException extends RuntimeException {
     /**
      * @param errorCode This will be one of the LoaderErrors error codes.
diff --git a/tot/base/android/java/src/org/chromium/base/lifetime/DestroyChecker.java b/tot/base/android/java/src/org/chromium/base/lifetime/DestroyChecker.java
index e23437a..3f0430c 100644
--- a/tot/base/android/java/src/org/chromium/base/lifetime/DestroyChecker.java
+++ b/tot/base/android/java/src/org/chromium/base/lifetime/DestroyChecker.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base.lifetime;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
  * Utility class that help ensure destruction of objects happens only once.
  *
@@ -20,6 +22,7 @@
  *      It is therefore not necessary to call {@link #checkNotDestroyed()} in that case. It is also
  *      not allowed to call {@link #destroy()} more than once.
  */
+@NullMarked
 public class DestroyChecker implements Destroyable {
     private boolean mIsDestroyed;
 
diff --git a/tot/base/android/java/src/org/chromium/base/lifetime/Destroyable.java b/tot/base/android/java/src/org/chromium/base/lifetime/Destroyable.java
index 4efa150..d977be0 100644
--- a/tot/base/android/java/src/org/chromium/base/lifetime/Destroyable.java
+++ b/tot/base/android/java/src/org/chromium/base/lifetime/Destroyable.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base.lifetime;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Interface for items that require a controlled clean up. */
+@NullMarked
 public interface Destroyable {
     /** Cleans up resources held by the implementing object. */
     void destroy();
diff --git a/tot/base/android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java b/tot/base/android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java
index 147b6ab..2dcb141 100644
--- a/tot/base/android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java
+++ b/tot/base/android/java/src/org/chromium/base/memory/JavaHeapDumpGenerator.java
@@ -9,10 +9,12 @@
 import org.jni_zero.CalledByNative;
 
 import org.chromium.base.Log;
+import org.chromium.build.annotations.NullMarked;
 
 import java.io.IOException;
 
 /** Enables the generation of hprof files from heap dumps. */
+@NullMarked
 public final class JavaHeapDumpGenerator {
     private static final String TAG = "JavaHprofGenerator";
 
diff --git a/tot/base/android/java/src/org/chromium/base/memory/MemoryInfoBridge.java b/tot/base/android/java/src/org/chromium/base/memory/MemoryInfoBridge.java
index 7cd8cb3..437d93a 100644
--- a/tot/base/android/java/src/org/chromium/base/memory/MemoryInfoBridge.java
+++ b/tot/base/android/java/src/org/chromium/base/memory/MemoryInfoBridge.java
@@ -9,13 +9,14 @@
 import android.os.Debug;
 import android.os.Process;
 
-import androidx.annotation.Nullable;
-
 import org.jni_zero.CalledByNative;
 
 import org.chromium.base.ContextUtils;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /** Allows calling ActivityManager#getProcessMemoryInfo() from native. */
+@NullMarked
 public class MemoryInfoBridge {
     /**
      * Returns the result of ActivityManager#getProcessMemoryInfo() on itself.
@@ -25,7 +26,7 @@
      * throttling handling code there would become incorrect otherwise.
      */
     @CalledByNative
-    public static @Nullable Debug.MemoryInfo getActivityManagerMemoryInfoForSelf() {
+    public static Debug.@Nullable MemoryInfo getActivityManagerMemoryInfoForSelf() {
         ActivityManager activityManager =
                 (ActivityManager)
                         ContextUtils.getApplicationContext()
diff --git a/tot/base/android/java/src/org/chromium/base/memory/MemoryPressureCallback.java b/tot/base/android/java/src/org/chromium/base/memory/MemoryPressureCallback.java
index fd8a0b8..ed32ee2 100644
--- a/tot/base/android/java/src/org/chromium/base/memory/MemoryPressureCallback.java
+++ b/tot/base/android/java/src/org/chromium/base/memory/MemoryPressureCallback.java
@@ -5,8 +5,10 @@
 package org.chromium.base.memory;
 
 import org.chromium.base.MemoryPressureLevel;
+import org.chromium.build.annotations.NullMarked;
 
 /** Memory pressure callback interface. */
+@NullMarked
 @FunctionalInterface
 public interface MemoryPressureCallback {
     public void onPressure(@MemoryPressureLevel int pressure);
diff --git a/tot/base/android/java/src/org/chromium/base/memory/MemoryPressureMonitor.java b/tot/base/android/java/src/org/chromium/base/memory/MemoryPressureMonitor.java
index e0a5e84..caf4aa4 100644
--- a/tot/base/android/java/src/org/chromium/base/memory/MemoryPressureMonitor.java
+++ b/tot/base/android/java/src/org/chromium/base/memory/MemoryPressureMonitor.java
@@ -18,6 +18,8 @@
 import org.chromium.base.supplier.Supplier;
 import org.chromium.base.task.PostTask;
 import org.chromium.base.task.TaskTraits;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /**
  *
@@ -74,6 +76,7 @@
  * NOTE: This class should only be used on UiThread as defined by ThreadUtils (which is
  *       Android main thread for Chrome, but can be some other thread for WebView).</pre>
  */
+@NullMarked
 public class MemoryPressureMonitor {
     private static final int DEFAULT_THROTTLING_INTERVAL_MS = 60 * 1000;
 
@@ -84,7 +87,7 @@
 
     // Pressure received (but not reported) during the current throttling interval,
     // or null if no pressure was received.
-    private @MemoryPressureLevel Integer mThrottledPressure;
+    private @MemoryPressureLevel @Nullable Integer mThrottledPressure;
 
     // Whether we need to throttle pressure signals.
     private boolean mIsInsideThrottlingInterval;
@@ -94,8 +97,8 @@
     // That's for an experiment to run the broadcast receiver in the background
     private boolean mPostToBackgroundIsEnabled;
 
-    private Supplier<Integer> mCurrentPressureSupplierForTesting;
-    private MemoryPressureCallback mReportingCallbackForTesting;
+    private @Nullable Supplier<Integer> mCurrentPressureSupplierForTesting;
+    private @Nullable MemoryPressureCallback mReportingCallbackForTesting;
 
     private final Runnable mThrottlingIntervalTask = this::onThrottlingIntervalFinished;
 
@@ -270,7 +273,7 @@
      * Queries current memory pressure.
      * Returns null if the pressure couldn't be determined.
      */
-    private static @MemoryPressureLevel Integer getCurrentMemoryPressure() {
+    private static @MemoryPressureLevel @Nullable Integer getCurrentMemoryPressure() {
         // We used to have a histogram here to measure the duration of each successful
         // ActivityManager.getMyMemoryState() call called
         // Android.MemoryPressureMonitor.GetMyMemoryState.Succeeded.Time. 50th percentile was 0.8ms.
@@ -290,7 +293,7 @@
      * Returns null if |level| couldn't be mapped and should be ignored.
      */
     @VisibleForTesting
-    public static @MemoryPressureLevel Integer memoryPressureFromTrimLevel(int level) {
+    public static @MemoryPressureLevel @Nullable Integer memoryPressureFromTrimLevel(int level) {
         if (level >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
                 || level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) {
             return MemoryPressureLevel.CRITICAL;
diff --git a/tot/base/android/java/src/org/chromium/base/memory/MemoryPressureUma.java b/tot/base/android/java/src/org/chromium/base/memory/MemoryPressureUma.java
index 355bf8c..a7e71db 100644
--- a/tot/base/android/java/src/org/chromium/base/memory/MemoryPressureUma.java
+++ b/tot/base/android/java/src/org/chromium/base/memory/MemoryPressureUma.java
@@ -12,11 +12,14 @@
 import org.chromium.base.ContextUtils;
 import org.chromium.base.ThreadUtils;
 import org.chromium.base.metrics.RecordHistogram;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 
 /** Centralizes UMA data collection for Android-specific memory conditions. */
+@NullMarked
 public class MemoryPressureUma implements ComponentCallbacks2 {
     @IntDef({
         Notification.UNKNOWN_TRIM_LEVEL,
@@ -50,7 +53,7 @@
 
     private final String mHistogramName;
 
-    private static MemoryPressureUma sInstance;
+    private static @Nullable MemoryPressureUma sInstance;
 
     public static void initializeForBrowser() {
         initializeInstance("Browser");
diff --git a/tot/base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java b/tot/base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java
index 9b3f769..12bf08b 100644
--- a/tot/base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java
+++ b/tot/base/android/java/src/org/chromium/base/memory/MemoryPurgeManager.java
@@ -17,6 +17,7 @@
 import org.chromium.base.TimeUtils;
 import org.chromium.base.library_loader.LibraryLoader;
 import org.chromium.base.metrics.RecordHistogram;
+import org.chromium.build.annotations.NullMarked;
 
 /**
  * This class is similar in principle to MemoryPurgeManager in blink, but on the browser process
@@ -25,6 +26,7 @@
  *
  * <p>UI thread only.
  */
+@NullMarked
 public class MemoryPurgeManager implements ApplicationStatus.ApplicationStateListener {
     private boolean mStarted;
     private long mLastBackgroundPeriodStart = NEVER;
@@ -190,10 +192,13 @@
     }
 
     protected boolean shouldSelfFreeze() {
+        // This is the last check before we call native.
         if (!LibraryLoader.getInstance().isInitialized()) return false;
         if (MemoryPurgeManagerJni.get() == null) return false;
 
-        return MemoryPurgeManagerJni.get().isSelfFreezeEnabled();
+        // We don't check the feature here, because we need to forward to
+        // native in all cases, in order to record metrics.
+        return true;
     }
 
     @NativeMethods
@@ -201,7 +206,5 @@
         void postDelayedPurgeTaskOnUiThread(long delayMillis);
 
         boolean isOnPreFreezeMemoryTrimEnabled();
-
-        boolean isSelfFreezeEnabled();
     }
 }
diff --git a/tot/base/android/java/src/org/chromium/base/memory/SelfFreezeCallback.java b/tot/base/android/java/src/org/chromium/base/memory/SelfFreezeCallback.java
index 8eec553..0f75d39 100644
--- a/tot/base/android/java/src/org/chromium/base/memory/SelfFreezeCallback.java
+++ b/tot/base/android/java/src/org/chromium/base/memory/SelfFreezeCallback.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base.memory;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** self freeze callback interface. */
+@NullMarked
 @FunctionalInterface
 public interface SelfFreezeCallback {
     public void onSelfFreeze();
diff --git a/tot/base/android/java/src/org/chromium/base/metrics/CachingUmaRecorder.java b/tot/base/android/java/src/org/chromium/base/metrics/CachingUmaRecorder.java
index 9343cde..fd33870 100644
--- a/tot/base/android/java/src/org/chromium/base/metrics/CachingUmaRecorder.java
+++ b/tot/base/android/java/src/org/chromium/base/metrics/CachingUmaRecorder.java
@@ -7,12 +7,13 @@
 import android.annotation.SuppressLint;
 
 import androidx.annotation.IntDef;
-import androidx.annotation.Nullable;
 import androidx.annotation.VisibleForTesting;
 
 import org.chromium.base.Callback;
 import org.chromium.base.Log;
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -31,7 +32,8 @@
  * Stores metrics until given an {@link UmaRecorder} to forward the samples to. After flushing, no
  * longer stores metrics, instead immediately forwards them to the given {@link UmaRecorder}.
  */
-/* package */ final class CachingUmaRecorder implements UmaRecorder {
+/* package */ @NullMarked
+final class CachingUmaRecorder implements UmaRecorder {
     private static final String TAG = "CachingUmaRecorder";
 
     /**
@@ -240,12 +242,10 @@
      * The read lock must be held while invoking methods on {@code mDelegate}.
      */
     @GuardedBy("mRwLock")
-    @Nullable
-    private UmaRecorder mDelegate;
+    private @Nullable UmaRecorder mDelegate;
 
     @GuardedBy("mRwLock")
-    @Nullable
-    private List<Callback<String>> mUserActionCallbacksForTesting;
+    private @Nullable List<Callback<String>> mUserActionCallbacksForTesting;
 
     /**
      * Sets the current delegate to {@code recorder}. Forwards and clears all cached metrics if
@@ -254,7 +254,7 @@
      * @param recorder new delegate.
      * @return the previous delegate.
      */
-    public UmaRecorder setDelegate(@Nullable final UmaRecorder recorder) {
+    public @Nullable UmaRecorder setDelegate(@Nullable final UmaRecorder recorder) {
         UmaRecorder previous;
         Map<String, Histogram> histogramCache = null;
         int droppedHistogramSampleCount = 0;
diff --git a/tot/base/android/java/src/org/chromium/base/metrics/HistogramBucket.java b/tot/base/android/java/src/org/chromium/base/metrics/HistogramBucket.java
index 2f9aab6..b942684 100644
--- a/tot/base/android/java/src/org/chromium/base/metrics/HistogramBucket.java
+++ b/tot/base/android/java/src/org/chromium/base/metrics/HistogramBucket.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base.metrics;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Represents one single bucket of a histogram, with the count of records in that bucket. */
+@NullMarked
 public class HistogramBucket {
     public final int mMin;
     public final long mMax;
diff --git a/tot/base/android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java b/tot/base/android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java
index 88d3888..389f55d 100644
--- a/tot/base/android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java
+++ b/tot/base/android/java/src/org/chromium/base/metrics/NativeUmaRecorder.java
@@ -10,6 +10,8 @@
 
 import org.chromium.base.Callback;
 import org.chromium.base.TimeUtils;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -23,6 +25,7 @@
  * Note: the JNI calls are relatively costly - avoid calling these methods in performance-critical
  * code.
  */
+@NullMarked
 @JNINamespace("base::android")
 /* package */ final class NativeUmaRecorder implements UmaRecorder {
     /**
@@ -34,7 +37,7 @@
     private final Map<String, Long> mNativeHints =
             Collections.synchronizedMap(new HashMap<String, Long>());
 
-    private Map<Callback<String>, Long> mUserActionTestingCallbackNativePtrs;
+    private @Nullable Map<Callback<String>, Long> mUserActionTestingCallbackNativePtrs;
 
     @Override
     public void recordBooleanHistogram(String name, boolean sample) {
@@ -144,15 +147,27 @@
     /** Natives API to record metrics. */
     @NativeMethods
     public interface Natives {
-        long recordBooleanHistogram(String name, long nativeHint, boolean sample);
+        long recordBooleanHistogram(
+                @JniType("std::string") String name, long nativeHint, boolean sample);
 
         long recordExponentialHistogram(
-                String name, long nativeHint, int sample, int min, int max, int numBuckets);
+                @JniType("std::string") String name,
+                long nativeHint,
+                int sample,
+                int min,
+                int max,
+                int numBuckets);
 
         long recordLinearHistogram(
-                String name, long nativeHint, int sample, int min, int max, int numBuckets);
+                @JniType("std::string") String name,
+                long nativeHint,
+                int sample,
+                int min,
+                int max,
+                int numBuckets);
 
-        long recordSparseHistogram(String name, long nativeHint, int sample);
+        long recordSparseHistogram(
+                @JniType("std::string") String name, long nativeHint, int sample);
 
         /**
          * Records that the user performed an action. See {@code base::RecordComputedActionAt}.
diff --git a/tot/base/android/java/src/org/chromium/base/metrics/NoopUmaRecorder.java b/tot/base/android/java/src/org/chromium/base/metrics/NoopUmaRecorder.java
index 78340cd..d7f64bc 100644
--- a/tot/base/android/java/src/org/chromium/base/metrics/NoopUmaRecorder.java
+++ b/tot/base/android/java/src/org/chromium/base/metrics/NoopUmaRecorder.java
@@ -5,12 +5,14 @@
 package org.chromium.base.metrics;
 
 import org.chromium.base.Callback;
+import org.chromium.build.annotations.NullMarked;
 
 import java.util.Collections;
 import java.util.List;
 
 /** An empty implementation of {@link UmaRecorder}. */
-/* package */ class NoopUmaRecorder implements UmaRecorder {
+/* package */ @NullMarked
+class NoopUmaRecorder implements UmaRecorder {
     @Override
     public void recordBooleanHistogram(String name, boolean sample) {}
 
diff --git a/tot/base/android/java/src/org/chromium/base/metrics/RecordHistogram.java b/tot/base/android/java/src/org/chromium/base/metrics/RecordHistogram.java
index 41ba92e..189d601 100644
--- a/tot/base/android/java/src/org/chromium/base/metrics/RecordHistogram.java
+++ b/tot/base/android/java/src/org/chromium/base/metrics/RecordHistogram.java
@@ -6,11 +6,14 @@
 
 import android.text.format.DateUtils;
 
+import org.chromium.build.annotations.NullMarked;
+
 import java.util.List;
 
 /**
  * Java API for recording UMA histograms.
  * */
+@NullMarked
 public class RecordHistogram {
     /**
      * Records a sample in a boolean UMA histogram of the given name. Boolean histogram has two
@@ -31,10 +34,12 @@
      *
      * @param name name of the histogram
      * @param sample sample to be recorded, at least 0 and at most {@code max-1}
-     * @param max upper bound for legal sample values - all sample values have to be strictly
-     *            lower than {@code max}
+     * @param max upper bound for legal sample values - all sample values have to be
+     *            lower than or equal to {@code max}. This value should be 1000 or less.
      */
     public static void recordEnumeratedHistogram(String name, int sample, int max) {
+        // While recordExactLinearHistogram’s documentation states that the third argument
+        // should be 100 or less, a value up to 1000 is actually accepted.
         recordExactLinearHistogram(name, sample, max);
     }
 
diff --git a/tot/base/android/java/src/org/chromium/base/metrics/RecordUserAction.java b/tot/base/android/java/src/org/chromium/base/metrics/RecordUserAction.java
index c0a8b80..3e8e8ba 100644
--- a/tot/base/android/java/src/org/chromium/base/metrics/RecordUserAction.java
+++ b/tot/base/android/java/src/org/chromium/base/metrics/RecordUserAction.java
@@ -5,6 +5,7 @@
 package org.chromium.base.metrics;
 
 import org.chromium.base.TimeUtils;
+import org.chromium.build.annotations.NullMarked;
 
 /**
  * Java API for recording UMA actions.
@@ -16,6 +17,7 @@
  * We use a script ({@code extract_actions.py{}) to scan the source code and extract actions. A
  * string literal (not a variable) must be passed to {@link #record(String)}.
  */
+@NullMarked
 public class RecordUserAction {
     /**
      * Similar to {@code base::RecordAction()} in C++.
diff --git a/tot/base/android/java/src/org/chromium/base/metrics/ScopedSysTraceEvent.java b/tot/base/android/java/src/org/chromium/base/metrics/ScopedSysTraceEvent.java
index 8b3b746..ad81842 100644
--- a/tot/base/android/java/src/org/chromium/base/metrics/ScopedSysTraceEvent.java
+++ b/tot/base/android/java/src/org/chromium/base/metrics/ScopedSysTraceEvent.java
@@ -6,6 +6,8 @@
 
 import android.os.Trace;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
  * An alternative to @{TraceEvent} that allows us to trace events before native initialization.
  *
@@ -13,6 +15,7 @@
  * directly purges to the kernel debug message but that method does not allow tracing events to be
  * written *after* the event occurrence.
  */
+@NullMarked
 public class ScopedSysTraceEvent implements AutoCloseable {
     /** The maximum length of a section name. Longer names will be truncated. */
     // From:
diff --git a/tot/base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java b/tot/base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java
index ac867ee..9ed8c53 100644
--- a/tot/base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java
+++ b/tot/base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java
@@ -8,7 +8,10 @@
 import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Java API which exposes the registered histograms on the native side as JSON test. */
+@NullMarked
 @JNINamespace("base::android")
 public final class StatisticsRecorderAndroid {
     private StatisticsRecorderAndroid() {}
diff --git a/tot/base/android/java/src/org/chromium/base/metrics/TimingMetric.java b/tot/base/android/java/src/org/chromium/base/metrics/TimingMetric.java
index 97ac4f1..79242a1 100644
--- a/tot/base/android/java/src/org/chromium/base/metrics/TimingMetric.java
+++ b/tot/base/android/java/src/org/chromium/base/metrics/TimingMetric.java
@@ -5,9 +5,9 @@
 package org.chromium.base.metrics;
 
 import androidx.annotation.IntDef;
-import androidx.annotation.NonNull;
 
 import org.chromium.base.TimeUtils;
+import org.chromium.build.annotations.NullMarked;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -17,6 +17,7 @@
  * block. Measures time elapsed between instantiation and the call to close using supplied time
  * source.
  */
+@NullMarked
 public class TimingMetric implements AutoCloseable {
     @IntDef({TimerType.SHORT_UPTIME, TimerType.MEDIUM_UPTIME, TimerType.SHORT_THREAD_TIME})
     @Retention(RetentionPolicy.SOURCE)
@@ -36,7 +37,7 @@
      *
      * @param metricName The name of the histogram to record.
      */
-    public static TimingMetric shortUptime(@NonNull String metricName) {
+    public static TimingMetric shortUptime(String metricName) {
         TimingMetric ret = new TimingMetric(metricName, TimerType.SHORT_UPTIME);
         ret.mStartTime = TimeUtils.uptimeMillis();
         return ret;
@@ -48,7 +49,7 @@
      *
      * @param metricName The name of the histogram to record.
      */
-    public static TimingMetric mediumUptime(@NonNull String metricName) {
+    public static TimingMetric mediumUptime(String metricName) {
         TimingMetric ret = new TimingMetric(metricName, TimerType.MEDIUM_UPTIME);
         ret.mStartTime = TimeUtils.uptimeMillis();
         return ret;
@@ -60,7 +61,7 @@
      *
      * @param metricName The name of the histogram to record.
      */
-    public static TimingMetric shortThreadTime(@NonNull String metricName) {
+    public static TimingMetric shortThreadTime(String metricName) {
         TimingMetric ret = new TimingMetric(metricName, TimerType.SHORT_THREAD_TIME);
         ret.mStartTime = TimeUtils.currentThreadTimeMillis();
         return ret;
diff --git a/tot/base/android/java/src/org/chromium/base/metrics/UmaRecorder.java b/tot/base/android/java/src/org/chromium/base/metrics/UmaRecorder.java
index 369b312..80d3c4e 100644
--- a/tot/base/android/java/src/org/chromium/base/metrics/UmaRecorder.java
+++ b/tot/base/android/java/src/org/chromium/base/metrics/UmaRecorder.java
@@ -7,10 +7,12 @@
 import com.google.errorprone.annotations.DoNotMock;
 
 import org.chromium.base.Callback;
+import org.chromium.build.annotations.NullMarked;
 
 import java.util.List;
 
 /** Common interface for code recording UMA metrics. */
+@NullMarked
 @DoNotMock("Use HistogramWatcher for histograms or UserActionTester for user actions instead.")
 public interface UmaRecorder {
     /** Records a single sample of a boolean histogram. */
diff --git a/tot/base/android/java/src/org/chromium/base/metrics/UmaRecorderHolder.java b/tot/base/android/java/src/org/chromium/base/metrics/UmaRecorderHolder.java
index b938fbe..ef8ece0 100644
--- a/tot/base/android/java/src/org/chromium/base/metrics/UmaRecorderHolder.java
+++ b/tot/base/android/java/src/org/chromium/base/metrics/UmaRecorderHolder.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base.metrics;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Holds the {@link CachingUmaRecorder} used by {@link RecordHistogram}. */
+@NullMarked
 public class UmaRecorderHolder {
     private UmaRecorderHolder() {}
 
diff --git a/tot/base/android/java/src/org/chromium/base/process_launcher/BindService.java b/tot/base/android/java/src/org/chromium/base/process_launcher/BindService.java
index d5ff40b..c002b23 100644
--- a/tot/base/android/java/src/org/chromium/base/process_launcher/BindService.java
+++ b/tot/base/android/java/src/org/chromium/base/process_launcher/BindService.java
@@ -17,13 +17,16 @@
 import androidx.annotation.RequiresApi;
 
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.lang.reflect.Method;
 import java.util.concurrent.Executor;
 
 /** Class of static helper methods to call Context.bindService variants. */
+@NullMarked
 final class BindService {
-    private static Method sBindServiceAsUserMethod;
+    private static @Nullable Method sBindServiceAsUserMethod;
 
     static boolean supportVariableConnections() {
         return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
@@ -39,7 +42,7 @@
             int flags,
             Handler handler,
             Executor executor,
-            String instanceName) {
+            @Nullable String instanceName) {
         if (supportVariableConnections() && instanceName != null) {
             return context.bindIsolatedService(intent, flags, instanceName, executor, connection);
         }
diff --git a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildConnectionAllocator.java b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildConnectionAllocator.java
index 6dfab33..7b75eea 100644
--- a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildConnectionAllocator.java
+++ b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildConnectionAllocator.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base.process_launcher;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
@@ -24,17 +26,21 @@
 import org.chromium.base.PackageUtils;
 import org.chromium.base.ResettersForTesting;
 import org.chromium.base.SysUtils;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.ArrayDeque;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
 import java.util.Queue;
 
 /**
- * This class is responsible for allocating and managing connections to child
- * process services. These connections are in a pool (the services are defined
- * in the AndroidManifest.xml).
+ * This class is responsible for allocating and managing connections to child process services.
+ * These connections are in a pool (the services are defined in the AndroidManifest.xml).
  */
+@NullMarked
 public abstract class ChildConnectionAllocator {
     private static final String TAG = "ChildConnAllocator";
     private static final String ZYGOTE_SUFFIX = "0";
@@ -46,11 +52,13 @@
         ChildProcessConnection createConnection(
                 Context context,
                 ComponentName serviceName,
-                ComponentName fallbackServiceName,
+                @Nullable ComponentName fallbackServiceName,
                 boolean bindToCaller,
                 boolean bindAsExternalService,
                 Bundle serviceBundle,
-                String instanceName);
+                @Nullable String instanceName,
+                boolean independentFallback,
+                boolean isSandboxedForHistograms);
     }
 
     /** Default implementation of the ConnectionFactory that creates actual connections. */
@@ -59,11 +67,13 @@
         public ChildProcessConnection createConnection(
                 Context context,
                 ComponentName serviceName,
-                ComponentName fallbackServiceName,
+                @Nullable ComponentName fallbackServiceName,
                 boolean bindToCaller,
                 boolean bindAsExternalService,
                 Bundle serviceBundle,
-                String instanceName) {
+                @Nullable String instanceName,
+                boolean independentFallback,
+                boolean isSandboxedForHistograms) {
             return new ChildProcessConnection(
                     context,
                     serviceName,
@@ -71,7 +81,9 @@
                     bindToCaller,
                     bindAsExternalService,
                     serviceBundle,
-                    instanceName);
+                    instanceName,
+                    independentFallback,
+                    isSandboxedForHistograms);
         }
     }
 
@@ -85,7 +97,7 @@
 
     // Runnable which will be called when allocator wants to allocate a new connection, but does
     // not have any more free slots. May be null.
-    private final Runnable mFreeSlotCallback;
+    private final @Nullable Runnable mFreeSlotCallback;
 
     private final Queue<Runnable> mPendingAllocations = new ArrayDeque<>();
 
@@ -94,10 +106,12 @@
 
     /* package */ final String mPackageName;
     /* package */ final String mServiceClassName;
-    /* package */ final String mFallbackServiceClassName;
+    /* package */ final @Nullable String mFallbackServiceClassName;
     /* package */ final boolean mBindToCaller;
     /* package */ final boolean mBindAsExternalService;
     /* package */ final boolean mUseStrongBinding;
+    // This has no functional change and is used only for logging histograms.
+    /* package */ final boolean mIsSandboxedForHistograms;
 
     /* package */ ConnectionFactory mConnectionFactory = new ConnectionFactoryImpl();
 
@@ -127,13 +141,15 @@
     public static ChildConnectionAllocator create(
             Context context,
             Handler launcherHandler,
-            Runnable freeSlotCallback,
+            @Nullable Runnable freeSlotCallback,
             String packageName,
             String serviceClassName,
             String numChildServicesManifestKey,
             boolean bindToCaller,
             boolean bindAsExternalService,
-            boolean useStrongBinding) {
+            boolean useStrongBinding,
+            boolean fallbackToNextSlot,
+            boolean isSandboxedForHistograms) {
         int numServices = -1;
         PackageManager packageManager = context.getPackageManager();
         try {
@@ -160,7 +176,9 @@
                 bindToCaller,
                 bindAsExternalService,
                 useStrongBinding,
-                numServices);
+                fallbackToNextSlot,
+                numServices,
+                isSandboxedForHistograms);
     }
 
     public static ChildConnectionAllocator createVariableSize(
@@ -171,7 +189,8 @@
             String serviceClassName,
             boolean bindToCaller,
             boolean bindAsExternalService,
-            boolean useStrongBinding) {
+            boolean useStrongBinding,
+            boolean isSandboxedForHistograms) {
         checkServiceExists(context, packageName, serviceClassName);
 
         // OnePlus devices are having trouble with app zygote in combination with dynamic
@@ -195,7 +214,8 @@
                         bindToCaller,
                         bindAsExternalService,
                         useStrongBinding,
-                        MAX_VARIABLE_ALLOCATED);
+                        MAX_VARIABLE_ALLOCATED,
+                        isSandboxedForHistograms);
             }
         }
         // On low end devices, we do not expect to have many renderers. As a consequence, the fixed
@@ -214,7 +234,8 @@
                 bindToCaller,
                 bindAsExternalService,
                 useStrongBinding,
-                MAX_VARIABLE_ALLOCATED);
+                MAX_VARIABLE_ALLOCATED,
+                isSandboxedForHistograms);
     }
 
     /**
@@ -222,13 +243,15 @@
      * instead of being retrieved from the AndroidManifest.xml.
      */
     public static FixedSizeAllocatorImpl createFixedForTesting(
-            Runnable freeSlotCallback,
+            @Nullable Runnable freeSlotCallback,
             String packageName,
             String serviceClassName,
             int serviceCount,
             boolean bindToCaller,
             boolean bindAsExternalService,
-            boolean useStrongBinding) {
+            boolean useStrongBinding,
+            boolean fallbackToNextSlot,
+            boolean isSandboxedForHistograms) {
         return new FixedSizeAllocatorImpl(
                 new Handler(),
                 freeSlotCallback,
@@ -237,13 +260,15 @@
                 bindToCaller,
                 bindAsExternalService,
                 useStrongBinding,
-                serviceCount);
+                fallbackToNextSlot,
+                serviceCount,
+                isSandboxedForHistograms);
     }
 
     public static VariableSizeAllocatorImpl createVariableSizeForTesting(
             Handler launcherHandler,
             String packageName,
-            Runnable freeSlotCallback,
+            @Nullable Runnable freeSlotCallback,
             String serviceClassName,
             boolean bindToCaller,
             boolean bindAsExternalService,
@@ -258,13 +283,14 @@
                 bindToCaller,
                 bindAsExternalService,
                 useStrongBinding,
-                maxAllocated);
+                maxAllocated,
+                /* isSandboxedForHistograms= */ false);
     }
 
     public static Android10WorkaroundAllocatorImpl createWorkaroundForTesting(
             Handler launcherHandler,
             String packageName,
-            Runnable freeSlotCallback,
+            @Nullable Runnable freeSlotCallback,
             String serviceClassName,
             boolean bindToCaller,
             boolean bindAsExternalService,
@@ -278,18 +304,20 @@
                 bindToCaller,
                 bindAsExternalService,
                 useStrongBinding,
-                maxAllocated);
+                maxAllocated,
+                /* isSandboxedForHistograms= */ false);
     }
 
     private ChildConnectionAllocator(
             Handler launcherHandler,
-            Runnable freeSlotCallback,
+            @Nullable Runnable freeSlotCallback,
             String packageName,
             String serviceClassName,
-            String fallbackServiceClassName,
+            @Nullable String fallbackServiceClassName,
             boolean bindToCaller,
             boolean bindAsExternalService,
-            boolean useStrongBinding) {
+            boolean useStrongBinding,
+            boolean isSandboxedForHistograms) {
         mLauncherHandler = launcherHandler;
         assert isRunningOnLauncherThread();
         mFreeSlotCallback = freeSlotCallback;
@@ -299,12 +327,13 @@
         mBindToCaller = bindToCaller;
         mBindAsExternalService = bindAsExternalService;
         mUseStrongBinding = useStrongBinding;
+        mIsSandboxedForHistograms = isSandboxedForHistograms;
     }
 
     /**
      * @return a bound connection, or null if there are no free slots.
      */
-    public ChildProcessConnection allocate(
+    public @Nullable ChildProcessConnection allocate(
             Context context,
             Bundle serviceBundle,
             final ChildProcessConnection.ServiceCallback serviceCallback) {
@@ -402,7 +431,7 @@
     }
 
     /** May return -1 if size is not fixed. */
-    public abstract int getNumberOfServices();
+    public abstract int getMaxNumberOfAllocations();
 
     @VisibleForTesting
     public abstract boolean anyConnectionAllocated();
@@ -420,7 +449,7 @@
         return mLauncherHandler.getLooper() == Looper.myLooper();
     }
 
-    /* package */ abstract ChildProcessConnection doAllocate(
+    /* package */ abstract @Nullable ChildProcessConnection doAllocate(
             Context context,
             Bundle serviceBundle,
             ChildProcessConnection.ServiceCallback serviceCallback);
@@ -431,20 +460,24 @@
     @VisibleForTesting
     public static class FixedSizeAllocatorImpl extends ChildConnectionAllocator {
         // Connections to services. Indices of the array correspond to the service numbers.
-        private final ChildProcessConnection[] mChildProcessConnections;
+        private final @Nullable ChildProcessConnection[] mChildProcessConnections;
 
         // The list of free (not bound) service indices.
         private final ArrayList<Integer> mFreeConnectionIndices;
 
+        private final @Nullable Map<ChildProcessConnection, Integer> mFallbackSlots;
+
         private FixedSizeAllocatorImpl(
                 Handler launcherHandler,
-                Runnable freeSlotCallback,
+                @Nullable Runnable freeSlotCallback,
                 String packageName,
                 String serviceClassName,
                 boolean bindToCaller,
                 boolean bindAsExternalService,
                 boolean useStrongBinding,
-                int numChildServices) {
+                boolean fallbackToNextSlot,
+                int numChildServices,
+                boolean isSandboxedForHistograms) {
             super(
                     launcherHandler,
                     freeSlotCallback,
@@ -453,7 +486,8 @@
                     null,
                     bindToCaller,
                     bindAsExternalService,
-                    useStrongBinding);
+                    useStrongBinding,
+                    isSandboxedForHistograms);
 
             mChildProcessConnections = new ChildProcessConnection[numChildServices];
 
@@ -461,10 +495,17 @@
             for (int i = 0; i < numChildServices; i++) {
                 mFreeConnectionIndices.add(i);
             }
+
+            if (fallbackToNextSlot) {
+                mFallbackSlots = new HashMap<>();
+            } else {
+                mFallbackSlots = null;
+            }
         }
 
         @Override
-        /* package */ ChildProcessConnection doAllocate(
+        /* package */ @Nullable
+        ChildProcessConnection doAllocate(
                 Context context,
                 Bundle serviceBundle,
                 ChildProcessConnection.ServiceCallback serviceCallback) {
@@ -472,10 +513,20 @@
                 Log.w(TAG, "Ran out of services to allocate.");
                 return null;
             }
+            if (mFallbackSlots != null && mFreeConnectionIndices.size() < 2) {
+                Log.w(TAG, "Ran out of services for fallback.");
+                return null;
+            }
             int slot = mFreeConnectionIndices.remove(0);
             assert mChildProcessConnections[slot] == null;
             ComponentName serviceName = new ComponentName(mPackageName, mServiceClassName + slot);
+            int fallbackSlot = -1;
             ComponentName fallbackServiceName = null;
+            if (mFallbackSlots != null) {
+                fallbackSlot = mFreeConnectionIndices.remove(0);
+                fallbackServiceName =
+                        new ComponentName(mPackageName, mServiceClassName + fallbackSlot);
+            }
 
             ChildProcessConnection connection =
                     mConnectionFactory.createConnection(
@@ -485,13 +536,19 @@
                             mBindToCaller,
                             mBindAsExternalService,
                             serviceBundle,
-                            /* instanceName= */ null);
+                            /* instanceName= */ null,
+                            /* independentFallback= */ true,
+                            mIsSandboxedForHistograms);
             mChildProcessConnections[slot] = connection;
+            if (mFallbackSlots != null) {
+                mFallbackSlots.put(connection, fallbackSlot);
+            }
             Log.d(
                     TAG,
-                    "Allocator allocated and bound a connection, name: %s, slot: %d",
+                    "Allocator allocated and bound a connection, name: %s, slot: %d fallback:%d",
                     mServiceClassName,
-                    slot);
+                    slot,
+                    fallbackSlot);
             connection.start(mUseStrongBinding, serviceCallback);
             return connection;
         }
@@ -508,11 +565,19 @@
                 mChildProcessConnections[slot] = null;
                 assert !mFreeConnectionIndices.contains(slot);
                 mFreeConnectionIndices.add(slot);
+
+                int fallbackSlot = -1;
+                if (mFallbackSlots != null) {
+                    fallbackSlot = assumeNonNull(mFallbackSlots.remove(connection));
+                    assert !mFreeConnectionIndices.contains(fallbackSlot);
+                    mFreeConnectionIndices.add(fallbackSlot);
+                }
                 Log.d(
                         TAG,
-                        "Allocator freed a connection, name: %s, slot: %d",
+                        "Allocator freed a connection, name: %s, slot: %d fallback:%d",
                         mServiceClassName,
-                        slot);
+                        slot,
+                        fallbackSlot);
             }
         }
 
@@ -522,16 +587,25 @@
         }
 
         @Override
-        public int getNumberOfServices() {
-            return mChildProcessConnections.length;
+        public int getMaxNumberOfAllocations() {
+            if (mFallbackSlots != null) {
+                return mChildProcessConnections.length / 2;
+            } else {
+                return mChildProcessConnections.length;
+            }
         }
 
         @Override
         public int allocatedConnectionsCountForTesting() {
-            return mChildProcessConnections.length - mFreeConnectionIndices.size();
+            if (mFallbackSlots != null) {
+                return (mChildProcessConnections.length - mFreeConnectionIndices.size()) / 2;
+            } else {
+                return mChildProcessConnections.length - mFreeConnectionIndices.size();
+            }
         }
 
-        public ChildProcessConnection getChildProcessConnectionAtSlotForTesting(int slotNumber) {
+        public @Nullable ChildProcessConnection getChildProcessConnectionAtSlotForTesting(
+                int slotNumber) {
             return mChildProcessConnections[slotNumber];
         }
 
@@ -550,14 +624,15 @@
         // Note |serviceClassName| includes the service suffix.
         private VariableSizeAllocatorImpl(
                 Handler launcherHandler,
-                Runnable freeSlotCallback,
+                @Nullable Runnable freeSlotCallback,
                 String packageName,
                 String serviceClassName,
-                String fallbackServiceClassName,
+                @Nullable String fallbackServiceClassName,
                 boolean bindToCaller,
                 boolean bindAsExternalService,
                 boolean useStrongBinding,
-                int maxAllocated) {
+                int maxAllocated,
+                boolean isSandboxedForHistograms) {
             super(
                     launcherHandler,
                     freeSlotCallback,
@@ -566,13 +641,15 @@
                     fallbackServiceClassName,
                     bindToCaller,
                     bindAsExternalService,
-                    useStrongBinding);
+                    useStrongBinding,
+                    isSandboxedForHistograms);
             assert maxAllocated > 0;
             mMaxAllocated = maxAllocated;
         }
 
         @Override
-        /* package */ ChildProcessConnection doAllocate(
+        /* package */ @Nullable
+        ChildProcessConnection doAllocate(
                 Context context,
                 Bundle serviceBundle,
                 ChildProcessConnection.ServiceCallback serviceCallback) {
@@ -583,7 +660,8 @@
             return connection;
         }
 
-        /* package */ ChildProcessConnection tryAllocate(
+        /* package */ @Nullable
+        ChildProcessConnection tryAllocate(
                 Context context,
                 Bundle serviceBundle,
                 ChildProcessConnection.ServiceCallback serviceCallback) {
@@ -595,7 +673,7 @@
             return connection;
         }
 
-        private ChildProcessConnection allocate(Context context, Bundle serviceBundle) {
+        private @Nullable ChildProcessConnection allocate(Context context, Bundle serviceBundle) {
             if (mAllocatedConnections.size() >= mMaxAllocated) {
                 Log.w(TAG, "Ran out of UIDs to allocate.");
                 return null;
@@ -615,7 +693,9 @@
                             mBindToCaller,
                             mBindAsExternalService,
                             serviceBundle,
-                            instanceName);
+                            instanceName,
+                            /* independentFallback= */ false,
+                            mIsSandboxedForHistograms);
             assert connection != null;
             return connection;
         }
@@ -631,7 +711,7 @@
         }
 
         @Override
-        public int getNumberOfServices() {
+        public int getMaxNumberOfAllocations() {
             return -1;
         }
 
@@ -662,13 +742,14 @@
 
         private Android10WorkaroundAllocatorImpl(
                 Handler launcherHandler,
-                Runnable freeSlotCallback,
+                @Nullable Runnable freeSlotCallback,
                 String packageName,
                 String serviceClassName,
                 boolean bindToCaller,
                 boolean bindAsExternalService,
                 boolean useStrongBinding,
-                int maxAllocated) {
+                int maxAllocated,
+                boolean isSandboxedForHistograms) {
             super(
                     launcherHandler,
                     freeSlotCallback,
@@ -677,7 +758,8 @@
                     null,
                     bindToCaller,
                     bindAsExternalService,
-                    useStrongBinding);
+                    useStrongBinding,
+                    isSandboxedForHistograms);
             mZygoteAllocator =
                     new VariableSizeAllocatorImpl(
                             launcherHandler,
@@ -688,7 +770,8 @@
                             bindToCaller,
                             bindAsExternalService,
                             useStrongBinding,
-                            maxAllocated);
+                            maxAllocated,
+                            isSandboxedForHistograms);
             mNonZygoteAllocator =
                     new VariableSizeAllocatorImpl(
                             launcherHandler,
@@ -699,11 +782,13 @@
                             bindToCaller,
                             bindAsExternalService,
                             useStrongBinding,
-                            maxAllocated);
+                            maxAllocated,
+                            isSandboxedForHistograms);
         }
 
         @Override
-        /* package */ ChildProcessConnection doAllocate(
+        /* package */ @Nullable
+        ChildProcessConnection doAllocate(
                 Context context,
                 Bundle serviceBundle,
                 ChildProcessConnection.ServiceCallback serviceCallback) {
@@ -725,7 +810,7 @@
         }
 
         @Override
-        public int getNumberOfServices() {
+        public int getMaxNumberOfAllocations() {
             return -1;
         }
 
diff --git a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConnection.java b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConnection.java
index 25cb33e..4db2a0f 100644
--- a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConnection.java
+++ b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConnection.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base.process_launcher;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
@@ -16,7 +18,7 @@
 import android.os.Looper;
 import android.os.RemoteException;
 
-import androidx.annotation.Nullable;
+import androidx.annotation.IntDef;
 import androidx.annotation.VisibleForTesting;
 
 import org.chromium.base.BuildInfo;
@@ -31,7 +33,11 @@
 import org.chromium.base.memory.SelfFreezeCallback;
 import org.chromium.base.metrics.RecordHistogram;
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Objects;
@@ -40,11 +46,13 @@
 import javax.annotation.concurrent.GuardedBy;
 
 /** Manages a connection between the browser activity and a child service. */
+@NullMarked
 public class ChildProcessConnection {
     private static final String TAG = "ChildProcessConn";
     private static final int FALLBACK_TIMEOUT_IN_SECONDS = 10;
     private static final boolean SUPPORT_NOT_PERCEPTIBLE_BINDING =
             Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
+    private static final String HISTOGRAM_NAME = "Android.ChildProcessConectionEventCounts";
 
     /**
      * Used to notify the consumer about the process start. These callbacks will be invoked before
@@ -76,9 +84,10 @@
     public interface ConnectionCallback {
         /**
          * Called when the connection to the service is established.
+         *
          * @param connection the connection object to the child process
          */
-        void onConnected(ChildProcessConnection connection);
+        void onConnected(@Nullable ChildProcessConnection connection);
     }
 
     /**
@@ -100,6 +109,24 @@
         void onReceivedZygoteInfo(ChildProcessConnection connection, Bundle relroBundle);
     }
 
+    // These values are persisted to logs. Entries should not be renumbered and numeric values
+    // should never be reused.
+    @IntDef({
+        EventsEnum.SCHEDULE_TIMEOUT_SANDBOXED,
+        EventsEnum.SCHEDULE_TIMEOUT_UNSANDBOXED,
+        EventsEnum.FALLBACK_ON_TIMEOUT_SANDBOXED,
+        EventsEnum.FALLBACK_ON_TIMEOUT_UNSANDBOXED,
+        EventsEnum.COUNT
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    private @interface EventsEnum {
+        int SCHEDULE_TIMEOUT_SANDBOXED = 0;
+        int SCHEDULE_TIMEOUT_UNSANDBOXED = 1;
+        int FALLBACK_ON_TIMEOUT_SANDBOXED = 2;
+        int FALLBACK_ON_TIMEOUT_UNSANDBOXED = 3;
+        int COUNT = 4;
+    }
+
     private static class ChildProcessMismatchException extends RuntimeException {
         ChildProcessMismatchException(String msg) {
             super(msg);
@@ -141,7 +168,7 @@
     private final Handler mLauncherHandler;
     private final Executor mLauncherExecutor;
     private ComponentName mServiceName;
-    private final ComponentName mFallbackServiceName;
+    private final @Nullable ComponentName mFallbackServiceName;
 
     // Parameters passed to the child process through the service binding intent.
     // If the service gets recreated by the framework the intent will be reused, so these parameters
@@ -154,11 +181,13 @@
 
     private static class ConnectionParams {
         final Bundle mConnectionBundle;
-        final List<IBinder> mClientInterfaces;
-        final IBinder mBinderBox;
+        final @Nullable List<IBinder> mClientInterfaces;
+        final @Nullable IBinder mBinderBox;
 
         ConnectionParams(
-                Bundle connectionBundle, List<IBinder> clientInterfaces, IBinder binderBox) {
+                Bundle connectionBundle,
+                @Nullable List<IBinder> clientInterfaces,
+                @Nullable IBinder binderBox) {
             mConnectionBundle = connectionBundle;
             mClientInterfaces = clientInterfaces;
             mBinderBox = binderBox;
@@ -166,22 +195,22 @@
     }
 
     // This is set in start() and is used in onServiceConnected().
-    private ServiceCallback mServiceCallback;
+    private @Nullable ServiceCallback mServiceCallback;
 
     // This is set in setupConnection() and is later used in doConnectionSetup(), after which the
     // variable is cleared. Therefore this is only valid while the connection is being set up.
-    private ConnectionParams mConnectionParams;
+    private @Nullable ConnectionParams mConnectionParams;
 
     // Callback provided in setupConnection() that will communicate the result to the caller. This
     // has to be called exactly once after setupConnection(), even if setup fails, so that the
     // caller can free up resources associated with the setup attempt. This is set to null after the
     // call.
-    private ConnectionCallback mConnectionCallback;
+    private @Nullable ConnectionCallback mConnectionCallback;
 
     // Callback provided in setupConnection().
-    private ZygoteInfoCallback mZygoteInfoCallback;
+    private @Nullable ZygoteInfoCallback mZygoteInfoCallback;
 
-    private IChildProcessService mService;
+    private @Nullable IChildProcessService mService;
 
     // Set to true when the service connection callback runs. This differs from
     // mServiceConnectComplete, which tracks that the connection completed successfully.
@@ -218,7 +247,16 @@
 
     // Instance named used on Android 10 and above to create separate instances from the same
     // <service> manifest declaration.
-    private final String mInstanceName;
+    private final @Nullable String mInstanceName;
+
+    // If true, then this connection fallbacking back does not cause other connections to fallback,
+    // and vice version; essentially ignore `sAlwaysFallback`.
+    private final boolean mIndependentFallback;
+
+    // Should not be used for any functional changes as this class should be oblivious to whether
+    // this child process is sandboxed or not. Only added here for histogram purposes since it's
+    // inconvenient to log some histogram where this information is available.
+    private final boolean mIsSandboxedForHistograms;
 
     // Use Context.BIND_EXTERNAL_SERVICE flag for this service.
     private final boolean mBindAsExternalService;
@@ -233,7 +271,7 @@
 
     // On Android Q+ a not perceptible binding will make the service priority below that of a
     // perceptible process of a backgrounded app. Only created on Android Q+.
-    private ChildServiceConnection mNotPerceptibleBinding;
+    private @Nullable ChildServiceConnection mNotPerceptibleBinding;
 
     // Low priority binding maintained in the entire lifetime of the connection, i.e. between calls
     // to start() and stop().
@@ -262,13 +300,13 @@
     @GuardedBy("mBindingStateLock")
     private boolean mKilledByUs;
 
-    private MemoryPressureCallback mMemoryPressureCallback;
-    private SelfFreezeCallback mSelfFreezeCallback;
+    private @Nullable MemoryPressureCallback mMemoryPressureCallback;
+    private @Nullable SelfFreezeCallback mSelfFreezeCallback;
 
     // If the process threw an exception before entering the main loop, the exception
     // string is reported here.
     @GuardedBy("mBindingStateLock")
-    private String mExceptionInServiceDuringInit;
+    private @Nullable String mExceptionInServiceDuringInit;
 
     // Whether the process exited cleanly or not.
     @GuardedBy("mBindingStateLock")
@@ -277,11 +315,13 @@
     public ChildProcessConnection(
             Context context,
             ComponentName serviceName,
-            ComponentName fallbackServiceName,
+            @Nullable ComponentName fallbackServiceName,
             boolean bindToCaller,
             boolean bindAsExternalService,
             Bundle serviceBundle,
-            String instanceName) {
+            @Nullable String instanceName,
+            boolean independentFallback,
+            boolean isSandboxedForHistograms) {
         this(
                 context,
                 serviceName,
@@ -290,19 +330,23 @@
                 bindAsExternalService,
                 serviceBundle,
                 /* connectionFactory= */ null,
-                instanceName);
+                instanceName,
+                independentFallback,
+                isSandboxedForHistograms);
     }
 
     @VisibleForTesting
     public ChildProcessConnection(
             final Context context,
             ComponentName serviceName,
-            ComponentName fallbackServiceName,
+            @Nullable ComponentName fallbackServiceName,
             boolean bindToCaller,
             boolean bindAsExternalService,
             Bundle serviceBundle,
-            ChildServiceConnectionFactory connectionFactory,
-            String instanceName) {
+            @Nullable ChildServiceConnectionFactory connectionFactory,
+            @Nullable String instanceName,
+            boolean independentFallback,
+            boolean isSandboxedForHistograms) {
         mLauncherHandler = new Handler();
         mLauncherExecutor =
                 (Runnable runnable) -> {
@@ -318,6 +362,8 @@
                 BuildInfo.getInstance().packageName);
         mBindToCaller = bindToCaller;
         mInstanceName = instanceName;
+        mIndependentFallback = independentFallback;
+        mIsSandboxedForHistograms = isSandboxedForHistograms;
         // Incremental install does not work with isolatedProcess, and externalService requires
         // isolatedProcess, so both need to be turned off for incremental install.
         mBindAsExternalService = bindAsExternalService && !BuildConfig.IS_INCREMENTAL_INSTALL;
@@ -329,7 +375,7 @@
                                 Intent bindIntent,
                                 int bindFlags,
                                 ChildServiceConnectionDelegate delegate,
-                                String instanceName) {
+                                @Nullable String instanceName) {
                             return new ChildServiceConnectionImpl(
                                     context,
                                     bindIntent,
@@ -368,7 +414,7 @@
                 };
 
         createBindings(
-                sAlwaysFallback && mFallbackServiceName != null
+                getAlwaysFallback() && mFallbackServiceName != null
                         ? mFallbackServiceName
                         : mServiceName);
     }
@@ -410,7 +456,7 @@
                         mInstanceName);
     }
 
-    public final IChildProcessService getService() {
+    public final @Nullable IChildProcessService getService() {
         assert isRunningOnLauncherThread();
         return mService;
     }
@@ -701,7 +747,7 @@
         s.append("bindings:");
         s.append(mWaivedBinding.isBound() ? "W" : " ");
         s.append(mVisibleBinding.isBound() ? "V" : " ");
-        s.append(supportNotPerceptibleBinding() && mNotPerceptibleBinding.isBound() ? "N" : " ");
+        s.append(mNotPerceptibleBinding != null && mNotPerceptibleBinding.isBound() ? "N" : " ");
         s.append(mStrongBinding.isBound() ? "S" : " ");
         return s.toString();
     }
@@ -830,8 +876,8 @@
         assert !mUnbound;
 
         boolean success = bindUsingExistingBindings(useStrongBinding);
-        boolean usedFallback = sAlwaysFallback && mFallbackServiceName != null;
-        boolean canFallback = !sAlwaysFallback && mFallbackServiceName != null;
+        boolean usedFallback = getAlwaysFallback() && mFallbackServiceName != null;
+        boolean canFallback = !getAlwaysFallback() && mFallbackServiceName != null;
         if (!success && !usedFallback && canFallback) {
             // Note this error condition is generally transient so `sAlwaysFallback` is
             // not set in this code path.
@@ -844,6 +890,14 @@
         if (success && !usedFallback && canFallback) {
             mLauncherHandler.postDelayed(
                     this::checkBindTimeOut, FALLBACK_TIMEOUT_IN_SECONDS * 1000);
+
+            if (mIsSandboxedForHistograms) {
+                RecordHistogram.recordEnumeratedHistogram(
+                        HISTOGRAM_NAME, EventsEnum.SCHEDULE_TIMEOUT_SANDBOXED, EventsEnum.COUNT);
+            } else {
+                RecordHistogram.recordEnumeratedHistogram(
+                        HISTOGRAM_NAME, EventsEnum.SCHEDULE_TIMEOUT_UNSANDBOXED, EventsEnum.COUNT);
+            }
         }
 
         return success;
@@ -883,8 +937,17 @@
         if (mUnbound) {
             return;
         }
-        sAlwaysFallback = true;
+        if (!mIndependentFallback) {
+            sAlwaysFallback = true;
+        }
         retireBindingsAndBindFallback();
+        if (mIsSandboxedForHistograms) {
+            RecordHistogram.recordEnumeratedHistogram(
+                    HISTOGRAM_NAME, EventsEnum.FALLBACK_ON_TIMEOUT_SANDBOXED, EventsEnum.COUNT);
+        } else {
+            RecordHistogram.recordEnumeratedHistogram(
+                    HISTOGRAM_NAME, EventsEnum.FALLBACK_ON_TIMEOUT_UNSANDBOXED, EventsEnum.COUNT);
+        }
     }
 
     private boolean retireBindingsAndBindFallback() {
@@ -892,7 +955,7 @@
         boolean isStrongBindingBound = mStrongBinding.isBound();
         boolean isVisibleBindingBound = mVisibleBinding.isBound();
         boolean isNotPerceptibleBindingBound =
-                supportNotPerceptibleBinding() && mNotPerceptibleBinding.isBound();
+                mNotPerceptibleBinding != null && mNotPerceptibleBinding.isBound();
         boolean isWaivedBindingBound = mWaivedBinding.isBound();
         retireAndCreateFallbackBindings();
         // Expect all bindings to succeed or fail together. So early out as soon as
@@ -908,7 +971,7 @@
             }
         }
         if (isNotPerceptibleBindingBound) {
-            if (!mNotPerceptibleBinding.bindServiceConnection()) {
+            if (!assumeNonNull(mNotPerceptibleBinding).bindServiceConnection()) {
                 return false;
             }
         }
@@ -925,7 +988,7 @@
         Log.w(TAG, "Fallback to %s", mFallbackServiceName);
         mStrongBinding.retire();
         mVisibleBinding.retire();
-        if (supportNotPerceptibleBinding()) {
+        if (mNotPerceptibleBinding != null) {
             mNotPerceptibleBinding.retire();
         }
         mWaivedBinding.retire();
@@ -940,7 +1003,7 @@
         mUnbound = true;
         mStrongBinding.unbindServiceConnection();
         mWaivedBinding.unbindServiceConnection();
-        if (supportNotPerceptibleBinding()) {
+        if (mNotPerceptibleBinding != null) {
             mNotPerceptibleBinding.unbindServiceConnection();
         }
         mVisibleBinding.unbindServiceConnection();
@@ -1050,7 +1113,7 @@
 
     public boolean isNotPerceptibleBindingBound() {
         assert isRunningOnLauncherThread();
-        return supportNotPerceptibleBinding() && mNotPerceptibleBinding.isBound();
+        return mNotPerceptibleBinding != null && mNotPerceptibleBinding.isBound();
     }
 
     public int getNotPerceptibleBindingCount() {
@@ -1066,7 +1129,7 @@
             return;
         }
         if (mNotPerceptibleBindingCount == 0) {
-            mNotPerceptibleBinding.bindServiceConnection();
+            assumeNonNull(mNotPerceptibleBinding).bindServiceConnection();
             updateBindingState();
         }
         mNotPerceptibleBindingCount++;
@@ -1081,7 +1144,7 @@
         assert mNotPerceptibleBindingCount > 0;
         mNotPerceptibleBindingCount--;
         if (mNotPerceptibleBindingCount == 0) {
-            mNotPerceptibleBinding.unbindServiceConnection();
+            assumeNonNull(mNotPerceptibleBinding).unbindServiceConnection();
             updateBindingState();
         }
     }
@@ -1151,7 +1214,7 @@
             newBindingState = ChildBindingState.STRONG;
         } else if (mVisibleBinding.isBound()) {
             newBindingState = ChildBindingState.VISIBLE;
-        } else if (supportNotPerceptibleBinding() && mNotPerceptibleBinding.isBound()) {
+        } else if (mNotPerceptibleBinding != null && mNotPerceptibleBinding.isBound()) {
             newBindingState = ChildBindingState.NOT_PERCEPTIBLE;
         } else {
             assert mWaivedBinding.isBound();
@@ -1181,7 +1244,7 @@
 
     public void crashServiceForTesting() {
         try {
-            mService.forceKill();
+            assumeNonNull(mService).forceKill();
         } catch (RemoteException e) {
             // Expected. Ignore.
         }
@@ -1196,6 +1259,10 @@
         return mLauncherHandler;
     }
 
+    private boolean getAlwaysFallback() {
+        return sAlwaysFallback && !mIndependentFallback;
+    }
+
     private void onMemoryPressure(@MemoryPressureLevel int pressure) {
         mLauncherHandler.post(() -> onMemoryPressureOnLauncherThread(pressure));
     }
diff --git a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConstants.java b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConstants.java
index 872d49b..8cc6e3c 100644
--- a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConstants.java
+++ b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConstants.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base.process_launcher;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Constants to be used by child processes. */
+@NullMarked
 public interface ChildProcessConstants {
     // Below are the names for the items placed in the bind or start command intent.
     // Note that because that intent maybe reused if a service is restarted, none should be process
diff --git a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessLauncher.java b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessLauncher.java
index 7957b85..6327a9c 100644
--- a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessLauncher.java
+++ b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessLauncher.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base.process_launcher;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.IBinder;
@@ -12,11 +14,15 @@
 import org.chromium.base.ContextUtils;
 import org.chromium.base.Log;
 import org.chromium.base.TraceEvent;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+import org.chromium.build.annotations.RequiresNonNull;
 
 import java.io.IOException;
 import java.util.List;
 
 /** This class is used to start a child process by connecting to a ChildProcessService. */
+@NullMarked
 public class ChildProcessLauncher {
     private static final String TAG = "ChildProcLauncher";
 
@@ -25,16 +31,16 @@
         /**
          * Called when the launcher is about to start. Gives the embedder a chance to provide an
          * already bound connection if it has one. (allowing for warm-up connections: connections
-         * that are already bound in advance to speed up child process start-up time).
-         * Note that onBeforeConnectionAllocated will not be called if this method returns a
-         * connection.
+         * that are already bound in advance to speed up child process start-up time). Note that
+         * onBeforeConnectionAllocated will not be called if this method returns a connection.
+         *
          * @param connectionAllocator the allocator the returned connection should have been
-         * allocated of.
+         *     allocated of.
          * @param serviceCallback the service callback that the connection should use.
          * @return a bound connection to use to connect to the child process service, or null if a
-         * connection should be allocated and bound by the launcher.
+         *     connection should be allocated and bound by the launcher.
          */
-        public ChildProcessConnection getBoundConnection(
+        public @Nullable ChildProcessConnection getBoundConnection(
                 ChildConnectionAllocator connectionAllocator,
                 ChildProcessConnection.ServiceCallback serviceCallback) {
             return null;
@@ -95,14 +101,14 @@
     private final ChildConnectionAllocator mConnectionAllocator;
 
     // The IBinder interfaces provided to the created service.
-    private final List<IBinder> mClientInterfaces;
+    private final @Nullable List<IBinder> mClientInterfaces;
 
-    // A binder box which can be used by the child to unpack additional binders. May be null.
-    private final IBinder mBinderBox;
+    // A binder box which can be used by the child to unpack additional binders.
+    private final @Nullable IBinder mBinderBox;
 
     // The actual service connection. Set once we have connected to the service. Volatile as it is
     // accessed from threads other than the Launcher thread.
-    private volatile ChildProcessConnection mConnection;
+    private volatile @Nullable ChildProcessConnection mConnection;
 
     /**
      * Constructor.
@@ -122,8 +128,8 @@
             String[] commandLine,
             FileDescriptorInfo[] filesToBeMapped,
             ChildConnectionAllocator connectionAllocator,
-            List<IBinder> clientInterfaces,
-            IBinder binderBox) {
+            @Nullable List<IBinder> clientInterfaces,
+            @Nullable IBinder binderBox) {
         assert connectionAllocator != null;
         mLauncherHandler = launcherHandler;
         isRunningOnLauncherThread();
@@ -198,7 +204,7 @@
         }
     }
 
-    public ChildProcessConnection getConnection() {
+    public @Nullable ChildProcessConnection getConnection() {
         return mConnection;
     }
 
@@ -235,6 +241,7 @@
         return true;
     }
 
+    @RequiresNonNull("mConnection")
     private void setupConnection() {
         ChildProcessConnection.ZygoteInfoCallback zygoteInfoCallback =
                 new ChildProcessConnection.ZygoteInfoCallback() {
@@ -247,7 +254,7 @@
         ChildProcessConnection.ConnectionCallback connectionCallback =
                 new ChildProcessConnection.ConnectionCallback() {
                     @Override
-                    public void onConnected(ChildProcessConnection connection) {
+                    public void onConnected(@Nullable ChildProcessConnection connection) {
                         onServiceConnected(connection);
                     }
                 };
@@ -261,13 +268,15 @@
                 zygoteInfoCallback);
     }
 
-    private void onServiceConnected(ChildProcessConnection connection) {
+    private void onServiceConnected(@Nullable ChildProcessConnection connection) {
+        ChildProcessConnection curConnection = mConnection;
         assert isRunningOnLauncherThread();
-        assert mConnection == connection || connection == null;
+        assert curConnection != null;
+        assert curConnection == connection || connection == null;
 
-        Log.d(TAG, "on connect callback, pid=%d", mConnection.getPid());
+        Log.d(TAG, "on connect callback, pid=%d", curConnection.getPid());
 
-        mDelegate.onConnectionEstablished(mConnection);
+        mDelegate.onConnectionEstablished(curConnection);
 
         // Proactively close the FDs rather than waiting for the GC to do it.
         try {
@@ -281,14 +290,15 @@
 
     public int getPid() {
         assert isRunningOnLauncherThread();
-        return mConnection == null ? NULL_PROCESS_HANDLE : mConnection.getPid();
+        ChildProcessConnection connection = mConnection;
+        return connection == null ? NULL_PROCESS_HANDLE : connection.getPid();
     }
 
-    public List<IBinder> getClientInterfaces() {
+    public @Nullable List<IBinder> getClientInterfaces() {
         return mClientInterfaces;
     }
 
-    public IBinder getBinderBox() {
+    public @Nullable IBinder getBinderBox() {
         return mBinderBox;
     }
 
@@ -304,15 +314,15 @@
     }
 
     private void onChildProcessDied() {
-        assert isRunningOnLauncherThread();
         if (getPid() != 0) {
-            mDelegate.onConnectionLost(mConnection);
+            mDelegate.onConnectionLost(assumeNonNull(mConnection));
         }
     }
 
     public void stop() {
         assert isRunningOnLauncherThread();
-        Log.d(TAG, "stopping child connection: pid=%d", mConnection.getPid());
-        mConnection.stop();
+        ChildProcessConnection connection = assumeNonNull(mConnection);
+        Log.d(TAG, "stopping child connection: pid=%d", connection.getPid());
+        connection.stop();
     }
 }
diff --git a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java
index 186c212..442f223 100644
--- a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java
+++ b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base.process_launcher;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
@@ -35,6 +37,9 @@
 import org.chromium.base.library_loader.LibraryLoader;
 import org.chromium.base.memory.MemoryPressureMonitor;
 import org.chromium.base.metrics.RecordHistogram;
+import org.chromium.build.annotations.Initializer;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.List;
 
@@ -61,6 +66,7 @@
  */
 @JNINamespace("base::android")
 @SuppressWarnings("SynchronizeOnNonFinalField") // mMainThread assigned in onCreate().
+@NullMarked
 public class ChildProcessService {
     private static final String MAIN_THREAD_NAME = "ChildProcessMain";
     private static final String TAG = "ChildProcessService";
@@ -87,16 +93,16 @@
     private int mBoundCallingPid;
 
     @GuardedBy("mBinderLock")
-    private String mBoundCallingClazz;
+    private @Nullable String mBoundCallingClazz;
 
     // This is the native "Main" thread for the renderer / utility process.
     private Thread mMainThread;
 
     // Parameters received via IPC, only accessed while holding the mMainThread monitor.
-    private String[] mCommandLineParams;
+    private String @Nullable [] mCommandLineParams;
 
     // File descriptors that should be registered natively.
-    private FileDescriptorInfo[] mFdInfos;
+    private FileDescriptorInfo @Nullable [] mFdInfos;
 
     @GuardedBy("mLibraryInitializedLock")
     private boolean mLibraryInitialized;
@@ -106,7 +112,7 @@
     private boolean mServiceBound;
 
     // Interface to send notifications to the parent process.
-    private IParentProcess mParentProcess;
+    private @Nullable IParentProcess mParentProcess;
 
     public ChildProcessService(
             ChildProcessServiceDelegate delegate, Service service, Context applicationContext) {
@@ -252,7 +258,7 @@
             };
 
     /** Loads Chrome's native libraries and initializes a ChildProcessService. */
-    // For sCreateCalled check.
+    @Initializer
     public void onCreate() {
         Log.i(TAG, "Creating new ChildProcessService pid=%d", Process.myPid());
         if (sCreateCalled) {
@@ -278,6 +284,7 @@
     }
 
     private void mainThreadMain() {
+        assumeNonNull(mParentProcess);
         try {
             // CommandLine must be initialized before everything else.
             synchronized (mMainThread) {
@@ -288,6 +295,11 @@
             assert mServiceBound;
             CommandLine.init(mCommandLineParams);
 
+            if (CommandLine.getInstance()
+                    .hasSwitch(BaseSwitches.ANDROID_SKIP_CHILD_SERVICE_INIT_FOR_TESTING)) {
+                return;
+            }
+
             if (CommandLine.getInstance().hasSwitch(BaseSwitches.RENDERER_WAIT_FOR_JAVA_DEBUGGER)) {
                 android.os.Debug.waitForDebugger();
             }
diff --git a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessServiceDelegate.java b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessServiceDelegate.java
index 08f7c5a..2bb8eed 100644
--- a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessServiceDelegate.java
+++ b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildProcessServiceDelegate.java
@@ -10,9 +10,12 @@
 import android.os.IBinder;
 import android.util.SparseArray;
 
+import org.chromium.build.annotations.NullMarked;
+
 import java.util.List;
 
 /** The interface that embedders should implement to specialize child service creation. */
+@NullMarked
 public interface ChildProcessServiceDelegate {
     /** Invoked when the service was created. This is the first method invoked on the delegate. */
     void onServiceCreated();
diff --git a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnection.java b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnection.java
index 560fe9d..0b4a281 100644
--- a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnection.java
+++ b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnection.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base.process_launcher;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Interface representing a connection to the Android service. Can be mocked in unit-tests. */
+@NullMarked
 /* package */ interface ChildServiceConnection {
     boolean bindServiceConnection();
 
diff --git a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnectionDelegate.java b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnectionDelegate.java
index 3439856..940ab3c 100644
--- a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnectionDelegate.java
+++ b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnectionDelegate.java
@@ -6,10 +6,13 @@
 
 import android.os.IBinder;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
- * Delegate that ChildServiceConnection should call when the service connects/disconnects.
- * These callbacks are expected to happen on a background thread.
+ * Delegate that ChildServiceConnection should call when the service connects/disconnects. These
+ * callbacks are expected to happen on a background thread.
  */
+@NullMarked
 /* package */ interface ChildServiceConnectionDelegate {
     void onServiceConnected(IBinder service);
 
diff --git a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnectionFactory.java b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnectionFactory.java
index 21b1521..52bda26 100644
--- a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnectionFactory.java
+++ b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnectionFactory.java
@@ -6,10 +6,14 @@
 
 import android.content.Intent;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
+@NullMarked
 /* package */ interface ChildServiceConnectionFactory {
     ChildServiceConnection createConnection(
             Intent bindIntent,
             int bindFlags,
             ChildServiceConnectionDelegate delegate,
-            String instanceName);
+            @Nullable String instanceName);
 }
diff --git a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnectionImpl.java b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnectionImpl.java
index a25d2cb..a357682 100644
--- a/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnectionImpl.java
+++ b/tot/base/android/java/src/org/chromium/base/process_launcher/ChildServiceConnectionImpl.java
@@ -13,10 +13,13 @@
 
 import org.chromium.base.Log;
 import org.chromium.base.TraceEvent;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.concurrent.Executor;
 
 /** Implementation of ChildServiceConnection that does connect to a service. */
+@NullMarked
 /* package */ class ChildServiceConnectionImpl
         implements ChildServiceConnection, ServiceConnection {
     private static final String TAG = "ChildServiceConn";
@@ -26,8 +29,8 @@
     private final int mBindFlags;
     private final Handler mHandler;
     private final Executor mExecutor;
-    private ChildServiceConnectionDelegate mDelegate;
-    private final String mInstanceName;
+    private @Nullable ChildServiceConnectionDelegate mDelegate;
+    private final @Nullable String mInstanceName;
     private boolean mBound;
 
     /* package */ ChildServiceConnectionImpl(
@@ -37,7 +40,7 @@
             Handler handler,
             Executor executor,
             ChildServiceConnectionDelegate delegate,
-            String instanceName) {
+            @Nullable String instanceName) {
         mContext = context;
         mBindIntent = bindIntent;
         mBindFlags = bindFlags;
diff --git a/tot/base/android/java/src/org/chromium/base/process_launcher/FileDescriptorInfo.java b/tot/base/android/java/src/org/chromium/base/process_launcher/FileDescriptorInfo.java
index 62f2f1f..5ecf70c 100644
--- a/tot/base/android/java/src/org/chromium/base/process_launcher/FileDescriptorInfo.java
+++ b/tot/base/android/java/src/org/chromium/base/process_launcher/FileDescriptorInfo.java
@@ -8,16 +8,18 @@
 import android.os.ParcelFileDescriptor;
 import android.os.Parcelable;
 
+import org.chromium.build.annotations.NullMarked;
 import org.chromium.build.annotations.UsedByReflection;
 
 import javax.annotation.concurrent.Immutable;
 
 /**
- * Parcelable class that contains file descriptor and file region information to
- * be passed to child processes.
+ * Parcelable class that contains file descriptor and file region information to be passed to child
+ * processes.
  */
 @Immutable
 @UsedByReflection("child_process_launcher_helper_android.cc")
+@NullMarked
 public final class FileDescriptorInfo implements Parcelable {
     public final int id;
     public final ParcelFileDescriptor fd;
@@ -33,7 +35,9 @@
 
     FileDescriptorInfo(Parcel in) {
         id = in.readInt();
-        fd = in.readParcelable(ParcelFileDescriptor.class.getClassLoader());
+        ParcelFileDescriptor gotFd = in.readParcelable(ParcelFileDescriptor.class.getClassLoader());
+        assert gotFd != null;
+        fd = gotFd;
         offset = in.readLong();
         size = in.readLong();
     }
diff --git a/tot/base/android/java/src/org/chromium/base/shared_preferences/KeyPrefix.java b/tot/base/android/java/src/org/chromium/base/shared_preferences/KeyPrefix.java
index 5f4416d..b0ec02c 100644
--- a/tot/base/android/java/src/org/chromium/base/shared_preferences/KeyPrefix.java
+++ b/tot/base/android/java/src/org/chromium/base/shared_preferences/KeyPrefix.java
@@ -4,11 +4,14 @@
 
 package org.chromium.base.shared_preferences;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
  * A prefix for a range of SharedPreferences keys generated dynamically.
  *
- * Instances should be declared as keys in the PreferenceKeys registry.
+ * <p>Instances should be declared as keys in the PreferenceKeys registry.
  */
+@NullMarked
 public class KeyPrefix {
     private final String mPrefix;
 
diff --git a/tot/base/android/java/src/org/chromium/base/shared_preferences/KnownPreferenceKeyRegistries.java b/tot/base/android/java/src/org/chromium/base/shared_preferences/KnownPreferenceKeyRegistries.java
index 1c0c261..87783b7 100644
--- a/tot/base/android/java/src/org/chromium/base/shared_preferences/KnownPreferenceKeyRegistries.java
+++ b/tot/base/android/java/src/org/chromium/base/shared_preferences/KnownPreferenceKeyRegistries.java
@@ -4,11 +4,15 @@
 
 package org.chromium.base.shared_preferences;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import com.google.common.collect.Sets;
 
 import org.chromium.base.ResettersForTesting;
 import org.chromium.build.BuildConfig;
 import org.chromium.build.annotations.CheckDiscard;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.ArrayList;
 import java.util.HashSet;
@@ -18,16 +22,18 @@
 /**
  * Ensures that all {@link PreferenceKeyRegistry}s used are known.
  *
- * A complement to ChromePreferenceKeysTest, which ensures that preference keys across all known
+ * <p>A complement to ChromePreferenceKeysTest, which ensures that preference keys across all known
  * registries are unique.
  *
- * This checking is done in tests in which |initializeKnownRegistries()| is called, which happens
+ * <p>This checking is done in tests in which |initializeKnownRegistries()| is called, which happens
  * during browser process initialization.
  */
 @CheckDiscard("Preference key checking should only happen on build with asserts")
+@NullMarked
 public class KnownPreferenceKeyRegistries {
-    private static Set<PreferenceKeyRegistry> sKnownRegistries;
-    private static Set<PreferenceKeyRegistry> sRegistriesUsedBeforeInitialization = new HashSet<>();
+    private static @Nullable Set<PreferenceKeyRegistry> sKnownRegistries;
+    private static @Nullable Set<PreferenceKeyRegistry> sRegistriesUsedBeforeInitialization =
+            new HashSet<>();
 
     public static void onRegistryUsed(PreferenceKeyRegistry registry) {
         if (!BuildConfig.ENABLE_ASSERTS) {
@@ -36,7 +42,7 @@
 
         if (sKnownRegistries == null) {
             // Before initialization, keep track of registries used.
-            sRegistriesUsedBeforeInitialization.add(registry);
+            assumeNonNull(sRegistriesUsedBeforeInitialization).add(registry);
         } else {
             // After initialization, check if registry is known.
             if (!sKnownRegistries.contains(registry)) {
@@ -62,7 +68,9 @@
 
         // Check that each registry already used is known; assert otherwise.
         Set<PreferenceKeyRegistry> unknownRegistries =
-                Sets.difference(sRegistriesUsedBeforeInitialization, knownRegistries);
+                Sets.difference(
+                        assumeNonNull(sRegistriesUsedBeforeInitialization),
+                        knownRegistries);
         if (!unknownRegistries.isEmpty()) {
             List<String> unknownRegistryNames = new ArrayList<>();
             for (PreferenceKeyRegistry unknownRegistry : unknownRegistries) {
diff --git a/tot/base/android/java/src/org/chromium/base/shared_preferences/PreferenceKeyChecker.java b/tot/base/android/java/src/org/chromium/base/shared_preferences/PreferenceKeyChecker.java
index a372d66..5682d58 100644
--- a/tot/base/android/java/src/org/chromium/base/shared_preferences/PreferenceKeyChecker.java
+++ b/tot/base/android/java/src/org/chromium/base/shared_preferences/PreferenceKeyChecker.java
@@ -4,12 +4,15 @@
 
 package org.chromium.base.shared_preferences;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
  * A SharedPreferences key checker that may check if the key is in use.
  *
- * In official builds, {@link NoOpPreferenceKeyChecker} is used, which is a no-op.
- * In debug builds, {@link StrictPreferenceKeyChecker} is used, which checks if a key is registered.
+ * <p>In official builds, {@link NoOpPreferenceKeyChecker} is used, which is a no-op. In debug
+ * builds, {@link StrictPreferenceKeyChecker} is used, which checks if a key is registered.
  */
+@NullMarked
 interface PreferenceKeyChecker {
     // Asserts that the SharedPreferences |key| is registered as "in use".
     void checkIsKeyInUse(String key);
diff --git a/tot/base/android/java/src/org/chromium/base/shared_preferences/PreferenceKeyRegistry.java b/tot/base/android/java/src/org/chromium/base/shared_preferences/PreferenceKeyRegistry.java
index 2d6badd..f76f8dd 100644
--- a/tot/base/android/java/src/org/chromium/base/shared_preferences/PreferenceKeyRegistry.java
+++ b/tot/base/android/java/src/org/chromium/base/shared_preferences/PreferenceKeyRegistry.java
@@ -4,15 +4,15 @@
 
 package org.chromium.base.shared_preferences;
 
-import androidx.annotation.NonNull;
-
 import org.chromium.build.annotations.CheckDiscard;
+import org.chromium.build.annotations.NullMarked;
 
 import java.util.HashSet;
 import java.util.List;
 import java.util.Locale;
 
 @CheckDiscard("Preference key checking should only happen on build with asserts")
+@NullMarked
 public class PreferenceKeyRegistry {
     private final String mModule;
     public final HashSet<String> mKeysInUse;
@@ -30,7 +30,6 @@
         mLegacyPrefixes = legacyPrefixes;
     }
 
-    @NonNull
     public String toDebugString() {
         return String.format(
                 Locale.getDefault(),
diff --git a/tot/base/android/java/src/org/chromium/base/shared_preferences/SharedPreferencesManager.java b/tot/base/android/java/src/org/chromium/base/shared_preferences/SharedPreferencesManager.java
index ea47564..0ef1ef5 100644
--- a/tot/base/android/java/src/org/chromium/base/shared_preferences/SharedPreferencesManager.java
+++ b/tot/base/android/java/src/org/chromium/base/shared_preferences/SharedPreferencesManager.java
@@ -4,18 +4,23 @@
 
 package org.chromium.base.shared_preferences;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.content.SharedPreferences;
 
 import androidx.annotation.GuardedBy;
-import androidx.annotation.Nullable;
 import androidx.annotation.VisibleForTesting;
 
 import org.jni_zero.CalledByNative;
 import org.jni_zero.JNINamespace;
+import org.jni_zero.JniType;
 
 import org.chromium.base.ContextUtils;
 import org.chromium.base.ResettersForTesting;
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.Contract;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.Collections;
 import java.util.HashMap;
@@ -26,15 +31,16 @@
 /** Layer over android {@link SharedPreferences}. */
 @JNINamespace("base::android")
 @SuppressWarnings("UseSharedPreferencesManagerFromChromeCheck")
+@NullMarked
 public class SharedPreferencesManager {
     // Without asserts, this is a singleton (because no key names are checked).
     // With asserts, there is one manager per-registry in order to not have to consult
     // all registries each time a key name is checked.
     @GuardedBy("sInstances")
-    private static final Map<PreferenceKeyRegistry, SharedPreferencesManager> sInstances =
+    private static final @Nullable Map<PreferenceKeyRegistry, SharedPreferencesManager> sInstances =
             BuildConfig.ENABLE_ASSERTS ? new HashMap<>() : null;
 
-    private static final SharedPreferencesManager sInstance =
+    private static final @Nullable SharedPreferencesManager sInstance =
             BuildConfig.ENABLE_ASSERTS
                     ? null
                     : new SharedPreferencesManager((PreferenceKeyRegistry) null);
@@ -113,7 +119,7 @@
         }
     }
 
-    private PreferenceKeyChecker mKeyChecker;
+    private @Nullable PreferenceKeyChecker mKeyChecker;
 
     protected SharedPreferencesManager(@Nullable PreferenceKeyRegistry registry) {
         mKeyChecker = BuildConfig.ENABLE_ASSERTS ? new StrictPreferenceKeyChecker(registry) : null;
@@ -130,10 +136,11 @@
      * @return a {@link SharedPreferencesManager} that operates on SharedPreferences keys registered
      *     in the passed |registry|
      */
+    @SuppressWarnings("NullAway") // Cannot assumeNonNull(sInstances) due to @GuardedBy warning.
     public static SharedPreferencesManager getInstanceForRegistry(
             @Nullable PreferenceKeyRegistry registry) {
         if (!BuildConfig.ENABLE_ASSERTS) {
-            return sInstance;
+            return assumeNonNull(sInstance);
         }
         SharedPreferencesManager manager;
         synchronized (sInstances) {
@@ -189,11 +196,14 @@
      *
      * @return unmodifiable Set with the values
      */
-    @Nullable
-    public Set<String> readStringSet(String key, @Nullable Set<String> defaultValue) {
+    @Contract("_, !null -> !null")
+    public @Nullable Set<String> readStringSet(String key, @Nullable Set<String> defaultValue) {
         checkIsKeyInUse(key);
         Set<String> values = ContextUtils.getAppSharedPreferences().getStringSet(key, defaultValue);
-        return (values != null) ? Collections.unmodifiableSet(values) : null;
+        if (values != null) {
+            return Collections.unmodifiableSet(values);
+        }
+        return null;
     }
 
     /** Adds a value to string set in shared preferences. */
@@ -294,7 +304,7 @@
      * @return The value of the preference.
      */
     @CalledByNative
-    public int readInt(String key, int defaultValue) {
+    public int readInt(@JniType("std::string") String key, int defaultValue) {
         checkIsKeyInUse(key);
         return ContextUtils.getAppSharedPreferences().getInt(key, defaultValue);
     }
@@ -433,7 +443,7 @@
      */
     public void writeDouble(String key, double value) {
         SharedPreferences.Editor ed = getEditor();
-        // Matches the conversion used in DoubleCachedFieldTrialParameter#writeCacheValueToEditor().
+        // Matches the conversion used in DoubleCachedFeatureParam#writeCacheValueToEditor().
         long ieee754LongValue = Double.doubleToRawLongBits(value);
         ed.putLong(key, ieee754LongValue);
         ed.apply();
@@ -507,7 +517,7 @@
      * @return The value of the preference if stored; defaultValue otherwise.
      */
     @CalledByNative
-    public boolean readBoolean(String key, boolean defaultValue) {
+    public boolean readBoolean(@JniType("std::string") String key, boolean defaultValue) {
         checkIsKeyInUse(key);
         return ContextUtils.getAppSharedPreferences().getBoolean(key, defaultValue);
     }
@@ -529,7 +539,8 @@
      * @param value The new value for the preference.
      */
     @CalledByNative
-    public void writeString(String key, String value) {
+    public void writeString(
+            @JniType("std::string") String key, @Nullable @JniType("std::string") String value) {
         SharedPreferences.Editor ed = getEditor();
         ed.putString(key, value);
         ed.apply();
@@ -556,8 +567,10 @@
      * @return The value of the preference if stored; defaultValue otherwise.
      */
     @CalledByNative
-    @Nullable
-    public String readString(String key, @Nullable String defaultValue) {
+    @Contract("_, !null -> !null")
+    public @Nullable @JniType("std::string") String readString(
+            @JniType("std::string") String key,
+            @JniType("std::string") @Nullable String defaultValue) {
         checkIsKeyInUse(key);
         return ContextUtils.getAppSharedPreferences().getString(key, defaultValue);
     }
@@ -578,7 +591,7 @@
      * @param key The key of the preference to remove.
      */
     @CalledByNative
-    public void removeKey(String key) {
+    public void removeKey(@JniType("std::string") String key) {
         SharedPreferences.Editor ed = getEditor();
         ed.remove(key);
         ed.apply();
@@ -597,6 +610,21 @@
      */
     public void removeKeysWithPrefix(KeyPrefix prefix) {
         checkIsPrefixInUse(prefix);
+        removeKeysWithPrefixInternal(prefix);
+    }
+
+    /**
+     * Removes all shared preference entries which have a prefix of prefix.createKey(infix + "*").
+     *
+     * @param prefix The KeyPrefix from which the prefix is constructed.
+     * @param infix The String infix from which the prefix is constructed.
+     */
+    public void removeKeysWithPrefix(KeyPrefix prefix, String infix) {
+        checkIsPrefixInUse(prefix);
+        removeKeysWithPrefixInternal(new KeyPrefix(prefix.createKey(infix + "*")));
+    }
+
+    private void removeKeysWithPrefixInternal(KeyPrefix prefix) {
         SharedPreferences.Editor ed = getEditor();
         Map<String, ?> allPrefs = ContextUtils.getAppSharedPreferences().getAll();
         for (Map.Entry<String, ?> pref : allPrefs.entrySet()) {
@@ -615,7 +643,7 @@
      * @return Whether any value was written for that key.
      */
     @CalledByNative
-    public boolean contains(String key) {
+    public boolean contains(@JniType("std::string") String key) {
         checkIsKeyInUse(key);
         return ContextUtils.getAppSharedPreferences().contains(key);
     }
diff --git a/tot/base/android/java/src/org/chromium/base/shared_preferences/StrictPreferenceKeyChecker.java b/tot/base/android/java/src/org/chromium/base/shared_preferences/StrictPreferenceKeyChecker.java
index 91721d9..4485af1 100644
--- a/tot/base/android/java/src/org/chromium/base/shared_preferences/StrictPreferenceKeyChecker.java
+++ b/tot/base/android/java/src/org/chromium/base/shared_preferences/StrictPreferenceKeyChecker.java
@@ -4,9 +4,13 @@
 
 package org.chromium.base.shared_preferences;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.text.TextUtils;
 
 import org.chromium.build.annotations.CheckDiscard;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.Arrays;
 import java.util.regex.Pattern;
@@ -14,14 +18,18 @@
 /**
  * Class that checks if given Strings are valid SharedPreferences keys to use.
  *
- * Checks that:
+ * <p>Checks that:
+ *
+ * <pre>
  * 1. Keys are registered as "in use".
  * 2. The key format is valid, either:
- *   - "Chrome.[Feature].[Key]"
- *   - "Chrome.[Feature].[KeyPrefix].[Suffix]"
- *   - Legacy key prior to this restriction
+ *     - "Chrome.[Feature].[Key]"
+ *     - "Chrome.[Feature].[KeyPrefix].[Suffix]"
+ *     - Legacy key prior to this restriction
+ * </pre>
  */
 @CheckDiscard("Validation is performed in tests and in debug builds.")
+@NullMarked
 class StrictPreferenceKeyChecker implements PreferenceKeyChecker {
     // The dynamic part cannot be empty, but otherwise it is anything that does not contain
     // stars.
@@ -29,12 +37,15 @@
 
     private final PreferenceKeyRegistry mRegistry;
 
-    StrictPreferenceKeyChecker(PreferenceKeyRegistry registry) {
-        mRegistry = registry;
+    StrictPreferenceKeyChecker(@Nullable PreferenceKeyRegistry registry) {
+        // |registry| is non-null when ENABLE_ASSERTS is true, and this class is supposed to be
+        // optimized away when ENABLE_ASSERTS is false. @CheckDiscard ensures this.
+        mRegistry = assumeNonNull(registry);
     }
 
     /**
      * Check that the |key| passed is in use.
+     *
      * @throws RuntimeException if the key is not in use.
      */
     @Override
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/DestroyableObservableSupplier.java b/tot/base/android/java/src/org/chromium/base/supplier/DestroyableObservableSupplier.java
index e250f983..00aa33c 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/DestroyableObservableSupplier.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/DestroyableObservableSupplier.java
@@ -5,6 +5,7 @@
 package org.chromium.base.supplier;
 
 import org.chromium.base.lifetime.Destroyable;
+import org.chromium.build.annotations.NullMarked;
 
 /**
  * An {@link ObservableSupplier} that may be destroyed by anyone with a reference to the object.
@@ -14,4 +15,5 @@
  *
  * @param <E> The type of the wrapped object.
  */
+@NullMarked
 public interface DestroyableObservableSupplier<E> extends ObservableSupplier<E>, Destroyable {}
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/LazyOneshotSupplier.java b/tot/base/android/java/src/org/chromium/base/supplier/LazyOneshotSupplier.java
index 9f29d76..9d92c67 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/LazyOneshotSupplier.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/LazyOneshotSupplier.java
@@ -4,9 +4,9 @@
 
 package org.chromium.base.supplier;
 
-import androidx.annotation.Nullable;
-
 import org.chromium.base.Callback;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /**
  * Wraps a lazy-loaded nullable object, notifying observers a single time when the dependency
@@ -15,7 +15,8 @@
  *
  * @param <T> The type of the wrapped object.
  */
-public interface LazyOneshotSupplier<T> {
+@NullMarked
+public interface LazyOneshotSupplier<T extends @Nullable Object> {
     /**
      * Add a callback that's called when the object owned by this supplier is available. If the
      * object is already available, the callback will be called at the end of the current message
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/LazyOneshotSupplierImpl.java b/tot/base/android/java/src/org/chromium/base/supplier/LazyOneshotSupplierImpl.java
index a2fab0f..b6f770b 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/LazyOneshotSupplierImpl.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/LazyOneshotSupplierImpl.java
@@ -4,11 +4,11 @@
 
 package org.chromium.base.supplier;
 
-import androidx.annotation.Nullable;
-
 import org.chromium.base.Callback;
 import org.chromium.base.Promise;
 import org.chromium.base.ThreadUtils;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /**
  * Abstract implementation of {@link LazySupplier} to be used by classes providing it as a
@@ -37,7 +37,9 @@
  *
  * @param <T> The type of the wrapped object.
  */
-public abstract class LazyOneshotSupplierImpl<T> implements LazyOneshotSupplier<T> {
+@NullMarked
+public abstract class LazyOneshotSupplierImpl<T extends @Nullable Object>
+        implements LazyOneshotSupplier<T> {
     private final Promise<T> mPromise = new Promise<>();
     private final ThreadUtils.ThreadChecker mThreadChecker = new ThreadUtils.ThreadChecker();
 
@@ -86,7 +88,7 @@
      *
      * @param object The object to supply.
      */
-    public void set(@Nullable T object) {
+    public void set(T object) {
         mThreadChecker.assertOnValidThread();
         assert !mPromise.isFulfilled();
         mPromise.fulfill(object);
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/ObservableSupplier.java b/tot/base/android/java/src/org/chromium/base/supplier/ObservableSupplier.java
index f429eab..bf5a6a5 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/ObservableSupplier.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/ObservableSupplier.java
@@ -4,7 +4,11 @@
 
 package org.chromium.base.supplier;
 
+import androidx.annotation.IntDef;
+
 import org.chromium.base.Callback;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /**
  * ObservableSupplier wraps an asynchronously provided object E, notifying observers when the
@@ -12,28 +16,109 @@
  * ObservableSupplier during construction and register a Callback<E> to be notified when the needed
  * dependency is available.
  *
- * This class must only be accessed from a single thread.
+ * <p>This class must only be accessed from a single thread.
  *
- * For classes owning the ObservableSupplier and providing it as a dependency to others, see
+ * <p>For classes owning the ObservableSupplier and providing it as a dependency to others, see
  * {@link ObservableSupplierImpl}.
  *
- * For classes using a ObservableSupplier to receive a dependency:
- *   - To be notified when the object is available, call {@link #addObserver(Callback)} with a
- *     Callback to be notified when the object is available.
- *   - If the object is already available, the Callback will be called immediately.
- *   - The Callback may be called multiple times if the object wrapped by the ObservableSupplier
- *     changes.
+ * <p>The behavior of the observer is different depending on which method is called.
  *
  * @param <E> The type of the wrapped object.
  */
+@NullMarked
 public interface ObservableSupplier<E> extends Supplier<E> {
     /**
-     * @param obs An observer to be notified when the object owned by this supplier is available.
-     *       If the object is already available, the callback will be notified at the end of the
-     *       current message loop (so long as the object hasn't changed).
+     * A bitmask of flags that control the notification behavior of {@link #addObserver(Callback,
+     * int)}.
+     */
+    @IntDef(
+            flag = true,
+            value = {
+                NotifyBehavior.NOTIFY_ON_ADD,
+                NotifyBehavior.POST_ON_ADD,
+                NotifyBehavior.NONE,
+            })
+    @interface NotifyBehavior {
+
+        /**
+         * If set, the observer in {@link #addObserver(Callback, int)} method will be called upon
+         * being added.
+         */
+        int NOTIFY_ON_ADD = 1 << 0;
+
+        /**
+         * If set, the observer in {@link #addObserver(Callback, int)} method will be called
+         * asynchronously upon being added. This flag only has an effect if {@link #NOTIFY_ON_ADD}
+         * is set.
+         */
+        int POST_ON_ADD = 1 << 1;
+
+        /** All flags disabled. */
+        int NONE = 0;
+    }
+
+    /**
+     * Adds an observer, which is then notified upon the dependency being modified. Additional
+     * behaviors are specified through |behavior|.
+     *
+     * @param obs An observer to be added.
+     * @param behavior A bitmask of {@link NotifyBehavior} flags that control the notification
+     *     behavior.
      * @return The current object or null if it hasn't been set yet.
      */
-    E addObserver(Callback<E> obs);
+    @Nullable E addObserver(Callback<E> obs, @NotifyBehavior int behavior);
+
+    /**
+     * Adds a synchronous observer. Equivalent to calling {@link #addObserver(Callback, int)} with
+     * {@link NotifyBehavior#NONE}.
+     *
+     * @param obs The observer to add.
+     * @return The current object if available, otherwise null.
+     */
+    default @Nullable E addSyncObserver(Callback<E> obs) {
+        return addObserver(obs, NotifyBehavior.NONE);
+    }
+
+    /**
+     * Adds an observer that is called immediately, if the value is non-null.
+     *
+     * <p>Equivalent to calling {@link #addObserver(Callback, int)} with {@link
+     * NotifyBehavior#NOTIFY_ON_ADD}.
+     *
+     * @param obs The observer to add.
+     * @return The current object if available, otherwise null.
+     */
+    default @Nullable E addSyncObserverAndCallIfNonNull(Callback<E> obs) {
+        return addObserver(obs, NotifyBehavior.NOTIFY_ON_ADD);
+    }
+
+    /**
+     * Adds an observer that is asynchronously called immediately, if the value is non-null.
+     *
+     * <p>Equivalent to calling {@link #addObserver(Callback, int)} with {@link
+     * NotifyBehavior#NOTIFY_ON_ADD} | {@link NotifyBehavior#POST_ON_ADD}.
+     *
+     * @param obs The observer to add.
+     * @return The current object if available, otherwise null.
+     */
+    default @Nullable E addSyncObserverAndPostIfNonNull(Callback<E> obs) {
+        return addObserver(obs, NotifyBehavior.NOTIFY_ON_ADD | NotifyBehavior.POST_ON_ADD);
+    }
+
+    /**
+     * Adds a synchronous observer, which will be notified when the object owned by this supplier is
+     * available. If the object is already available, the callback will be notified asynchronously
+     * at the end of the current message loop (so long as the object hasn't changed).
+     *
+     * <p>Equivalent to calling {@link #addObserver(Callback, int)} with {@link
+     * NotifyBehavior#NOTIFY_ON_ADD} | {@link NotifyBehavior#POST_ON_ADD}.
+     *
+     * @param obs An observer to be added.
+     * @return The current object or null if it hasn't been set yet.
+     */
+    default @Nullable E addObserver(Callback<E> obs) {
+        return addSyncObserverAndPostIfNonNull(obs);
+    }
 
     /**
      * @param obs The observer to remove.
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/ObservableSupplierImpl.java b/tot/base/android/java/src/org/chromium/base/supplier/ObservableSupplierImpl.java
index 319e6c3..8552041 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/ObservableSupplierImpl.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/ObservableSupplierImpl.java
@@ -4,14 +4,12 @@
 
 package org.chromium.base.supplier;
 
-import android.os.Handler;
-
-import androidx.annotation.Nullable;
-
 import org.chromium.base.Callback;
 import org.chromium.base.ObserverList;
 import org.chromium.base.ThreadUtils;
 import org.chromium.base.ThreadUtils.ThreadChecker;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.Objects;
 
@@ -30,12 +28,12 @@
  *
  * @param <E> The type of the wrapped object.
  */
-public class ObservableSupplierImpl<E> implements ObservableSupplier<E> {
+@NullMarked
+public class ObservableSupplierImpl<E extends @Nullable Object> implements ObservableSupplier<E> {
     private final ThreadChecker mThreadChecker = new ThreadChecker();
-    private final Handler mHandler = new Handler();
 
-    private E mObject;
-    private final ObserverList<Callback<E>> mObservers = new ObserverList<>();
+    private @Nullable E mObject;
+    protected final ObserverList<Callback<E>> mObservers = new ObserverList<>();
 
     public ObservableSupplierImpl() {
         // Guard against creation on Instrumentation thread, since this is basically always a bug.
@@ -47,24 +45,32 @@
     }
 
     @Override
-    public E addObserver(Callback<E> obs) {
+    @SuppressWarnings("NullAway") // Cannot specify that mObject is @Nullable only when E is.
+    public @Nullable E addObserver(Callback<E> obs, @NotifyBehavior int behavior) {
         // ObserverList has its own ThreadChecker.
         mObservers.addObserver(obs);
 
-        if (mObject != null) {
-            final E currentObject = mObject;
-            mHandler.post(
-                    () -> {
-                        if (mObject != currentObject || !mObservers.hasObserver(obs)) return;
-                        obs.onResult(mObject);
-                    });
+        boolean notify = shouldNotifyOnAdd(behavior) && mObject != null;
+        if (notify) {
+            E currentObject = mObject;
+            if (shouldPostOnAdd(behavior)) {
+                ThreadUtils.assertOnUiThread();
+                ThreadUtils.postOnUiThread(
+                        () -> {
+                            if (mObject == currentObject && mObservers.hasObserver(obs)) {
+                                obs.onResult(currentObject);
+                            }
+                        });
+            } else {
+                obs.onResult(currentObject);
+            }
         }
 
         return mObject;
     }
 
     @Override
-    public void removeObserver(Callback<E> obs) {
+    public void removeObserver(@Nullable Callback<E> obs) {
         // ObserverList has its own ThreadChecker.
         mObservers.removeObserver(obs);
     }
@@ -85,7 +91,7 @@
         mObject = object;
 
         for (Callback<E> observer : mObservers) {
-            observer.onResult(mObject);
+            observer.onResult(object);
         }
     }
 
@@ -102,4 +108,14 @@
         // ObserverList has its own ThreadChecker.
         return !mObservers.isEmpty();
     }
+
+    /** Returns whether the observer should be notified on being added. */
+    private static boolean shouldNotifyOnAdd(@NotifyBehavior int behavior) {
+        return (NotifyBehavior.NOTIFY_ON_ADD & behavior) != 0;
+    }
+
+    /** Returns whether the observer should be notified asynchronously on being added. */
+    private static boolean shouldPostOnAdd(int behavior) {
+        return (NotifyBehavior.POST_ON_ADD & behavior) != 0;
+    }
 }
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/OneShotCallback.java b/tot/base/android/java/src/org/chromium/base/supplier/OneShotCallback.java
index 2c0c8ca..5934a9b 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/OneShotCallback.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/OneShotCallback.java
@@ -4,9 +4,8 @@
 
 package org.chromium.base.supplier;
 
-import androidx.annotation.NonNull;
-
 import org.chromium.base.Callback;
+import org.chromium.build.annotations.NullMarked;
 
 import java.lang.ref.WeakReference;
 
@@ -27,6 +26,7 @@
  *
  * @param <E> The type of the wrapped object.
  */
+@NullMarked
 public class OneShotCallback<E> {
     private final Callback<E> mCallbackWrapper = new CallbackWrapper();
     private final WeakReference<ObservableSupplier<E>> mWeakSupplier;
@@ -38,7 +38,7 @@
      * @param supplier The {@link ObservableSupplier} to wait for.
      * @param callback The {@link Callback} to notify with a valid value.
      */
-    public OneShotCallback(@NonNull ObservableSupplier<E> supplier, @NonNull Callback<E> callback) {
+    public OneShotCallback(ObservableSupplier<E> supplier, Callback<E> callback) {
         mWeakSupplier = new WeakReference<>(supplier);
         mCallback = callback;
 
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/OneshotSupplier.java b/tot/base/android/java/src/org/chromium/base/supplier/OneshotSupplier.java
index 5b7a72a..c6c51f1 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/OneshotSupplier.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/OneshotSupplier.java
@@ -4,9 +4,9 @@
 
 package org.chromium.base.supplier;
 
-import androidx.annotation.Nullable;
-
 import org.chromium.base.Callback;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /**
  * OneshotSupplier wraps an asynchronously provided, non-null object {@code T}, notifying
@@ -39,6 +39,7 @@
  *
  * @param <T> The type of the wrapped object.
  */
+@NullMarked
 public interface OneshotSupplier<T> extends Supplier<T> {
     /**
      * Add a callback that's called when the object owned by this supplier is available.
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/OneshotSupplierImpl.java b/tot/base/android/java/src/org/chromium/base/supplier/OneshotSupplierImpl.java
index 234f29f..d0a3fb4 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/OneshotSupplierImpl.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/OneshotSupplierImpl.java
@@ -4,12 +4,11 @@
 
 package org.chromium.base.supplier;
 
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-
 import org.chromium.base.Callback;
 import org.chromium.base.Promise;
 import org.chromium.base.ThreadUtils;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /**
  * Concrete implementation of {@link OneshotSupplier} to be used by classes owning a
@@ -26,12 +25,13 @@
  *
  * @param <T> The type of the wrapped object.
  */
+@NullMarked
 public class OneshotSupplierImpl<T> implements OneshotSupplier<T> {
     private final Promise<T> mPromise = new Promise<>();
     private final ThreadUtils.ThreadChecker mThreadChecker = new ThreadUtils.ThreadChecker();
 
     @Override
-    public T onAvailable(Callback<T> callback) {
+    public @Nullable T onAvailable(Callback<T> callback) {
         mThreadChecker.assertOnValidThread();
         mPromise.then(callback);
         return get();
@@ -50,7 +50,7 @@
      *
      * @param object The object to supply.
      */
-    public void set(@NonNull T object) {
+    public void set(T object) {
         mThreadChecker.assertOnValidThread();
         assert !mPromise.isFulfilled();
         assert object != null;
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/Supplier.java b/tot/base/android/java/src/org/chromium/base/supplier/Supplier.java
index 2e0a5f6..9c7c8a3 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/Supplier.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/Supplier.java
@@ -4,13 +4,17 @@
 
 package org.chromium.base.supplier;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /**
- * Based on Java 8's java.util.function.Supplier.
- * Similar to Callable<T>, but without a checked Exception and with #hasValue().
+ * Based on Java 8's java.util.function.Supplier. Similar to Callable<T>, but without a checked
+ * Exception and with #hasValue().
  *
  * @param <T> Return type.
  */
-public interface Supplier<T> extends java.util.function.Supplier<T> {
+@NullMarked
+public interface Supplier<T extends @Nullable Object> extends java.util.function.Supplier<T> {
     /** Returns whether the supplier holds a value currently. */
     default boolean hasValue() {
         return get() != null;
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/SupplierUtils.java b/tot/base/android/java/src/org/chromium/base/supplier/SupplierUtils.java
index b4fe503..a56b04c 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/SupplierUtils.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/SupplierUtils.java
@@ -4,21 +4,22 @@
 
 package org.chromium.base.supplier;
 
-import androidx.annotation.NonNull;
-
 import org.chromium.base.Callback;
 import org.chromium.base.ThreadUtils;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /** Utilities for interactions with Suppliers. */
+@NullMarked
 public class SupplierUtils {
     private SupplierUtils() {}
 
     private static class Barrier {
         private final ThreadUtils.ThreadChecker mThreadChecker = new ThreadUtils.ThreadChecker();
         private int mWaitingCount;
-        private Runnable mCallback;
+        private @Nullable Runnable mCallback;
 
-        void waitForAll(Runnable callback, Supplier... suppliers) {
+        void waitForAll(Runnable callback, Supplier<?>... suppliers) {
             mThreadChecker.assertOnValidThread();
             assert mCallback == null;
             mCallback = callback;
@@ -75,7 +76,7 @@
      * @param callback The callback to be notified when all suppliers have values set.
      * @param suppliers The list of suppliers to check for values.
      */
-    public static void waitForAll(@NonNull Runnable callback, Supplier... suppliers) {
+    public static void waitForAll(Runnable callback, Supplier<?>... suppliers) {
         assert callback != null;
         new Barrier().waitForAll(callback, suppliers);
     }
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/SyncOneshotSupplier.java b/tot/base/android/java/src/org/chromium/base/supplier/SyncOneshotSupplier.java
index 6ad7f81..bb522f9 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/SyncOneshotSupplier.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/SyncOneshotSupplier.java
@@ -4,9 +4,9 @@
 
 package org.chromium.base.supplier;
 
-import androidx.annotation.Nullable;
-
 import org.chromium.base.Callback;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 /**
  * SyncOneshotSupplier wraps an asynchronously provided, non-null object {@code T}, synchronously
@@ -27,6 +27,7 @@
  *
  * @param <T> The type of the wrapped object.
  */
+@NullMarked
 public interface SyncOneshotSupplier<T> extends Supplier<T> {
     /**
      * Add a callback that's synchronously called when the object owned by this supplier is
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/SyncOneshotSupplierImpl.java b/tot/base/android/java/src/org/chromium/base/supplier/SyncOneshotSupplierImpl.java
index 287ad42..9e8b7c3 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/SyncOneshotSupplierImpl.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/SyncOneshotSupplierImpl.java
@@ -4,11 +4,10 @@
 
 package org.chromium.base.supplier;
 
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-
 import org.chromium.base.Callback;
 import org.chromium.base.ThreadUtils;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.ArrayList;
 
@@ -29,6 +28,7 @@
  *
  * @param <T> The type of the wrapped object.
  */
+@NullMarked
 public class SyncOneshotSupplierImpl<T> implements SyncOneshotSupplier<T> {
     private final ThreadUtils.ThreadChecker mThreadChecker = new ThreadUtils.ThreadChecker();
 
@@ -65,7 +65,7 @@
      *
      * @param object The object to supply.
      */
-    public void set(@NonNull T object) {
+    public void set(T object) {
         mThreadChecker.assertOnValidThread();
         assert mObject == null;
         assert object != null;
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/TransitiveObservableSupplier.java b/tot/base/android/java/src/org/chromium/base/supplier/TransitiveObservableSupplier.java
index 80b4107..db230c1 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/TransitiveObservableSupplier.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/TransitiveObservableSupplier.java
@@ -4,10 +4,10 @@
 
 package org.chromium.base.supplier;
 
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-
 import org.chromium.base.Callback;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.NullUnmarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.function.Function;
 
@@ -24,18 +24,16 @@
  * @param <P> The parent object that's holding a reference to the target.
  * @param <T> The target type that the client wants to observe.
  */
-public class TransitiveObservableSupplier<P, T> implements ObservableSupplier<T> {
+@NullMarked
+public class TransitiveObservableSupplier<P extends @Nullable Object, T extends @Nullable Object>
+        implements ObservableSupplier<T> {
     // Used to hold observers and current state. However the current value is only valid when there
     // are observers, otherwise is may be stale.
-    private final @NonNull ObservableSupplierImpl<T> mDelegateSupplier =
-            new ObservableSupplierImpl<>();
-
-    private final @NonNull Callback<P> mOnParentSupplierChangeCallback =
-            this::onParentSupplierChange;
-    private final @NonNull Callback<T> mOnTargetSupplierChangeCallback =
-            this::onTargetSupplierChange;
-    private final @NonNull ObservableSupplier<P> mParentSupplier;
-    private final @NonNull Function<P, ObservableSupplier<T>> mUnwrapFunction;
+    private final ObservableSupplierImpl<T> mDelegateSupplier = new ObservableSupplierImpl<>();
+    private final Callback<P> mOnParentSupplierChangeCallback = this::onParentSupplierChange;
+    private final Callback<T> mOnTargetSupplierChangeCallback = this::onTargetSupplierChange;
+    private final ObservableSupplier<P> mParentSupplier;
+    private final Function<P, ObservableSupplier<T>> mUnwrapFunction;
 
     // When this is set, then mOnTargetSupplierChangeCallback is an observer of the object
     // referenced by mCurrentTargetSupplier. When this value is changed, the observer must be
@@ -50,11 +48,12 @@
     }
 
     @Override
-    public T addObserver(Callback<T> obs) {
+    public @Nullable T addObserver(Callback<T> obs, @NotifyBehavior int behavior) {
         if (!mDelegateSupplier.hasObservers()) {
-            onParentSupplierChange(mParentSupplier.addObserver(mOnParentSupplierChangeCallback));
+            onParentSupplierChange(
+                    mParentSupplier.addSyncObserver(mOnParentSupplierChangeCallback));
         }
-        return mDelegateSupplier.addObserver(obs);
+        return mDelegateSupplier.addObserver(obs, behavior);
     }
 
     @Override
@@ -92,6 +91,7 @@
      * sure we keep our delegate supplier's value up to date, which is also what drives client
      * observations.
      */
+    @NullUnmarked // Needs to work where P is non-null or nullable.
     private void onParentSupplierChange(@Nullable P parentValue) {
         if (mCurrentTargetSupplier != null) {
             mCurrentTargetSupplier.removeObserver(mOnTargetSupplierChangeCallback);
@@ -101,20 +101,20 @@
         // remove our observer from it.
         mCurrentTargetSupplier = parentValue == null ? null : mUnwrapFunction.apply(parentValue);
 
-        if (mCurrentTargetSupplier == null) {
-            onTargetSupplierChange(null);
-        } else {
+        @Nullable T targetValue = null;
+        if (mCurrentTargetSupplier != null) {
             // While addObserver will call us if a value is already set, we do not want to depend on
             // that for two reasons. If there is no value set, we need to null out our supplier now.
             // And if there is a value set, we're going to get invoked asynchronously, which means
             // our delegate supplier could be in an intermediately incorrect state. By just setting
             // our delegate eagerly we avoid both problems.
-            onTargetSupplierChange(
-                    mCurrentTargetSupplier.addObserver(mOnTargetSupplierChangeCallback));
+            targetValue = mCurrentTargetSupplier.addSyncObserver(mOnTargetSupplierChangeCallback);
         }
+        onTargetSupplierChange(targetValue);
     }
 
-    private void onTargetSupplierChange(@Nullable T targetValue) {
+    @NullUnmarked // Needs to work where T is non-null or nullable.
+    private void onTargetSupplierChange(T targetValue) {
         mDelegateSupplier.set(targetValue);
     }
 }
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/UnownedUserDataSupplier.java b/tot/base/android/java/src/org/chromium/base/supplier/UnownedUserDataSupplier.java
index c11b78a..1c6a3c8 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/UnownedUserDataSupplier.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/UnownedUserDataSupplier.java
@@ -5,13 +5,13 @@
 package org.chromium.base.supplier;
 
 import androidx.annotation.CallSuper;
-import androidx.annotation.NonNull;
 
 import org.chromium.base.UnownedUserData;
 import org.chromium.base.UnownedUserDataHost;
 import org.chromium.base.UnownedUserDataKey;
 import org.chromium.base.lifetime.DestroyChecker;
 import org.chromium.base.lifetime.Destroyable;
+import org.chromium.build.annotations.NullMarked;
 
 /**
  * UnownedUserDataSupplier handles the combined lifecycle management for {@link UnownedUserData} and
@@ -42,6 +42,7 @@
  * @see UnownedUserDataKey for information about the type of key that is required.
  * @see UnownedUserData for the marker interface used for this type of data.
  */
+@NullMarked
 public abstract class UnownedUserDataSupplier<E> extends ObservableSupplierImpl<E>
         implements Destroyable, UnownedUserData {
     private final UnownedUserDataKey<UnownedUserDataSupplier<E>> mUudKey;
@@ -52,7 +53,7 @@
      * @param uudKey The {@link UnownedUserDataKey}, which is defined in subclasses.
      */
     protected UnownedUserDataSupplier(
-            @NonNull UnownedUserDataKey<? extends UnownedUserDataSupplier<E>> uudKey) {
+            UnownedUserDataKey<? extends UnownedUserDataSupplier<E>> uudKey) {
         mUudKey = (UnownedUserDataKey<UnownedUserDataSupplier<E>>) uudKey;
     }
 
@@ -60,7 +61,7 @@
      * Attach to the specified host.
      * @param host The host to attach the supplier to.
      */
-    public void attach(@NonNull UnownedUserDataHost host) {
+    public void attach(UnownedUserDataHost host) {
         mDestroyChecker.checkNotDestroyed();
         mUudKey.attachToHost(host, this);
     }
diff --git a/tot/base/android/java/src/org/chromium/base/supplier/UnwrapObservableSupplier.java b/tot/base/android/java/src/org/chromium/base/supplier/UnwrapObservableSupplier.java
index 79fc876..e69ee12 100644
--- a/tot/base/android/java/src/org/chromium/base/supplier/UnwrapObservableSupplier.java
+++ b/tot/base/android/java/src/org/chromium/base/supplier/UnwrapObservableSupplier.java
@@ -4,10 +4,9 @@
 
 package org.chromium.base.supplier;
 
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-
 import org.chromium.base.Callback;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.function.Function;
 
@@ -43,20 +42,20 @@
  * @param <P> The parent object that's holding the target value somehow.
  * @param <T> The target type that the client wants to observe.
  */
-public class UnwrapObservableSupplier<P, T> implements ObservableSupplier<T> {
-    private final @NonNull ObservableSupplierImpl<T> mDelegateSupplier =
-            new ObservableSupplierImpl<>();
-    private final @NonNull Callback<P> mOnParentSupplierChangeCallback =
-            this::onParentSupplierChange;
-    private final @NonNull ObservableSupplier<P> mParentSupplier;
-    private final @NonNull Function<P, T> mUnwrapFunction;
+@NullMarked
+public class UnwrapObservableSupplier<P extends @Nullable Object, T extends @Nullable Object>
+        implements ObservableSupplier<T> {
+    private final ObservableSupplierImpl<T> mDelegateSupplier = new ObservableSupplierImpl<>();
+    private final Callback<P> mOnParentSupplierChangeCallback = this::onParentSupplierChange;
+    private final ObservableSupplier<P> mParentSupplier;
+    private final Function<@Nullable P, T> mUnwrapFunction;
 
     /**
      * @param parentSupplier The parent observable supplier.
      * @param unwrapFunction Converts the parent value to target value. Should handle null values.
      */
     public UnwrapObservableSupplier(
-            @NonNull ObservableSupplier<P> parentSupplier, @NonNull Function<P, T> unwrapFunction) {
+            ObservableSupplier<P> parentSupplier, Function<@Nullable P, T> unwrapFunction) {
         mParentSupplier = parentSupplier;
         mUnwrapFunction = unwrapFunction;
     }
@@ -67,16 +66,16 @@
     }
 
     @Override
-    public T addObserver(Callback<T> obs) {
+    public @Nullable T addObserver(Callback<T> obs, @NotifyBehavior int behavior) {
         // Can use mDelegateSupplier.hasObservers() to tell if we are subscribed or not to
         // mParentSupplier. This is safe because we never expose outside callers, and completely
         // control when we add/remove observers to it.
         if (!mDelegateSupplier.hasObservers()) {
             // The value in mDelegateSupplier is stale or has never been set, and so we update it
             // by passing through the current parent value to our on change method.
-            onParentSupplierChange(mParentSupplier.addObserver(mOnParentSupplierChangeCallback));
+            mParentSupplier.addSyncObserverAndCallIfNonNull(mOnParentSupplierChangeCallback);
         }
-        return mDelegateSupplier.addObserver(obs);
+        return mDelegateSupplier.addObserver(obs, behavior);
     }
 
     @Override
diff --git a/tot/base/android/java/src/org/chromium/base/task/AsyncTask.java b/tot/base/android/java/src/org/chromium/base/task/AsyncTask.java
index f4666bf..11678bc 100644
--- a/tot/base/android/java/src/org/chromium/base/task/AsyncTask.java
+++ b/tot/base/android/java/src/org/chromium/base/task/AsyncTask.java
@@ -16,6 +16,8 @@
 import org.chromium.base.TraceEvent;
 import org.chromium.base.metrics.RecordHistogram;
 import org.chromium.build.annotations.DoNotInline;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -33,10 +35,12 @@
 /**
  * A Chromium version of android.os.AsyncTask.
  *
- * The API is quite close to Android's Oreo version, but with a number of things removed.
+ * <p>The API is quite close to Android's Oreo version, but with a number of things removed.
+ *
  * @param <Result> Return type of the background task.
  */
-public abstract class AsyncTask<Result> {
+@NullMarked
+public abstract class AsyncTask<Result extends @Nullable Object> {
     private static final String TAG = "AsyncTask";
 
     private static final String GET_STATUS_UMA_HISTOGRAM =
@@ -139,14 +143,14 @@
         mFuture = new NamedFutureTask(mWorker);
     }
 
-    private void postResultIfNotInvoked(Result result) {
+    private void postResultIfNotInvoked(@Nullable Result result) {
         final boolean wasTaskInvoked = mTaskInvoked.get();
         if (!wasTaskInvoked) {
             postResult(result);
         }
     }
 
-    private void postResult(Result result) {
+    private void postResult(@Nullable Result result) {
         // We check if this task is of a type which does not require post-execution.
         if (this instanceof BackgroundOnlyAsyncTask) {
             mStatus = Status.FINISHED;
@@ -202,16 +206,15 @@
     protected void onPreExecute() {}
 
     /**
-     * <p>Runs on the UI thread after {@link #doInBackground}. The
-     * specified result is the value returned by {@link #doInBackground}.</p>
+     * Runs on the UI thread after {@link #doInBackground}. The specified result is the value
+     * returned by {@link #doInBackground}.
      *
-     * <p>This method won't be invoked if the task was cancelled.</p>
+     * <p>This method won't be invoked if the task was cancelled.
      *
-     * <p> Must be overridden by subclasses. If a subclass doesn't need
-     * post-execution, is should extend BackgroundOnlyAsyncTask instead.
+     * <p>Must be overridden by subclasses. If a subclass doesn't need post-execution, is should
+     * extend BackgroundOnlyAsyncTask instead.
      *
      * @param result The result of the operation computed by {@link #doInBackground}.
-     *
      * @see #onPreExecute
      * @see #doInBackground
      * @see #onCancelled(Object)
@@ -221,22 +224,19 @@
     protected abstract void onPostExecute(Result result);
 
     /**
-     * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
-     * {@link #doInBackground()} has finished.</p>
+     * Runs on the UI thread after {@link #cancel(boolean)} is invoked and {@link #doInBackground()}
+     * has finished.
      *
-     * <p>The default implementation simply invokes {@link #onCancelled()} and
-     * ignores the result. If you write your own implementation, do not call
-     * <code>super.onCancelled(result)</code>.</p>
+     * <p>The default implementation simply invokes {@link #onCancelled()} and ignores the result.
+     * If you write your own implementation, do not call <code>super.onCancelled(result)</code>.
      *
-     * @param result The result, if any, computed in
-     *               {@link #doInBackground()}, can be null
-     *
+     * @param result The result, if any, computed in {@link #doInBackground()}, can be null
      * @see #cancel(boolean)
      * @see #isCancelled()
      */
     @SuppressWarnings({"UnusedParameters"})
     @MainThread
-    protected void onCancelled(Result result) {
+    protected void onCancelled(@Nullable Result result) {
         onCancelled();
     }
 
@@ -459,7 +459,8 @@
         return this;
     }
 
-    private void finish(Result result) {
+    @SuppressWarnings("NullAway") // onPostExecute is non-null when <Result> is non-null.
+    private void finish(@Nullable Result result) {
         if (isCancelled()) {
             onCancelled(result);
         } else {
diff --git a/tot/base/android/java/src/org/chromium/base/task/BackgroundOnlyAsyncTask.java b/tot/base/android/java/src/org/chromium/base/task/BackgroundOnlyAsyncTask.java
index 4ff2068..c69276b 100644
--- a/tot/base/android/java/src/org/chromium/base/task/BackgroundOnlyAsyncTask.java
+++ b/tot/base/android/java/src/org/chromium/base/task/BackgroundOnlyAsyncTask.java
@@ -4,17 +4,22 @@
 
 package org.chromium.base.task;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 /**
  * An AsyncTask which does not require post-execution.
  *
- * The addition of this class is only temporary with the eventual goal of
- * transitioning all such tasks to FutureTasks / Runnables.
+ * <p>The addition of this class is only temporary with the eventual goal of transitioning all such
+ * tasks to FutureTasks / Runnables.
  *
  * @param <Result> Return type of the background task.
  */
-public abstract class BackgroundOnlyAsyncTask<Result> extends AsyncTask<Result> {
+@NullMarked
+public abstract class BackgroundOnlyAsyncTask<Result extends @Nullable Object>
+        extends AsyncTask<Result> {
     @Override
-    protected final void onPostExecute(Result result) {
+    protected final void onPostExecute(@Nullable Result result) {
         // This method should never be executed for background-only tasks.
         assert false;
     }
diff --git a/tot/base/android/java/src/org/chromium/base/task/ChainedTasks.java b/tot/base/android/java/src/org/chromium/base/task/ChainedTasks.java
index d807e4b..4aaf737 100644
--- a/tot/base/android/java/src/org/chromium/base/task/ChainedTasks.java
+++ b/tot/base/android/java/src/org/chromium/base/task/ChainedTasks.java
@@ -7,6 +7,7 @@
 import android.util.Pair;
 
 import org.chromium.base.TraceEvent;
+import org.chromium.build.annotations.NullMarked;
 
 import java.util.LinkedList;
 
@@ -24,6 +25,7 @@
  * may run with arbitrary TaskTraits, unless tasks are coalesced, in which case all tasks must run
  * on the same thread.
  */
+@NullMarked
 public class ChainedTasks {
     private final LinkedList<Pair<Integer, Runnable>> mTasks = new LinkedList<>();
 
diff --git a/tot/base/android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java b/tot/base/android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java
index e191d24..1f7f5ca 100644
--- a/tot/base/android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java
+++ b/tot/base/android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java
@@ -8,6 +8,8 @@
 
 import androidx.annotation.VisibleForTesting;
 
+import org.chromium.build.annotations.NullMarked;
+
 import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.ArrayBlockingQueue;
@@ -18,6 +20,7 @@
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
+@NullMarked
 class ChromeThreadPoolExecutor extends ThreadPoolExecutor {
     private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
 
diff --git a/tot/base/android/java/src/org/chromium/base/task/PostTask.java b/tot/base/android/java/src/org/chromium/base/task/PostTask.java
index 361ca8b..91af5dd 100644
--- a/tot/base/android/java/src/org/chromium/base/task/PostTask.java
+++ b/tot/base/android/java/src/org/chromium/base/task/PostTask.java
@@ -4,7 +4,7 @@
 
 package org.chromium.base.task;
 
-import androidx.annotation.Nullable;
+import static org.chromium.build.NullUtil.assumeNonNull;
 
 import org.jni_zero.CalledByNative;
 import org.jni_zero.JNINamespace;
@@ -14,6 +14,8 @@
 import org.chromium.base.ResettersForTesting;
 import org.chromium.base.ThreadUtils;
 import org.chromium.build.BuildConfig;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -29,6 +31,7 @@
  * initialization, but task prioritization is extremely limited. Once the native scheduler is ready,
  * tasks will be migrated over.
  */
+@NullMarked
 @JNINamespace("base")
 public class PostTask {
     private static final String TAG = "PostTask";
@@ -36,7 +39,7 @@
     private static final Object sPreNativeTaskRunnerLock = new Object();
 
     @GuardedBy("sPreNativeTaskRunnerLock")
-    private static List<TaskRunnerImpl> sPreNativeTaskRunners = new ArrayList<>();
+    private static @Nullable List<TaskRunnerImpl> sPreNativeTaskRunners = new ArrayList<>();
 
     // Volatile is sufficient for synchronization here since we never need to read-write. This is a
     // one-way switch (outside of testing) and volatile makes writes to it immediately visible to
@@ -44,8 +47,8 @@
     private static volatile boolean sNativeInitialized;
     private static ChromeThreadPoolExecutor sPrenativeThreadPoolExecutor =
             new ChromeThreadPoolExecutor();
-    private static volatile Executor sPrenativeThreadPoolExecutorForTesting;
-    private static final ThreadLocal<TaskOriginException> sTaskOrigin =
+    private static volatile @Nullable Executor sPrenativeThreadPoolExecutorForTesting;
+    private static final @Nullable ThreadLocal<TaskOriginException> sTaskOrigin =
             ENABLE_TASK_ORIGINS ? new ThreadLocal<>() : null;
     private static final TaskRunner[] sTraitsToRunnerMap =
             new TaskRunner[TaskTraits.UI_TRAITS_END + 1];
@@ -73,13 +76,14 @@
 
         @Override
         public void run() {
-            sTaskOrigin.set(mTaskOrigin);
+            var taskOrigin = assumeNonNull(sTaskOrigin);
+            taskOrigin.set(mTaskOrigin);
             try {
                 mWrappedRunnable.run();
             } catch (Throwable t) {
                 JavaUtils.throwUnchecked(maybeAddTaskOrigin(t));
             } finally {
-                sTaskOrigin.remove();
+                taskOrigin.remove();
             }
         }
     }
@@ -166,7 +170,8 @@
      * @param c The task to be run with the specified traits.
      * @return The result of the callable
      */
-    public static <T> T runSynchronously(@TaskTraits int taskTraits, Callable<T> c) {
+    public static <T extends @Nullable Object> T runSynchronously(
+            @TaskTraits int taskTraits, Callable<T> c) {
         return runSynchronouslyInternal(taskTraits, new FutureTask<T>(c));
     }
 
@@ -184,7 +189,8 @@
         runSynchronouslyInternal(taskTraits, new FutureTask<Void>(r, null));
     }
 
-    private static <T> T runSynchronouslyInternal(@TaskTraits int taskTraits, FutureTask<T> task) {
+    private static <T extends @Nullable Object> T runSynchronouslyInternal(
+            @TaskTraits int taskTraits, FutureTask<T> task) {
         // Ensure no task origin "caused by" is added, since we are wrapping in a RuntimeException
         // anyways.
         Runnable r = ENABLE_TASK_ORIGINS ? populateTaskOrigin(null, task) : task;
@@ -220,7 +226,11 @@
     }
 
     public static @Nullable Exception getTaskOrigin() {
-        return ENABLE_TASK_ORIGINS ? sTaskOrigin.get() : null;
+        if (ENABLE_TASK_ORIGINS) {
+            assumeNonNull(sTaskOrigin);
+            return sTaskOrigin.get();
+        }
+        return null;
     }
 
     /**
@@ -281,6 +291,7 @@
         sNativeInitialized = true;
         List<TaskRunnerImpl> preNativeTaskRunners;
         synchronized (sPreNativeTaskRunnerLock) {
+            assert sPreNativeTaskRunners != null;
             preNativeTaskRunners = sPreNativeTaskRunners;
             sPreNativeTaskRunners = null;
         }
diff --git a/tot/base/android/java/src/org/chromium/base/task/SequencedTaskRunner.java b/tot/base/android/java/src/org/chromium/base/task/SequencedTaskRunner.java
index d8b9c46..16d07e9 100644
--- a/tot/base/android/java/src/org/chromium/base/task/SequencedTaskRunner.java
+++ b/tot/base/android/java/src/org/chromium/base/task/SequencedTaskRunner.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base.task;
 
+import org.chromium.build.annotations.NullMarked;
+
 /**
  * Tasks posted will be run in order with respect to this sequence, but they may be executed
  * on arbitrary threads. Unless specified otherwise by the provider of a given
@@ -11,4 +13,5 @@
  * guarantees w.r.t. other SequencedTaskRunners. They have destroy() automatically called whenever
  * they go empty, so calling destroy() on them is not needed.
  */
+@NullMarked
 public interface SequencedTaskRunner extends TaskRunner {}
diff --git a/tot/base/android/java/src/org/chromium/base/task/SequencedTaskRunnerImpl.java b/tot/base/android/java/src/org/chromium/base/task/SequencedTaskRunnerImpl.java
index ce5fede..e2ccbe9 100644
--- a/tot/base/android/java/src/org/chromium/base/task/SequencedTaskRunnerImpl.java
+++ b/tot/base/android/java/src/org/chromium/base/task/SequencedTaskRunnerImpl.java
@@ -4,12 +4,15 @@
 
 package org.chromium.base.task;
 
+import org.chromium.build.annotations.NullMarked;
+
 import java.util.concurrent.atomic.AtomicInteger;
 
 /**
  * Implementation of the abstract class {@link SequencedTaskRunner}. Uses AsyncTasks until
  * native APIs are available.
  */
+@NullMarked
 public class SequencedTaskRunnerImpl extends TaskRunnerImpl implements SequencedTaskRunner {
     private AtomicInteger mPendingTasks = new AtomicInteger();
 
diff --git a/tot/base/android/java/src/org/chromium/base/task/SerialExecutor.java b/tot/base/android/java/src/org/chromium/base/task/SerialExecutor.java
index c43acee..f1b67a6 100644
--- a/tot/base/android/java/src/org/chromium/base/task/SerialExecutor.java
+++ b/tot/base/android/java/src/org/chromium/base/task/SerialExecutor.java
@@ -4,12 +4,16 @@
 
 package org.chromium.base.task;
 
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
+
 import java.util.ArrayDeque;
 import java.util.concurrent.Executor;
 
+@NullMarked
 class SerialExecutor implements Executor {
     final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
-    Runnable mActive;
+    @Nullable Runnable mActive;
 
     @Override
     public synchronized void execute(final Runnable r) {
diff --git a/tot/base/android/java/src/org/chromium/base/task/TaskOriginException.java b/tot/base/android/java/src/org/chromium/base/task/TaskOriginException.java
index 3546621..82d2389 100644
--- a/tot/base/android/java/src/org/chromium/base/task/TaskOriginException.java
+++ b/tot/base/android/java/src/org/chromium/base/task/TaskOriginException.java
@@ -4,7 +4,10 @@
 
 package org.chromium.base.task;
 
+import org.chromium.build.annotations.NullMarked;
+
 /** Used to capture stacks of where tasks are posted from. */
+@NullMarked
 class TaskOriginException extends Exception {
 
     TaskOriginException() {
diff --git a/tot/base/android/java/src/org/chromium/base/task/TaskRunner.java b/tot/base/android/java/src/org/chromium/base/task/TaskRunner.java
index 763f281..f18143d 100644
--- a/tot/base/android/java/src/org/chromium/base/task/TaskRunner.java
+++ b/tot/base/android/java/src/org/chromium/base/task/TaskRunner.java
@@ -4,6 +4,8 @@
 
 package org.chromium.base.task;
 
+import org.chromium.build.annotations.NullMarked;
+
 import java.util.concurrent.Executor;
 
 /**
@@ -11,6 +13,7 @@
  * be backed by an {@link android.os.Handler} or the java thread pool. The TaskQueue interface
  * provides no guarantee over the order or the thread on which the task will be executed.
  */
+@NullMarked
 public interface TaskRunner extends Executor {
 
     /**
diff --git a/tot/base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java b/tot/base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java
index d8ebd3e..3f26000 100644
--- a/tot/base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java
+++ b/tot/base/android/java/src/org/chromium/base/task/TaskRunnerImpl.java
@@ -4,22 +4,28 @@
 
 package org.chromium.base.task;
 
+import static org.chromium.build.NullUtil.assumeNonNull;
+
 import android.util.Pair;
 
-import androidx.annotation.Nullable;
+import androidx.annotation.VisibleForTesting;
 
+import org.jni_zero.CalledByNative;
 import org.jni_zero.JNINamespace;
-import org.jni_zero.JniType;
 import org.jni_zero.NativeMethods;
 
 import org.chromium.base.TraceEvent;
+import org.chromium.build.annotations.NullMarked;
+import org.chromium.build.annotations.Nullable;
 
 import java.lang.ref.ReferenceQueue;
 import java.lang.ref.WeakReference;
 import java.util.ArrayDeque;
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.Queue;
 import java.util.Set;
 
@@ -29,6 +35,7 @@
  * Implementation of the abstract class {@link TaskRunnerImpl}. Uses AsyncTasks until native APIs
  * are available.
  */
+@NullMarked
 @JNINamespace("base")
 public class TaskRunnerImpl implements TaskRunner {
 
@@ -36,6 +43,20 @@
     // cleared.
     private static final ReferenceQueue<Object> sQueue = new ReferenceQueue<>();
 
+    // Track tasks in java to prevent overflowing the JNI global ref table (crbug.com/369845089).
+    // Table which ideally covers most immediate posted tasks so they don't have to do map
+    // operations.
+    private static Object sPendingTaskLock = new Object();
+
+    @GuardedBy("sPendingTaskLock")
+    private static final @Nullable Runnable[] sPendingTaskTable = new Runnable[50];
+
+    @GuardedBy("sPendingTaskLock")
+    private static int sPendingTaskMapNextIndex = sPendingTaskTable.length;
+
+    @GuardedBy("sPendingTaskLock")
+    private static final Map<Integer, Runnable> sPendingTaskMap = new HashMap<>();
+
     // Holds a strong reference to the pending TaskRunnerCleaners so they don't get GC'd before the
     // TaskRunnerImpl they're weakly referencing does.
     @GuardedBy("sCleaners")
@@ -56,21 +77,20 @@
     @GuardedBy("mPreNativeTaskLock")
     private boolean mDidOneTimeInitialization;
 
-    @Nullable
     @GuardedBy("mPreNativeTaskLock")
-    private Queue<Runnable> mPreNativeTasks;
+    private @Nullable Queue<Runnable> mPreNativeTasks;
 
-    @Nullable
     @GuardedBy("mPreNativeTaskLock")
-    private List<Pair<Runnable, Long>> mPreNativeDelayedTasks;
+    private @Nullable List<Pair<Runnable, Long>> mPreNativeDelayedTasks;
 
     int clearTaskQueueForTesting() {
         int taskCount = 0;
         synchronized (mPreNativeTaskLock) {
             if (mPreNativeTasks != null) {
-                taskCount = mPreNativeTasks.size() + mPreNativeDelayedTasks.size();
+                var preNativeDelayedTasks = assumeNonNull(mPreNativeDelayedTasks);
+                taskCount = mPreNativeTasks.size() + preNativeDelayedTasks.size();
                 mPreNativeTasks.clear();
-                mPreNativeDelayedTasks.clear();
+                preNativeDelayedTasks.clear();
             }
         }
         return taskCount;
@@ -153,17 +173,13 @@
         }
         // Lock-free path when native is initialized.
         if (mNativeTaskRunnerAndroid != 0) {
-            TaskRunnerImplJni.get()
-                    .postDelayedTask(
-                            mNativeTaskRunnerAndroid, task, delay, task.getClass().getName());
+            queueDelayedTaskToNative(mNativeTaskRunnerAndroid, task, delay);
             return;
         }
         synchronized (mPreNativeTaskLock) {
             oneTimeInitialization();
             if (mNativeTaskRunnerAndroid != 0) {
-                TaskRunnerImplJni.get()
-                        .postDelayedTask(
-                                mNativeTaskRunnerAndroid, task, delay, task.getClass().getName());
+                queueDelayedTaskToNative(mNativeTaskRunnerAndroid, task, delay);
                 return;
             }
             // We don't expect a whole lot of these, if that changes consider pooling them.
@@ -171,11 +187,11 @@
             // pre-native task runner. Tasks scheduled to run with a delay will
             // wait until the native task runner is initialised.
             if (delay == 0) {
-                mPreNativeTasks.add(task);
+                assumeNonNull(mPreNativeTasks).add(task);
                 schedulePreNativeTask();
             } else if (!schedulePreNativeDelayedTask(task, delay)) {
                 Pair<Runnable, Long> preNativeDelayedTask = new Pair<>(task, delay);
-                mPreNativeDelayedTasks.add(preNativeDelayedTask);
+                assumeNonNull(mPreNativeDelayedTasks).add(preNativeDelayedTask);
             }
         }
     }
@@ -240,20 +256,13 @@
         synchronized (mPreNativeTaskLock) {
             if (mPreNativeTasks != null) {
                 for (Runnable task : mPreNativeTasks) {
-                    TaskRunnerImplJni.get()
-                            .postDelayedTask(
-                                    nativeTaskRunnerAndroid, task, 0, task.getClass().getName());
+                    queueDelayedTaskToNative(nativeTaskRunnerAndroid, task, 0);
                 }
                 mPreNativeTasks = null;
             }
             if (mPreNativeDelayedTasks != null) {
                 for (Pair<Runnable, Long> task : mPreNativeDelayedTasks) {
-                    TaskRunnerImplJni.get()
-                            .postDelayedTask(
-                                    nativeTaskRunnerAndroid,
-                                    task.first,
-                                    task.second,
-                                    task.getClass().getName());
+                    queueDelayedTaskToNative(nativeTaskRunnerAndroid, task.first, task.second);
                 }
                 mPreNativeDelayedTasks = null;
             }
@@ -273,16 +282,58 @@
         destroyGarbageCollectedTaskRunners();
     }
 
+    private static void queueDelayedTaskToNative(
+            long nativeTaskRunnerAndroid, Runnable task, long delay) {
+        // If there's no delay, then try to store it in the table. Otherwise use the map.
+        int taskIndex = queueTask(task, /* useTable= */ delay == 0);
+        TaskRunnerImplJni.get().postDelayedTask(nativeTaskRunnerAndroid, delay, taskIndex);
+    }
+
+    @CalledByNative
+    @VisibleForTesting
+    static void runTask(int taskIndex) {
+        Runnable task = dequeueTask(taskIndex);
+        task.run();
+    }
+
+    private static int queueTask(Runnable task, boolean useTable) {
+        synchronized (sPendingTaskLock) {
+            for (int i = 0; useTable && i < sPendingTaskTable.length; i++) {
+                if (sPendingTaskTable[i] == null) {
+                    sPendingTaskTable[i] = task;
+                    return i;
+                }
+            }
+
+            int taskIndex = sPendingTaskMapNextIndex++;
+            // Overflow is highly unlikely here.
+            assert taskIndex < Integer.MAX_VALUE;
+            sPendingTaskMap.put(taskIndex, task);
+
+            return taskIndex;
+        }
+    }
+
+    private static Runnable dequeueTask(int taskIndex) {
+        synchronized (sPendingTaskLock) {
+            Runnable task;
+            if (taskIndex < sPendingTaskTable.length) {
+                task = sPendingTaskTable[taskIndex];
+                sPendingTaskTable[taskIndex] = null;
+            } else {
+                task = sPendingTaskMap.remove(taskIndex);
+            }
+            assert task != null : "Task at index " + taskIndex + " was null.";
+            return task;
+        }
+    }
+
     @NativeMethods
     interface Natives {
         long init(@TaskRunnerType int taskRunnerType, @TaskTraits int taskTraits);
 
         void destroy(long nativeTaskRunnerAndroid);
 
-        void postDelayedTask(
-                long nativeTaskRunnerAndroid,
-                Runnable task,
-                long delay,
-                @JniType("std::string") String runnableClassName);
+        void postDelayedTask(long nativeTaskRunnerAndroid, long delay, int taskIndex);
     }
 }
diff --git a/tot/base/android/java/src/org/chromium/base/task/UiThreadTaskRunnerImpl.java b/tot/base/android/java/src/org/chromium/base/task/UiThreadTaskRunnerImpl.java
index 4f4b41f..5945d9f 100644
--- a/tot/base/android/java/src/org/chromium/base/task/UiThreadTaskRunnerImpl.java
+++ b/tot/base/android/java/src/org/chromium/base/task/UiThreadTaskRunnerImpl.java
@@ -7,8 +7,10 @@
 import org.jni_zero.JNINamespace;
 
 import org.chromium.base.ThreadUtils;
+import org.chromium.build.annotations.NullMarked;
 
 /** TaskRunner for UI thread. */
+@NullMarked
 @JNINamespace("base")
 public class UiThreadTaskRunnerImpl extends TaskRunnerImpl implements SequencedTaskRunner {
     /**
diff --git a/tot/base/android/java_exception_reporter.cc b/tot/base/android/java_exception_reporter.cc
index 90ef9b9..dace51c 100644
--- a/tot/base/android/java_exception_reporter.cc
+++ b/tot/base/android/java_exception_reporter.cc
@@ -11,16 +11,10 @@
 #include "base/functional/callback.h"
 #include "base/lazy_instance.h"
 #include "base/logging.h"
-#include "build/robolectric_buildflags.h"
 
 // Must come after all headers that specialize FromJniType() / ToJniType().
-#if BUILDFLAG(IS_ROBOLECTRIC)
-#include "base/base_robolectric_jni/JavaExceptionReporter_jni.h"  // nogncheck
-#else
-#include "base/base_jni/JavaExceptionReporter_jni.h"
-#endif
+#include "base/base_minimal_jni/JavaExceptionReporter_jni.h"
 
-using jni_zero::JavaParamRef;
 using jni_zero::JavaRef;
 
 namespace base {
@@ -83,7 +77,7 @@
 void JNI_JavaExceptionReporter_ReportJavaException(
     JNIEnv* env,
     jboolean crash_after_report,
-    const JavaParamRef<jthrowable>& e) {
+    const JavaRef<jthrowable>& e) {
   std::string exception_info = base::android::GetJavaExceptionInfo(env, e);
   bool should_report_exception = g_java_exception_filter.Get().Run(e);
   if (should_report_exception) {
@@ -108,3 +102,5 @@
 
 }  // namespace android
 }  // namespace base
+
+DEFINE_JNI_FOR_JavaExceptionReporter()
diff --git a/tot/base/android/java_handler_thread.cc b/tot/base/android/java_handler_thread.cc
index 93c48f6..4ecea04 100644
--- a/tot/base/android/java_handler_thread.cc
+++ b/tot/base/android/java_handler_thread.cc
@@ -81,14 +81,14 @@
   Java_JavaHandlerThread_joinThread(env, java_thread_);
 }
 
-void JavaHandlerThread::InitializeThread(JNIEnv* env,
-                                         jlong event) {
+void JavaHandlerThread::InitializeThread(JNIEnv* env, jlong event) {
   base::ThreadIdNameManager::GetInstance()->RegisterThread(
       base::PlatformThread::CurrentHandle().platform_handle(),
       base::PlatformThread::CurrentId());
 
-  if (name_)
+  if (name_) {
     PlatformThread::SetName(name_);
+  }
 
   thread_id_ = base::PlatformThread::CurrentId();
   state_ = std::make_unique<State>();
@@ -178,5 +178,5 @@
 
 JavaHandlerThread::State::~State() = default;
 
-} // namespace android
-} // namespace base
+}  // namespace android
+}  // namespace base
diff --git a/tot/base/android/java_handler_thread.h b/tot/base/android/java_handler_thread.h
index 197db23..4c77362 100644
--- a/tot/base/android/java_handler_thread.h
+++ b/tot/base/android/java_handler_thread.h
@@ -52,8 +52,7 @@
 
   // Called from java on the newly created thread.
   // Start() will not return before this methods has finished.
-  void InitializeThread(JNIEnv* env,
-                        jlong event);
+  void InitializeThread(JNIEnv* env, jlong event);
   // Called from java on this thread.
   void OnLooperStopped(JNIEnv* env);
 
diff --git a/tot/base/android/javatests/src/org/chromium/base/CommandLineTest.java b/tot/base/android/javatests/src/org/chromium/base/CommandLineTest.java
index 7812120..53ad517 100644
--- a/tot/base/android/javatests/src/org/chromium/base/CommandLineTest.java
+++ b/tot/base/android/javatests/src/org/chromium/base/CommandLineTest.java
@@ -50,9 +50,9 @@
     }
 
     void loadJni() {
-        Assert.assertFalse(CommandLine.isNativeImplementationForTesting());
+        Assert.assertFalse(CommandLine.getInstance().hasSwitchedToNative());
         LibraryLoader.getInstance().ensureInitialized();
-        Assert.assertTrue(CommandLine.isNativeImplementationForTesting());
+        Assert.assertTrue(CommandLine.getInstance().hasSwitchedToNative());
     }
 
     void checkInitSwitches() {
diff --git a/tot/base/android/javatests/src/org/chromium/base/IntentUtilsTest.java b/tot/base/android/javatests/src/org/chromium/base/IntentUtilsTest.java
index 0b9dfcd..9fc4d39 100644
--- a/tot/base/android/javatests/src/org/chromium/base/IntentUtilsTest.java
+++ b/tot/base/android/javatests/src/org/chromium/base/IntentUtilsTest.java
@@ -7,20 +7,13 @@
 import static org.junit.Assert.assertEquals;
 
 import android.content.ComponentName;
-import android.content.Context;
 import android.content.Intent;
 import android.os.Bundle;
 
 import androidx.test.filters.SmallTest;
 
-import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnit;
-import org.mockito.junit.MockitoRule;
-import org.mockito.quality.Strictness;
 
 import org.chromium.base.test.BaseJUnit4ClassRunner;
 import org.chromium.base.test.util.Batch;
@@ -30,14 +23,10 @@
 @RunWith(BaseJUnit4ClassRunner.class)
 @Batch(Batch.UNIT_TESTS)
 public class IntentUtilsTest {
-    @Mock private Context mContext;
-
-    @Rule public MockitoRule mMockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
-
     private void assertTargetsSelf(boolean targetsSelf, Intent intent, boolean expectAssertion) {
         boolean asserted = false;
         try {
-            assertEquals(targetsSelf, IntentUtils.intentTargetsSelf(mContext, intent));
+            assertEquals(targetsSelf, IntentUtils.intentTargetsSelf(intent));
         } catch (AssertionError e) {
             asserted = true;
             if (!expectAssertion) throw e;
@@ -48,10 +37,12 @@
     @Test
     @SmallTest
     public void testIntentTargetsSelf() {
-        String packageName = "package.name";
-        Mockito.when(mContext.getPackageName()).thenReturn(packageName);
+        String packageName = BuildInfo.getInstance().hostPackageName;
         assertTargetsSelf(false, new Intent(), false);
-        assertTargetsSelf(true, new Intent(mContext, IntentUtilsTest.class), false);
+        assertTargetsSelf(
+                true,
+                new Intent(ContextUtils.getApplicationContext(), IntentUtilsTest.class),
+                false);
 
         Intent intent = new Intent();
         intent.setComponent(new ComponentName(packageName, ""));
diff --git a/tot/base/android/javatests/src/org/chromium/base/library_loader/EarlyNativeTest.java b/tot/base/android/javatests/src/org/chromium/base/library_loader/EarlyNativeTest.java
index 14f67a3..e7d104e 100644
--- a/tot/base/android/javatests/src/org/chromium/base/library_loader/EarlyNativeTest.java
+++ b/tot/base/android/javatests/src/org/chromium/base/library_loader/EarlyNativeTest.java
@@ -7,7 +7,6 @@
 import androidx.test.filters.SmallTest;
 
 import org.jni_zero.JNINamespace;
-import org.jni_zero.NativeLibraryLoadedStatus;
 import org.jni_zero.NativeMethods;
 import org.junit.After;
 import org.junit.Assert;
@@ -18,7 +17,6 @@
 import org.chromium.base.test.BaseJUnit4ClassRunner;
 import org.chromium.base.test.util.Batch;
 import org.chromium.base.test.util.CallbackHelper;
-import org.chromium.build.BuildConfig;
 
 /** Tests for early JNI initialization. */
 @RunWith(BaseJUnit4ClassRunner.class)
@@ -67,31 +65,4 @@
         LibraryLoader.getInstance().ensureInitialized();
         Assert.assertTrue(LibraryLoader.getInstance().isInitialized());
     }
-
-    @Test
-    @SmallTest
-    public void testNativeMethodsReadyAfterLibraryInitialized() {
-        // Test is a no-op if DCHECK isn't on.
-        if (!BuildConfig.ENABLE_ASSERTS) return;
-
-        Assert.assertFalse(
-                NativeLibraryLoadedStatus.getProviderForTesting().areNativeMethodsReady());
-
-        LibraryLoader.getInstance().ensureInitialized();
-        Assert.assertTrue(
-                NativeLibraryLoadedStatus.getProviderForTesting().areNativeMethodsReady());
-    }
-
-    @Test
-    @SmallTest
-    public void testNativeMethodsNotReadyThrows() {
-        // Test is a no-op if dcheck isn't on.
-        if (!BuildConfig.ENABLE_ASSERTS) return;
-
-        try {
-            EarlyNativeTestJni.get().isCommandLineInitialized();
-            Assert.fail("Using JNI before the library is loaded should throw an exception.");
-        } catch (NativeLibraryLoadedStatus.NativeNotLoadedException e) {
-        }
-    }
 }
diff --git a/tot/base/android/jni_android.cc b/tot/base/android/jni_android.cc
index 17f8034..32df13c 100644
--- a/tot/base/android/jni_android.cc
+++ b/tot/base/android/jni_android.cc
@@ -19,11 +19,8 @@
 #include "build/robolectric_buildflags.h"
 #include "third_party/jni_zero/jni_zero.h"
 
-#if BUILDFLAG(IS_ROBOLECTRIC)
-#include "base/base_robolectric_jni/JniAndroid_jni.h"  // nogncheck
-#else
-#include "base/base_jni/JniAndroid_jni.h"
-#endif
+// Must come after all headers that specialize FromJniType() / ToJniType().
+#include "base/base_minimal_jni/JniAndroid_jni.h"
 
 namespace base {
 namespace android {
@@ -112,7 +109,6 @@
   DCHECK(g_out_of_memory_error_class);
 }
 
-
 void CheckException(JNIEnv* env) {
   if (!jni_zero::HasException(env)) {
     return;
@@ -204,8 +200,7 @@
   LOG(ERROR) << "Native stack trace:" << std::endl << native_stack_trace;
 
   ScopedJavaLocalRef<jthrowable> secondary_exception =
-      Java_JniAndroid_handleException(
-          env, throwable, ConvertUTF8ToJavaString(env, native_stack_trace));
+      Java_JniAndroid_handleException(env, throwable, native_stack_trace);
 
   // Ideally handleException() should have terminated the process and we should
   // not get here. This can happen in the case of OutOfMemoryError or if the
@@ -227,11 +222,11 @@
 
 std::string GetJavaExceptionInfo(JNIEnv* env,
                                  const JavaRef<jthrowable>& throwable) {
-  ScopedJavaLocalRef<jstring> sanitized_exception_string =
+  std::string sanitized_exception_string =
       Java_JniAndroid_sanitizedStacktraceForUnhandledException(env, throwable);
   // Returns null when PiiElider results in an OutOfMemoryError.
-  return sanitized_exception_string
-             ? ConvertJavaStringToUTF8(sanitized_exception_string)
+  return !sanitized_exception_string.empty()
+             ? sanitized_exception_string
              : kOomInGetJavaExceptionInfoMessage;
 }
 
@@ -270,3 +265,5 @@
 
 }  // namespace android
 }  // namespace base
+
+DEFINE_JNI_FOR_JniAndroid()
diff --git a/tot/base/android/jni_android.h b/tot/base/android/jni_android.h
index 428255b..1e77223 100644
--- a/tot/base/android/jni_android.h
+++ b/tot/base/android/jni_android.h
@@ -23,7 +23,7 @@
 namespace android {
 
 // Used to mark symbols to be exported in a shared library's symbol table.
-#define JNI_EXPORT __attribute__ ((visibility("default")))
+#define JNI_EXPORT __attribute__((visibility("default")))
 
 // Contains the registration method information for initializing JNI bindings.
 struct RegistrationMethod {
@@ -91,7 +91,6 @@
   return jni_zero::GetClass(env, class_name);
 }
 
-
 // Returns true if an exception is pending in the provided JNIEnv*.
 inline bool HasException(JNIEnv* env) {
   return jni_zero::HasException(env);
diff --git a/tot/base/android/jni_android_unittest.cc b/tot/base/android/jni_android_unittest.cc
index 6576f4a..81690f4 100644
--- a/tot/base/android/jni_android_unittest.cc
+++ b/tot/base/android/jni_android_unittest.cc
@@ -89,12 +89,9 @@
 
 std::atomic<jmethodID> g_atomic_id(nullptr);
 int LazyMethodIDCall(JNIEnv* env, jclass clazz, int p) {
-  jmethodID id = base::android::MethodID::LazyGet<
-      base::android::MethodID::TYPE_STATIC>(
-      env, clazz,
-      "abs",
-      "(I)I",
-      &g_atomic_id);
+  jmethodID id =
+      base::android::MethodID::LazyGet<base::android::MethodID::TYPE_STATIC>(
+          env, clazz, "abs", "(I)I", &g_atomic_id);
 
   return env->CallStaticIntMethod(clazz, id, p);
 }
@@ -110,23 +107,25 @@
   ScopedJavaLocalRef<jclass> clazz(GetClass(env, "java/lang/Math"));
   base::Time start_lazy = base::Time::Now();
   int o = 0;
-  for (int i = 0; i < 1024; ++i)
+  for (int i = 0; i < 1024; ++i) {
     o += LazyMethodIDCall(env, clazz.obj(), i);
+  }
   base::Time end_lazy = base::Time::Now();
 
   jmethodID id = g_atomic_id;
   base::Time start = base::Time::Now();
-  for (int i = 0; i < 1024; ++i)
+  for (int i = 0; i < 1024; ++i) {
     o += MethodIDCall(env, clazz.obj(), id, i);
+  }
   base::Time end = base::Time::Now();
 
   // On a Galaxy Nexus, results were in the range of:
   // JNI LazyMethodIDCall (us) 1984
   // JNI MethodIDCall (us) 1861
-  LOG(ERROR) << "JNI LazyMethodIDCall (us) " <<
-      base::TimeDelta(end_lazy - start_lazy).InMicroseconds();
-  LOG(ERROR) << "JNI MethodIDCall (us) " <<
-      base::TimeDelta(end - start).InMicroseconds();
+  LOG(ERROR) << "JNI LazyMethodIDCall (us) "
+             << base::TimeDelta(end_lazy - start_lazy).InMicroseconds();
+  LOG(ERROR) << "JNI MethodIDCall (us) "
+             << base::TimeDelta(end - start).InMicroseconds();
   LOG(ERROR) << "JNI " << o;
 }
 
diff --git a/tot/base/android/jni_array.cc b/tot/base/android/jni_array.cc
index 7067dfa..a53ad8b 100644
--- a/tot/base/android/jni_array.cc
+++ b/tot/base/android/jni_array.cc
@@ -299,8 +299,9 @@
                                          const JavaRef<jobjectArray>& array,
                                          std::vector<std::u16string>* out) {
   DCHECK(out);
-  if (!array)
+  if (!array) {
     return;
+  }
   size_t len = SafeGetArrayLength(env, array);
   if (!len) {
     return;
@@ -319,8 +320,9 @@
                                          const JavaRef<jobjectArray>& array,
                                          std::vector<std::string>* out) {
   DCHECK(out);
-  if (!array)
+  if (!array) {
     return;
+  }
   size_t len = SafeGetArrayLength(env, array);
   if (!len) {
     return;
@@ -339,8 +341,9 @@
                                      const JavaRef<jbyteArray>& byte_array,
                                      std::vector<uint8_t>* out) {
   DCHECK(out);
-  if (!byte_array)
+  if (!byte_array) {
     return;
+  }
   size_t len = SafeGetArrayLength(env, byte_array);
   if (!len) {
     return;
@@ -394,8 +397,9 @@
                                   const JavaRef<jbooleanArray>& boolean_array,
                                   std::vector<bool>* out) {
   DCHECK(out);
-  if (!boolean_array)
+  if (!boolean_array) {
     return;
+  }
   size_t len = SafeGetArrayLength(env, boolean_array);
   out->resize(len);
   if (!len) {
@@ -421,8 +425,9 @@
   DCHECK(out);
   size_t len = SafeGetArrayLength(env, int_array);
   out->resize(len);
-  if (!len)
+  if (!len) {
     return;
+  }
   env->GetIntArrayRegion(int_array.obj(), jsize{0}, checked_cast<jsize>(len),
                          out->data());
 }
@@ -443,8 +448,9 @@
   DCHECK(out);
   size_t len = SafeGetArrayLength(env, long_array);
   out->resize(len);
-  if (!len)
+  if (!len) {
     return;
+  }
   env->GetLongArrayRegion(long_array.obj(), jsize{0}, checked_cast<jsize>(len),
                           out->data());
 }
@@ -455,8 +461,9 @@
   DCHECK(out);
   size_t len = SafeGetArrayLength(env, float_array);
   out->resize(len);
-  if (!len)
+  if (!len) {
     return;
+  }
   env->GetFloatArrayRegion(float_array.obj(), jsize{0},
                            checked_cast<jsize>(len), out->data());
 }
@@ -467,8 +474,9 @@
   DCHECK(out);
   size_t len = SafeGetArrayLength(env, double_array);
   out->resize(len);
-  if (!len)
+  if (!len) {
     return;
+  }
   env->GetDoubleArrayRegion(double_array.obj(), jsize{0},
                             checked_cast<jsize>(len), out->data());
 }
diff --git a/tot/base/android/jni_array_unittest.cc b/tot/base/android/jni_array_unittest.cc
index ed7faf8..7911b65 100644
--- a/tot/base/android/jni_array_unittest.cc
+++ b/tot/base/android/jni_array_unittest.cc
@@ -443,8 +443,9 @@
   input_bytes.reserve(kMaxItems);
   for (size_t i = 0; i < kMaxItems; ++i) {
     std::vector<uint8_t> cur_bytes(i + 1);
-    for (size_t j = 0; j < cur_bytes.size(); ++j)
+    for (size_t j = 0; j < cur_bytes.size(); ++j) {
       cur_bytes[j] = static_cast<uint8_t>(i + j * kStep);
+    }
     ScopedJavaLocalRef<jbyteArray> byte_array = ToJavaByteArray(env, cur_bytes);
     ASSERT_TRUE(byte_array);
 
@@ -460,8 +461,9 @@
   JavaArrayOfByteArrayToBytesVector(env, array, &result);
 
   EXPECT_EQ(input_bytes.size(), result.size());
-  for (size_t i = 0; i < kMaxItems; ++i)
+  for (size_t i = 0; i < kMaxItems; ++i) {
     EXPECT_THAT(result[i], ::testing::ElementsAreArray(input_bytes.at(i)));
+  }
 }
 
 TEST(JniArray, JavaArrayOfStringArrayToVectorOfStringVector) {
diff --git a/tot/base/android/jni_callback.cc b/tot/base/android/jni_callback.cc
new file mode 100644
index 0000000..5624744
--- /dev/null
+++ b/tot/base/android/jni_callback.cc
@@ -0,0 +1,116 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/android/jni_callback.h"
+
+// Must come after all headers that specialize FromJniType() / ToJniType().
+#include "base/base_minimal_jni/JniCallbackUtils_jni.h"
+#include "base/base_minimal_jni/JniOnceCallback_jni.h"
+#include "base/base_minimal_jni/JniRepeatingCallback_jni.h"
+
+namespace base::android {
+
+namespace {
+class JniOnceCallback {
+ public:
+  explicit JniOnceCallback(JniOnceWrappedCallbackType&& on_complete)
+      : wrapped_callback_(std::make_unique<JniOnceWrappedCallbackType>(
+            std::move(on_complete))) {}
+  ~JniOnceCallback() = default;
+
+  JniOnceCallback(const JniOnceCallback&) = delete;
+  const JniOnceCallback& operator=(const JniOnceCallback&) = delete;
+
+  jni_zero::ScopedJavaLocalRef<jobject> TransferToJava(JNIEnv* env) && {
+    CHECK(wrapped_callback_);
+    CHECK(!wrapped_callback_->is_null());
+    return Java_JniOnceCallback_Constructor(
+        env, reinterpret_cast<jlong>(wrapped_callback_.release()));
+  }
+
+ private:
+  std::unique_ptr<JniOnceWrappedCallbackType> wrapped_callback_;
+};
+
+class JniRepeatingCallback {
+ public:
+  explicit JniRepeatingCallback(
+      const JniRepeatingWrappedCallbackType& on_complete)
+      : wrapped_callback_(
+            std::make_unique<JniRepeatingWrappedCallbackType>(on_complete)) {}
+  explicit JniRepeatingCallback(JniRepeatingWrappedCallbackType&& on_complete)
+      : wrapped_callback_(std::make_unique<JniRepeatingWrappedCallbackType>(
+            std::move(on_complete))) {}
+  ~JniRepeatingCallback() = default;
+
+  jni_zero::ScopedJavaLocalRef<jobject> TransferToJava(JNIEnv* env) && {
+    CHECK(wrapped_callback_);
+    CHECK(!wrapped_callback_->is_null());
+    return Java_JniRepeatingCallback_Constructor(
+        env, reinterpret_cast<jlong>(wrapped_callback_.release()));
+  }
+  JniRepeatingCallback(const JniRepeatingCallback&) = delete;
+  const JniRepeatingCallback& operator=(const JniRepeatingCallback&) = delete;
+
+ private:
+  std::unique_ptr<JniRepeatingWrappedCallbackType> wrapped_callback_;
+};
+}  // namespace
+
+ScopedJavaLocalRef<jobject> ToJniCallback(
+    JNIEnv* env,
+    JniOnceWrappedCallbackType&& callback) {
+  return JniOnceCallback(std::move(callback)).TransferToJava(env);
+}
+
+ScopedJavaLocalRef<jobject> ToJniCallback(
+    JNIEnv* env,
+    JniRepeatingWrappedCallbackType&& callback) {
+  return JniRepeatingCallback(std::move(callback)).TransferToJava(env);
+}
+
+ScopedJavaLocalRef<jobject> ToJniCallback(
+    JNIEnv* env,
+    const JniRepeatingWrappedCallbackType& callback) {
+  return JniRepeatingCallback(callback).TransferToJava(env);
+}
+
+void JNI_JniCallbackUtils_OnResult(
+    JNIEnv* env,
+    jlong callbackPtr,
+    jboolean isRepeating,
+    const jni_zero::JavaParamRef<jobject>& j_result) {
+  if (isRepeating) {
+    auto* callback =
+        reinterpret_cast<JniRepeatingWrappedCallbackType*>(callbackPtr);
+    callback->Run(j_result);
+  } else {
+    auto* callback = reinterpret_cast<JniOnceWrappedCallbackType*>(callbackPtr);
+    std::move(*callback).Run(j_result);
+    delete callback;
+  }
+}
+
+void JNI_JniCallbackUtils_Destroy(JNIEnv* env,
+                                  jlong callbackPtr,
+                                  jboolean isRepeating) {
+  if (isRepeating) {
+    auto* callback =
+        reinterpret_cast<JniRepeatingWrappedCallbackType*>(callbackPtr);
+    // Call Reset to ensure all accidental use-after-frees fail loudly.
+    callback->Reset();
+    delete callback;
+  } else {
+    auto* callback = reinterpret_cast<JniOnceWrappedCallbackType*>(callbackPtr);
+    // Call Reset to ensure all accidental use-after-frees fail loudly.
+    callback->Reset();
+    delete callback;
+  }
+}
+
+}  // namespace base::android
+
+DEFINE_JNI_FOR_JniCallbackUtils()
+DEFINE_JNI_FOR_JniOnceCallback()
+DEFINE_JNI_FOR_JniRepeatingCallback()
diff --git a/tot/base/android/jni_callback.h b/tot/base/android/jni_callback.h
new file mode 100644
index 0000000..8902081
--- /dev/null
+++ b/tot/base/android/jni_callback.h
@@ -0,0 +1,99 @@
+// Copyright 2025 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_ANDROID_JNI_CALLBACK_H_
+#define BASE_ANDROID_JNI_CALLBACK_H_
+
+#include <jni.h>
+
+#include <type_traits>
+
+#include "base/android/scoped_java_ref.h"
+#include "base/base_export.h"
+#include "base/functional/callback_forward.h"
+#include "base/functional/callback_helpers.h"
+#include "third_party/jni_zero/jni_zero.h"
+
+namespace base::android {
+
+using JniOnceWrappedCallbackType =
+    base::OnceCallback<void(const jni_zero::JavaRef<jobject>&)>;
+using JniRepeatingWrappedCallbackType =
+    base::RepeatingCallback<void(const jni_zero::JavaRef<jobject>&)>;
+
+BASE_EXPORT ScopedJavaLocalRef<jobject> ToJniCallback(
+    JNIEnv* env,
+    JniOnceWrappedCallbackType&& callback);
+BASE_EXPORT ScopedJavaLocalRef<jobject> ToJniCallback(
+    JNIEnv* env,
+    JniRepeatingWrappedCallbackType&& callback);
+BASE_EXPORT ScopedJavaLocalRef<jobject> ToJniCallback(
+    JNIEnv* env,
+    const JniRepeatingWrappedCallbackType& callback);
+
+// Java Callbacks don't return a value so any return value by the passed in
+// callback will be ignored.
+template <typename R, typename Arg>
+BASE_EXPORT ScopedJavaLocalRef<jobject> ToJniCallback(
+    JNIEnv* env,
+    base::OnceCallback<R(Arg)>&& callback) {
+  return ToJniCallback(env, base::BindOnce(
+                                [](base::OnceCallback<R(Arg)> captured_callback,
+                                   const jni_zero::JavaRef<jobject>& j_result) {
+                                  Arg result = jni_zero::FromJniType<Arg>(
+                                      jni_zero::AttachCurrentThread(),
+                                      j_result);
+                                  std::move(captured_callback).Run(result);
+                                },
+                                std::move(callback)));
+}
+
+// Java Callbacks don't return a value so any return value by the passed in
+// callback will be ignored.
+template <typename R>
+BASE_EXPORT ScopedJavaLocalRef<jobject> ToJniCallback(
+    JNIEnv* env,
+    base::OnceCallback<R()>&& callback) {
+  return ToJniCallback(env, base::BindOnce(
+                                [](base::OnceCallback<R()> captured_callback,
+                                   const jni_zero::JavaRef<jobject>& j_result) {
+                                  std::move(captured_callback).Run();
+                                },
+                                std::move(callback)));
+}
+
+// Java Callbacks don't return a value so any return value by the passed in
+// callback will be ignored.
+template <typename R, typename Arg>
+BASE_EXPORT ScopedJavaLocalRef<jobject> ToJniCallback(
+    JNIEnv* env,
+    const base::RepeatingCallback<R(Arg)>& callback) {
+  return ToJniCallback(
+      env, base::BindRepeating(
+               [](const base::RepeatingCallback<R(Arg)>& captured_callback,
+                  const jni_zero::JavaRef<jobject>& j_result) {
+                 Arg result = jni_zero::FromJniType<Arg>(
+                     jni_zero::AttachCurrentThread(), j_result);
+                 captured_callback.Run(result);
+               },
+               callback));
+}
+
+// Java Callbacks don't return a value so any return value by the passed in
+// callback will be ignored.
+template <typename R>
+BASE_EXPORT ScopedJavaLocalRef<jobject> ToJniCallback(
+    JNIEnv* env,
+    const base::RepeatingCallback<R()>& callback) {
+  return ToJniCallback(
+      env, base::BindRepeating(
+               [](const base::RepeatingCallback<R()>& captured_callback,
+                  const jni_zero::JavaRef<jobject>& j_result) {
+                 captured_callback.Run();
+               },
+               callback));
+}
+}  // namespace base::android
+
+#endif  // BASE_ANDROID_JNI_CALLBACK_H_
diff --git a/tot/base/android/jni_string.cc b/tot/base/android/jni_string.cc
index 008cef4..06c04b2 100644
--- a/tot/base/android/jni_string.cc
+++ b/tot/base/android/jni_string.cc
@@ -30,9 +30,7 @@
 namespace android {
 
 void ConvertJavaStringToUTF8(JNIEnv* env, jstring str, std::string* result) {
-  DCHECK(str);
   if (!str) {
-    LOG(WARNING) << "ConvertJavaStringToUTF8 called with null string.";
     result->clear();
     return;
   }
@@ -84,6 +82,10 @@
 
 ScopedJavaLocalRef<jstring> ConvertUTF8ToJavaString(JNIEnv* env,
                                                     std::string_view str) {
+  // ART allocates new empty strings, so use a singleton when applicable.
+  if (str.empty()) {
+    return jni_zero::g_empty_string.AsLocalRef(env);
+  }
   // JNI's NewStringUTF expects "modified" UTF8 so instead create the string
   // via our own UTF16 conversion utility.
   // Further, Dalvik requires the string passed into NewStringUTF() to come from
@@ -91,16 +93,14 @@
   // it gets here, so constructing via UTF16 side-steps this issue.
   // (Dalvik stores strings internally as UTF16 anyway, so there shouldn't be
   // a significant performance hit by doing it this way).
-  return ScopedJavaLocalRef<jstring>(env, ConvertUTF16ToJavaStringImpl(
-      env, UTF8ToUTF16(str)));
+  return ScopedJavaLocalRef<jstring>(
+      env, ConvertUTF16ToJavaStringImpl(env, UTF8ToUTF16(str)));
 }
 
 void ConvertJavaStringToUTF16(JNIEnv* env,
                               jstring str,
                               std::u16string* result) {
-  DCHECK(str);
   if (!str) {
-    LOG(WARNING) << "ConvertJavaStringToUTF16 called with null string.";
     result->clear();
     return;
   }
@@ -150,6 +150,10 @@
 
 ScopedJavaLocalRef<jstring> ConvertUTF16ToJavaString(JNIEnv* env,
                                                      std::u16string_view str) {
+  // ART allocates new empty strings, so use a singleton when applicable.
+  if (str.empty()) {
+    return jni_zero::g_empty_string.AsLocalRef(env);
+  }
   return ScopedJavaLocalRef<jstring>(env,
                                      ConvertUTF16ToJavaStringImpl(env, str));
 }
diff --git a/tot/base/android/jni_string.h b/tot/base/android/jni_string.h
index 603a53f..61425bb 100644
--- a/tot/base/android/jni_string.h
+++ b/tot/base/android/jni_string.h
@@ -66,7 +66,7 @@
 
 template <>
 inline ScopedJavaLocalRef<jobject> ToJniType<const char>(JNIEnv* env,
-                                                   const char* input) {
+                                                         const char* input) {
   return base::android::ConvertUTF8ToJavaString(env, input);
 }
 
diff --git a/tot/base/android/jni_utils.cc b/tot/base/android/jni_utils.cc
index 6f28da4..1fdc90c 100644
--- a/tot/base/android/jni_utils.cc
+++ b/tot/base/android/jni_utils.cc
@@ -7,34 +7,37 @@
 #include "base/android/jni_string.h"
 #include "base/android/scoped_java_ref.h"
 #include "base/containers/flat_map.h"
+#include "base/lazy_instance.h"
 #include "base/no_destructor.h"
 #include "base/synchronization/lock.h"
-#include "build/robolectric_buildflags.h"
 
-#if BUILDFLAG(IS_ROBOLECTRIC)
-#include "base/base_robolectric_jni/JNIUtils_jni.h"  // nogncheck
-#else
-#include "base/base_jni/JNIUtils_jni.h"
-#endif
+// Must come after all headers that specialize FromJniType() / ToJniType().
+#include "base/base_minimal_jni/JNIUtils_jni.h"
 
 namespace base {
 namespace android {
 
-jobject GetSplitClassLoader(JNIEnv* env, const char* split_name) {
-  struct LockAndMap {
-    base::Lock lock;
-    base::flat_map<const char*, ScopedJavaGlobalRef<jobject>> map;
-  };
+namespace {
+struct LockAndMap {
+  base::Lock lock;
+  base::flat_map<const char*, ScopedJavaGlobalRef<jobject>> map;
+};
+LockAndMap* GetLockAndMap() {
   static base::NoDestructor<LockAndMap> lock_and_map;
+  return lock_and_map.get();
+}
+}  // namespace
 
+jobject GetSplitClassLoader(JNIEnv* env, const char* split_name) {
+  LockAndMap* lock_and_map = GetLockAndMap();
   base::AutoLock guard(lock_and_map->lock);
   auto it = lock_and_map->map.find(split_name);
   if (it != lock_and_map->map.end()) {
     return it->second.obj();
   }
 
-  ScopedJavaGlobalRef<jobject> class_loader(Java_JNIUtils_getSplitClassLoader(
-      env, ConvertUTF8ToJavaString(env, split_name)));
+  ScopedJavaGlobalRef<jobject> class_loader(
+      env, Java_JNIUtils_getSplitClassLoader(env, split_name));
   jobject class_loader_obj = class_loader.obj();
   lock_and_map->map.insert({split_name, std::move(class_loader)});
   return class_loader_obj;
@@ -43,3 +46,4 @@
 }  // namespace android
 }  // namespace base
 
+DEFINE_JNI_FOR_JNIUtils()
diff --git a/tot/base/android/jni_utils.h b/tot/base/android/jni_utils.h
index f619671..e18dec4 100644
--- a/tot/base/android/jni_utils.h
+++ b/tot/base/android/jni_utils.h
@@ -28,4 +28,3 @@
 }  // namespace base
 
 #endif  // BASE_ANDROID_JNI_UTILS_H_
-
diff --git a/tot/base/android/junit/src/org/chromium/base/CommandLineTest.java b/tot/base/android/junit/src/org/chromium/base/CommandLineTest.java
index 20a57fc..82ac5fa 100644
--- a/tot/base/android/junit/src/org/chromium/base/CommandLineTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/CommandLineTest.java
@@ -7,7 +7,6 @@
 import androidx.test.filters.SmallTest;
 
 import org.junit.Assert;
-import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.robolectric.annotation.Config;
@@ -45,15 +44,8 @@
     static final String CL_ADDED_SWITCH_2 = "username";
     static final String CL_ADDED_VALUE_2 = "bozo";
 
-    private CommandLine.JavaCommandLine mCommandLine;
-
-    @Before
-    public void setUp() {
-        mCommandLine = new CommandLine.JavaCommandLine(null);
-    }
-
     void checkInitSwitches() {
-        CommandLine cl = mCommandLine;
+        CommandLine cl = CommandLine.getInstance();
         Assert.assertFalse(cl.hasSwitch("init_command"));
         Assert.assertFalse(cl.hasSwitch("switch"));
         Assert.assertTrue(cl.hasSwitch("SWITCH"));
@@ -68,7 +60,7 @@
     }
 
     void checkSettingThenGettingThenRemoving() {
-        CommandLine cl = mCommandLine;
+        CommandLine cl = CommandLine.getInstance();
 
         // Add a plain switch.
         Assert.assertFalse(cl.hasSwitch(CL_ADDED_SWITCH));
@@ -128,7 +120,8 @@
     @SmallTest
     @Feature({"Android-AppBase"})
     public void testJavaInitialization() {
-        mCommandLine = new CommandLine.JavaCommandLine(INIT_SWITCHES);
+        CommandLine.resetForTesting(false);
+        CommandLine.init(INIT_SWITCHES);
         checkInitSwitches();
         checkSettingThenGettingThenRemoving();
     }
@@ -137,9 +130,8 @@
     @SmallTest
     @Feature({"Android-AppBase"})
     public void testBufferInitialization() {
-        mCommandLine =
-                new CommandLine.JavaCommandLine(
-                        CommandLine.tokenizeQuotedArguments(INIT_SWITCHES_BUFFER));
+        CommandLine.resetForTesting(false);
+        CommandLine.init(CommandLine.tokenizeQuotedArguments(INIT_SWITCHES_BUFFER));
         checkInitSwitches();
         checkSettingThenGettingThenRemoving();
     }
@@ -172,7 +164,8 @@
     @SmallTest
     @Feature({"Android-AppBase"})
     public void testUpdatingArgList() {
-        CommandLine cl = mCommandLine;
+        CommandLine.resetForTesting(true);
+        CommandLine cl = CommandLine.getInstance();
         cl.appendSwitch(CL_ADDED_SWITCH);
         cl.appendSwitchWithValue(CL_ADDED_SWITCH_2, CL_ADDED_VALUE_2);
         cl.appendSwitchWithValue(CL_ADDED_SWITCH_2, "updatedValue");
@@ -186,7 +179,7 @@
         Assert.assertArrayEquals(
                 "Appending a switch multiple times should add multiple args",
                 expectedValueForBothSwitches,
-                mCommandLine.getCommandLineArguments());
+                CommandLine.getJavaSwitchesForTesting());
 
         cl.removeSwitch(CL_ADDED_SWITCH_2);
         final String[] expectedValueWithSecondSwitchRemoved = {
@@ -195,6 +188,6 @@
         Assert.assertArrayEquals(
                 "Removing a switch should remove all its args",
                 expectedValueWithSecondSwitchRemoved,
-                mCommandLine.getCommandLineArguments());
+                CommandLine.getJavaSwitchesForTesting());
     }
 }
diff --git a/tot/base/android/junit/src/org/chromium/base/FeatureListUnitTest.java b/tot/base/android/junit/src/org/chromium/base/FeatureListUnitTest.java
deleted file mode 100644
index 8e762b1..0000000
--- a/tot/base/android/junit/src/org/chromium/base/FeatureListUnitTest.java
+++ /dev/null
@@ -1,174 +0,0 @@
-// Copyright 2023 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-package org.chromium.base;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import org.chromium.base.FeatureList.TestValues;
-import org.chromium.base.test.BaseRobolectricTestRunner;
-import org.chromium.base.test.util.Features.EnableFeatures;
-
-/** Unit tests for {@link FeatureList}. */
-@RunWith(BaseRobolectricTestRunner.class)
-public class FeatureListUnitTest {
-
-    private static final String FEATURE_A = "FeatureA";
-    private static final String FEATURE_A_PARAM_1 = "Param1InFeatureA";
-    private static final String FEATURE_A_PARAM_2 = "Param2InFeatureA";
-    private static final String FEATURE_B = "FeatureB";
-
-    @Test
-    public void test_getTestValueForFeature_noOverride_throwsException() {
-        Assert.assertThrows(
-                IllegalArgumentException.class,
-                () -> FeatureList.getTestValueForFeatureStrict(FEATURE_A));
-    }
-
-    @Test
-    public void test_getTestValueForFeature_canUseDefaults_noException() {
-        FeatureList.setDisableNativeForTesting(false);
-        Assert.assertNull(FeatureList.getTestValueForFeatureStrict(FEATURE_A));
-    }
-
-    @Test
-    public void test_getTestValueForFieldTrialParam_noOverride_returnsNull() {
-        Assert.assertNull(FeatureList.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_1));
-    }
-
-    @Test
-    public void test_getTestValueForFeature_override() {
-        TestValues testValues = new TestValues();
-        testValues.addFeatureFlagOverride(FEATURE_A, true);
-        FeatureList.setTestValues(testValues);
-
-        Assert.assertEquals(true, FeatureList.getTestValueForFeatureStrict(FEATURE_A));
-
-        testValues.addFeatureFlagOverride(FEATURE_A, false);
-        FeatureList.setTestValues(testValues);
-
-        Assert.assertEquals(false, FeatureList.getTestValueForFeatureStrict(FEATURE_A));
-    }
-
-    @Test
-    public void test_getTestValueForFieldTrialParam_override() {
-        TestValues testValues = new TestValues();
-        testValues.addFieldTrialParamOverride(FEATURE_A, FEATURE_A_PARAM_1, "paramValue");
-        FeatureList.setTestValues(testValues);
-
-        Assert.assertEquals(
-                "paramValue",
-                FeatureList.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_1));
-
-        // Other params should still return null
-        Assert.assertNull(FeatureList.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_2));
-    }
-
-    @Test
-    public void test_getTestValueForFeature_overrideOther_throwsException() {
-        TestValues testValues = new TestValues();
-        testValues.addFeatureFlagOverride(FEATURE_A, true);
-        FeatureList.setTestValues(testValues);
-
-        Assert.assertThrows(
-                IllegalArgumentException.class,
-                () -> FeatureList.getTestValueForFeatureStrict(FEATURE_B));
-    }
-
-    @Test
-    public void test_mergeTestValues_noConflict() {
-        TestValues testValues1 = new TestValues();
-        testValues1.addFeatureFlagOverride(FEATURE_A, false);
-        testValues1.addFieldTrialParamOverride(FEATURE_A, FEATURE_A_PARAM_1, "paramValue1");
-
-        TestValues testValues2 = new TestValues();
-        testValues2.addFeatureFlagOverride(FEATURE_B, true);
-        testValues2.addFieldTrialParamOverride(FEATURE_A, FEATURE_A_PARAM_2, "paramValue2");
-
-        FeatureList.setTestValues(testValues1);
-        FeatureList.mergeTestValues(testValues2, true);
-
-        Assert.assertEquals(false, FeatureList.getTestValueForFeatureStrict(FEATURE_A));
-        Assert.assertEquals(true, FeatureList.getTestValueForFeatureStrict(FEATURE_B));
-        Assert.assertEquals(
-                "paramValue1",
-                FeatureList.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_1));
-        Assert.assertEquals(
-                "paramValue2",
-                FeatureList.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_2));
-    }
-
-    @Test
-    public void test_mergeTestValues_replace() {
-        TestValues testValues1 = new TestValues();
-        testValues1.addFeatureFlagOverride(FEATURE_A, false);
-        testValues1.addFieldTrialParamOverride(FEATURE_A, FEATURE_A_PARAM_1, "false");
-
-        TestValues testValues2 = new TestValues();
-        testValues2.addFeatureFlagOverride(FEATURE_A, true);
-        testValues2.addFieldTrialParamOverride(FEATURE_A, FEATURE_A_PARAM_1, "true");
-
-        FeatureList.setTestValues(testValues1);
-        FeatureList.mergeTestValues(testValues2, true);
-
-        Assert.assertEquals(true, FeatureList.getTestValueForFeatureStrict(FEATURE_A));
-        Assert.assertEquals(
-                "true", FeatureList.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_1));
-    }
-
-    @Test
-    public void test_mergeTestValues_doNotReplace() {
-        TestValues testValues1 = new TestValues();
-        testValues1.addFeatureFlagOverride(FEATURE_A, false);
-        testValues1.addFieldTrialParamOverride(FEATURE_A, FEATURE_A_PARAM_1, "false");
-
-        TestValues testValues2 = new TestValues();
-        testValues2.addFeatureFlagOverride(FEATURE_A, true);
-        testValues2.addFieldTrialParamOverride(FEATURE_A, FEATURE_A_PARAM_1, "true");
-
-        FeatureList.setTestValues(testValues1);
-        FeatureList.mergeTestValues(testValues2, false);
-
-        Assert.assertEquals(false, FeatureList.getTestValueForFeatureStrict(FEATURE_A));
-        Assert.assertEquals(
-                "false", FeatureList.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_1));
-    }
-
-    @Test
-    @EnableFeatures({FEATURE_A, FEATURE_B})
-    public void test_setTestValues_replacesAnnotation() {
-        FeatureList.setDisableNativeForTesting(false);
-
-        TestValues testValues = new TestValues();
-        testValues.addFeatureFlagOverride(FEATURE_A, false);
-        FeatureList.setTestValues(testValues);
-
-        Assert.assertEquals(false, FeatureList.getTestValueForFeatureStrict(FEATURE_A));
-        Assert.assertNull(FeatureList.getTestValueForFeatureStrict(FEATURE_B));
-    }
-
-    @Test
-    @EnableFeatures({FEATURE_A, FEATURE_B})
-    public void test_mergeTestValues_replace_overridesAnnotation() {
-        TestValues testValues = new TestValues();
-        testValues.addFeatureFlagOverride(FEATURE_A, false);
-        FeatureList.mergeTestValues(testValues, true);
-
-        Assert.assertEquals(false, FeatureList.getTestValueForFeatureStrict(FEATURE_A));
-        Assert.assertEquals(true, FeatureList.getTestValueForFeatureStrict(FEATURE_B));
-    }
-
-    @Test
-    @EnableFeatures({FEATURE_A, FEATURE_B})
-    public void test_mergeTestValues_doNotReplace_doesNotOverrideAnnotation() {
-        TestValues testValues = new TestValues();
-        testValues.addFeatureFlagOverride(FEATURE_A, false);
-        FeatureList.mergeTestValues(testValues, false);
-
-        Assert.assertEquals(true, FeatureList.getTestValueForFeatureStrict(FEATURE_A));
-        Assert.assertEquals(true, FeatureList.getTestValueForFeatureStrict(FEATURE_B));
-    }
-}
diff --git a/tot/base/android/junit/src/org/chromium/base/FeatureOverridesUnitTest.java b/tot/base/android/junit/src/org/chromium/base/FeatureOverridesUnitTest.java
new file mode 100644
index 0000000..084d52d
--- /dev/null
+++ b/tot/base/android/junit/src/org/chromium/base/FeatureOverridesUnitTest.java
@@ -0,0 +1,159 @@
+// Copyright 2023 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.base;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import org.chromium.base.test.BaseRobolectricTestRunner;
+import org.chromium.base.test.util.Features.EnableFeatures;
+
+/** Unit tests for {@link FeatureOverrides}. */
+@RunWith(BaseRobolectricTestRunner.class)
+public class FeatureOverridesUnitTest {
+
+    private static final String FEATURE_A = "FeatureA";
+    private static final String FEATURE_A_PARAM_1 = "Param1InFeatureA";
+    private static final String FEATURE_A_PARAM_2 = "Param2InFeatureA";
+    private static final String FEATURE_B = "FeatureB";
+
+    @Test
+    public void test_getTestValueForFeature_noOverride_throwsException() {
+        Assert.assertThrows(
+                IllegalArgumentException.class,
+                () -> FeatureOverrides.getTestValueForFeatureStrict(FEATURE_A));
+    }
+
+    @Test
+    public void test_getTestValueForFeature_canUseDefaults_noException() {
+        FeatureList.setDisableNativeForTesting(false);
+        Assert.assertNull(FeatureOverrides.getTestValueForFeatureStrict(FEATURE_A));
+    }
+
+    @Test
+    public void test_getTestValueForFieldTrialParam_noOverride_returnsNull() {
+        Assert.assertNull(
+                FeatureOverrides.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_1));
+    }
+
+    @Test
+    public void test_getTestValueForFeature_override() {
+        FeatureOverrides.enable(FEATURE_A);
+
+        Assert.assertEquals(true, FeatureOverrides.getTestValueForFeatureStrict(FEATURE_A));
+
+        FeatureOverrides.disable(FEATURE_A);
+
+        Assert.assertEquals(false, FeatureOverrides.getTestValueForFeatureStrict(FEATURE_A));
+    }
+
+    @Test
+    public void test_getTestValueForFieldTrialParam_override() {
+        FeatureOverrides.overrideParam(FEATURE_A, FEATURE_A_PARAM_1, "paramValue");
+
+        Assert.assertEquals(
+                "paramValue",
+                FeatureOverrides.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_1));
+
+        // Other params should still return null
+        Assert.assertNull(
+                FeatureOverrides.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_2));
+    }
+
+    @Test
+    public void test_getTestValueForFeature_overrideOther_throwsException() {
+        FeatureOverrides.enable(FEATURE_A);
+
+        Assert.assertThrows(
+                IllegalArgumentException.class,
+                () -> FeatureOverrides.getTestValueForFeatureStrict(FEATURE_B));
+    }
+
+    @Test
+    public void test_apply_noConflict() {
+        FeatureOverrides.newBuilder()
+                .enable(FEATURE_A)
+                .param(FEATURE_A_PARAM_1, "paramValue1")
+                .apply();
+        FeatureOverrides.newBuilder()
+                .param(FEATURE_A, FEATURE_A_PARAM_2, "paramValue2")
+                .disable(FEATURE_B)
+                .apply();
+
+        Assert.assertEquals(true, FeatureOverrides.getTestValueForFeatureStrict(FEATURE_A));
+        Assert.assertEquals(false, FeatureOverrides.getTestValueForFeatureStrict(FEATURE_B));
+        Assert.assertEquals(
+                "paramValue1",
+                FeatureOverrides.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_1));
+        Assert.assertEquals(
+                "paramValue2",
+                FeatureOverrides.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_2));
+    }
+
+    @Test
+    public void test_apply_replace() {
+        FeatureOverrides.newBuilder()
+                .enable(FEATURE_A)
+                .param(FEATURE_A_PARAM_1, "paramValue1Original")
+                .param(FEATURE_A_PARAM_2, "paramValue2")
+                .enable(FEATURE_B)
+                .apply();
+        FeatureOverrides.newBuilder()
+                .param(FEATURE_A, FEATURE_A_PARAM_1, "paramValue1Replaced")
+                .disable(FEATURE_B)
+                .apply();
+
+        Assert.assertEquals(true, FeatureOverrides.getTestValueForFeatureStrict(FEATURE_A));
+        Assert.assertEquals(false, FeatureOverrides.getTestValueForFeatureStrict(FEATURE_B));
+        Assert.assertEquals(
+                "paramValue1Replaced",
+                FeatureOverrides.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_1));
+        Assert.assertEquals(
+                "paramValue2",
+                FeatureOverrides.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_2));
+    }
+
+    @Test
+    public void test_applyWithoutOverwrite_doNotReplace() {
+        FeatureOverrides.newBuilder()
+                .enable(FEATURE_A)
+                .param(FEATURE_A_PARAM_1, "paramValue1Original")
+                .param(FEATURE_A_PARAM_2, "paramValue2")
+                .enable(FEATURE_B)
+                .apply();
+        FeatureOverrides.newBuilder()
+                .param(FEATURE_A, FEATURE_A_PARAM_1, "paramValue1Replaced")
+                .disable(FEATURE_B)
+                .applyWithoutOverwrite();
+
+        Assert.assertEquals(true, FeatureOverrides.getTestValueForFeatureStrict(FEATURE_A));
+        Assert.assertEquals(true, FeatureOverrides.getTestValueForFeatureStrict(FEATURE_B));
+        Assert.assertEquals(
+                "paramValue1Original",
+                FeatureOverrides.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_1));
+        Assert.assertEquals(
+                "paramValue2",
+                FeatureOverrides.getTestValueForFieldTrialParam(FEATURE_A, FEATURE_A_PARAM_2));
+    }
+
+    @Test
+    @EnableFeatures({FEATURE_A, FEATURE_B})
+    public void test_apply_replacesAnnotation() {
+        FeatureOverrides.newBuilder().disable(FEATURE_A).apply();
+
+        Assert.assertEquals(false, FeatureOverrides.getTestValueForFeatureStrict(FEATURE_A));
+        Assert.assertEquals(true, FeatureOverrides.getTestValueForFeatureStrict(FEATURE_B));
+    }
+
+    @Test
+    @EnableFeatures({FEATURE_A, FEATURE_B})
+    public void test_mergeTestValues_doNotReplace_doesNotOverrideAnnotation() {
+        FeatureOverrides.newBuilder().disable(FEATURE_A).applyWithoutOverwrite();
+
+        Assert.assertEquals(true, FeatureOverrides.getTestValueForFeatureStrict(FEATURE_A));
+        Assert.assertEquals(true, FeatureOverrides.getTestValueForFeatureStrict(FEATURE_B));
+    }
+}
diff --git a/tot/base/android/junit/src/org/chromium/base/MutableBooleanParamWithSafeDefaultUnitTest.java b/tot/base/android/junit/src/org/chromium/base/MutableBooleanParamWithSafeDefaultUnitTest.java
index 690b9c5..765215b 100644
--- a/tot/base/android/junit/src/org/chromium/base/MutableBooleanParamWithSafeDefaultUnitTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/MutableBooleanParamWithSafeDefaultUnitTest.java
@@ -15,7 +15,6 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import org.chromium.base.FeatureList.TestValues;
 import org.chromium.base.test.BaseRobolectricTestRunner;
 import org.chromium.base.test.util.BaseFlagTestRule;
 import org.chromium.base.test.util.Features.EnableFeatures;
@@ -50,10 +49,7 @@
         MutableBooleanParamWithSafeDefault paramBA = makeParam(FEATURE_B, PARAM_A, false);
         MutableBooleanParamWithSafeDefault paramBB = makeParam(FEATURE_B, PARAM_B, false);
 
-        TestValues testValues = new TestValues();
-        testValues.addFeatureFlagOverride(FEATURE_A, true);
-        testValues.addFieldTrialParamOverride(paramAA, "true");
-        FeatureList.setTestValues(testValues);
+        FeatureOverrides.newBuilder().enable(FEATURE_A).param(PARAM_A, true).apply();
 
         assertTrue(paramAA.getValue());
         assertFalse(paramAB.getValue());
diff --git a/tot/base/android/junit/src/org/chromium/base/MutableFlagWithSafeDefaultUnitTest.java b/tot/base/android/junit/src/org/chromium/base/MutableFlagWithSafeDefaultUnitTest.java
index b372902..1d22f77 100644
--- a/tot/base/android/junit/src/org/chromium/base/MutableFlagWithSafeDefaultUnitTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/MutableFlagWithSafeDefaultUnitTest.java
@@ -4,7 +4,9 @@
 
 package org.chromium.base;
 
-import static org.chromium.base.test.util.BaseFlagTestRule.A_OFF_B_ON;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
 import static org.chromium.base.test.util.BaseFlagTestRule.A_ON_B_OFF;
 import static org.chromium.base.test.util.BaseFlagTestRule.FEATURE_A;
 import static org.chromium.base.test.util.BaseFlagTestRule.FEATURE_B;
@@ -35,17 +37,18 @@
     }
 
     @Test
-    public void testNativeInitialized_getsFromChromeFeatureList() {
+    public void testNativeInitialized_getsFromFeatureMap() {
         MutableFlagWithSafeDefault featureA =
                 FEATURE_MAP.mutableFlagWithSafeDefault(FEATURE_A, false);
         MutableFlagWithSafeDefault featureB =
                 FEATURE_MAP.mutableFlagWithSafeDefault(FEATURE_B, true);
 
-        // Values from ChromeFeatureList should be used from now on.
-        FeatureList.setTestFeatures(A_ON_B_OFF);
+        // Values from FeatureMap should be used from now on.
+        A_ON_B_OFF.apply();
 
-        // Verify that {@link MutableFlagWithSafeDefault} returns native values.
-        BaseFlagTestRule.assertIsEnabledMatches(A_ON_B_OFF, featureA, featureB);
+        // Verify that {@link MutableFlagWithSafeDefault} returns values from FeatureMap.
+        assertTrue(featureA.isEnabled());
+        assertFalse(featureB.isEnabled());
     }
 
     @Test
@@ -56,23 +59,26 @@
                 FEATURE_MAP.mutableFlagWithSafeDefault(FEATURE_B, true);
 
         // Query the flags to make sure the default values are returned.
-        BaseFlagTestRule.assertIsEnabledMatches(A_OFF_B_ON, featureA, featureB);
+        assertFalse(featureA.isEnabled());
+        assertTrue(featureB.isEnabled());
     }
 
     @Test
-    public void testNativeInitializedUsedDefault_getsFromChromeFeatureList() {
+    public void testNativeInitializedUsedDefault_getsFromFeatureMap() {
         MutableFlagWithSafeDefault featureA =
                 FEATURE_MAP.mutableFlagWithSafeDefault(FEATURE_A, false);
         MutableFlagWithSafeDefault featureB =
                 FEATURE_MAP.mutableFlagWithSafeDefault(FEATURE_B, true);
 
         // Query the flags to make sure the default values are returned.
-        BaseFlagTestRule.assertIsEnabledMatches(A_OFF_B_ON, featureA, featureB);
+        assertFalse(featureA.isEnabled());
+        assertTrue(featureB.isEnabled());
 
-        // Values from ChromeFeatureList should be used from now on.
-        FeatureList.setTestFeatures(A_ON_B_OFF);
+        // Values from FeatureMap should be used from now on.
+        A_ON_B_OFF.apply();
 
-        // Verify that {@link MutableFlagWithSafeDefault} returns native values.
-        BaseFlagTestRule.assertIsEnabledMatches(A_ON_B_OFF, featureA, featureB);
+        // Verify that {@link MutableFlagWithSafeDefault} returns values from FeatureMap.
+        assertTrue(featureA.isEnabled());
+        assertFalse(featureB.isEnabled());
     }
 }
diff --git a/tot/base/android/junit/src/org/chromium/base/MutableIntParamWithSafeDefaultUnitTest.java b/tot/base/android/junit/src/org/chromium/base/MutableIntParamWithSafeDefaultUnitTest.java
index 4dc2368..b03d9ec 100644
--- a/tot/base/android/junit/src/org/chromium/base/MutableIntParamWithSafeDefaultUnitTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/MutableIntParamWithSafeDefaultUnitTest.java
@@ -14,7 +14,6 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import org.chromium.base.FeatureList.TestValues;
 import org.chromium.base.test.BaseRobolectricTestRunner;
 import org.chromium.base.test.util.BaseFlagTestRule;
 
@@ -48,10 +47,7 @@
         MutableIntParamWithSafeDefault paramBA = makeParam(FEATURE_B, PARAM_A, 3);
         MutableIntParamWithSafeDefault paramBB = makeParam(FEATURE_B, PARAM_B, 4);
 
-        TestValues testValues = new TestValues();
-        testValues.addFeatureFlagOverride(FEATURE_A, true);
-        testValues.addFieldTrialParamOverride(paramAA, "11");
-        FeatureList.setTestValues(testValues);
+        FeatureOverrides.newBuilder().enable(FEATURE_A).param(PARAM_A, 11).apply();
 
         assertEquals(11, paramAA.getValue());
         assertEquals(2, paramAB.getValue());
diff --git a/tot/base/android/junit/src/org/chromium/base/PathUtilsTest.java b/tot/base/android/junit/src/org/chromium/base/PathUtilsTest.java
index 45cde29..591920e 100644
--- a/tot/base/android/junit/src/org/chromium/base/PathUtilsTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/PathUtilsTest.java
@@ -37,9 +37,9 @@
         String cacheDir = PathUtils.getCacheDirectory();
         String thumbnailDir = PathUtils.getThumbnailCacheDirectory();
 
-        assertEquals(dataDir, expectedDataDir);
-        assertEquals(cacheDir, expectedCacheDir);
-        assertEquals(thumbnailDir, expectedThumbnailDir);
+        assertEquals(expectedDataDir, dataDir);
+        assertEquals(expectedCacheDir, cacheDir);
+        assertEquals(expectedThumbnailDir, thumbnailDir);
     }
 
     @Test
@@ -74,9 +74,9 @@
         String cacheDir = PathUtils.getCacheDirectory();
         String thumbnailDir = PathUtils.getThumbnailCacheDirectory();
 
-        assertEquals(dataDir, expectedDataDir);
-        assertEquals(cacheDir, expectedCacheDir);
-        assertEquals(thumbnailDir, expectedThumbnailDir);
+        assertEquals(expectedDataDir, dataDir);
+        assertEquals(expectedCacheDir, cacheDir);
+        assertEquals(expectedThumbnailDir, thumbnailDir);
     }
 
     @Test
@@ -94,8 +94,8 @@
         String cacheDir = PathUtils.getCacheDirectory();
         String thumbnailDir = PathUtils.getThumbnailCacheDirectory();
 
-        assertEquals(dataDir, expectedDataDir);
-        assertEquals(cacheDir, expectedCacheDir);
-        assertEquals(thumbnailDir, expectedThumbnailDir);
+        assertEquals(expectedDataDir, dataDir);
+        assertEquals(expectedCacheDir, cacheDir);
+        assertEquals(expectedThumbnailDir, thumbnailDir);
     }
 }
diff --git a/tot/base/android/junit/src/org/chromium/base/PostNativeFlagUnitTest.java b/tot/base/android/junit/src/org/chromium/base/PostNativeFlagUnitTest.java
index ccdcad4..2c6df0b 100644
--- a/tot/base/android/junit/src/org/chromium/base/PostNativeFlagUnitTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/PostNativeFlagUnitTest.java
@@ -4,10 +4,12 @@
 
 package org.chromium.base;
 
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
 import static org.chromium.base.test.util.BaseFlagTestRule.A_OFF_B_ON;
 import static org.chromium.base.test.util.BaseFlagTestRule.FEATURE_A;
 import static org.chromium.base.test.util.BaseFlagTestRule.FEATURE_B;
-import static org.chromium.base.test.util.BaseFlagTestRule.assertIsEnabledMatches;
 
 import org.junit.Rule;
 import org.junit.Test;
@@ -43,10 +45,11 @@
         PostNativeFlag featureA = new PostNativeFlag(BaseFlagTestRule.FEATURE_MAP, FEATURE_A);
         PostNativeFlag featureB = new PostNativeFlag(BaseFlagTestRule.FEATURE_MAP, FEATURE_B);
 
-        // Values from ChromeFeatureList should be used from now on.
-        FeatureList.setTestFeatures(A_OFF_B_ON);
+        // Values from the FeatureMap should be used from now on.
+        A_OFF_B_ON.apply();
 
-        // Assert {@link MutableFlagWithSafeDefault} uses the values from {@link ChromeFeatureList}.
-        assertIsEnabledMatches(A_OFF_B_ON, featureA, featureB);
+        // Assert {@link MutableFlagWithSafeDefault} uses the values from FeatureMap.
+        assertFalse(featureA.isEnabled());
+        assertTrue(featureB.isEnabled());
     }
 }
diff --git a/tot/base/android/junit/src/org/chromium/base/PromiseTest.java b/tot/base/android/junit/src/org/chromium/base/PromiseTest.java
index 3f37e58..3405e5d 100644
--- a/tot/base/android/junit/src/org/chromium/base/PromiseTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/PromiseTest.java
@@ -52,10 +52,10 @@
         Promise<Integer> promise = new Promise<>();
         promise.then(PromiseTest.setValue(value, 1));
 
-        assertEquals(value.get(), 0);
+        assertEquals(0, value.get());
 
         promise.fulfill(1);
-        assertEquals(value.get(), 1);
+        assertEquals(1, value.get());
     }
 
     /** Tests that multiple callbacks are called. */
@@ -71,10 +71,10 @@
         promise.then(callback);
         promise.then(callback);
 
-        assertEquals(value.get(), 0);
+        assertEquals(0, value.get());
 
         promise.fulfill(0);
-        assertEquals(value.get(), 2);
+        assertEquals(2, value.get());
     }
 
     /** Tests that a callback is called immediately when given to a fulfilled Promise. */
@@ -83,11 +83,11 @@
         final Value value = new Value();
 
         Promise<Integer> promise = Promise.fulfilled(0);
-        assertEquals(value.get(), 0);
+        assertEquals(0, value.get());
 
         promise.then(PromiseTest.setValue(value, 1));
 
-        assertEquals(value.get(), 1);
+        assertEquals(1, value.get());
     }
 
     /** Tests that promises can chain synchronous functions correctly. */
@@ -210,7 +210,7 @@
         promise.reject(new Exception());
         ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
 
-        assertEquals(value.get(), 5);
+        assertEquals(5, value.get());
         assertTrue(result.isRejected());
     }
 
@@ -229,7 +229,7 @@
         promise.fulfill(0);
 
         ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
-        assertEquals(value.get(), 5);
+        assertEquals(5, value.get());
     }
 
     /** Tests that Promises get rejected if an AsyncFunction throws. */
@@ -248,7 +248,7 @@
         promise.fulfill(0);
 
         ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
-        assertEquals(value.get(), 5);
+        assertEquals(5, value.get());
     }
 
     /** Tests that Promises get rejected if an AsyncFunction rejects. */
@@ -263,12 +263,12 @@
         promise.fulfill(0);
 
         ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
-        assertEquals(value.get(), 0);
+        assertEquals(0, value.get());
 
         inner.reject();
 
         ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
-        assertEquals(value.get(), 5);
+        assertEquals(5, value.get());
     }
 
     @Test
diff --git a/tot/base/android/junit/src/org/chromium/base/TraceEventTest.java b/tot/base/android/junit/src/org/chromium/base/TraceEventTest.java
index 3d2ccc0..391a84b 100644
--- a/tot/base/android/junit/src/org/chromium/base/TraceEventTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/TraceEventTest.java
@@ -80,8 +80,8 @@
                 TraceEvent.BasicLooperMonitor.LOOPER_TASK_PREFIX
                         + "org.chromium.myClass.myMethod(org.chromium.myOtherClass.instance)";
         Assert.assertEquals(
-                TraceEvent.BasicLooperMonitor.getTraceEventName(realEventName),
-                TraceEvent.BasicLooperMonitor.FILTERED_EVENT_NAME);
+                TraceEvent.BasicLooperMonitor.FILTERED_EVENT_NAME,
+                TraceEvent.BasicLooperMonitor.getTraceEventName(realEventName));
     }
 
     @Test
@@ -122,13 +122,25 @@
     @Test
     @SmallTest
     @Feature({"Android-AppBase"})
-    public void testWebViewStartupStage2() {
+    public void testWebViewStartupFirstInstance() {
         TraceEvent.setEnabled(true);
         long startTime = 10;
         long duration = 50;
-        boolean isCold = true;
-        TraceEvent.webViewStartupStage2(startTime, duration, isCold);
-        verify(mNativeMock).webViewStartupStage2(startTime, duration, isCold);
+        boolean includedGlobalStartup = true;
+        TraceEvent.webViewStartupFirstInstance(startTime, duration, includedGlobalStartup);
+        verify(mNativeMock).webViewStartupFirstInstance(startTime, duration, includedGlobalStartup);
+        TraceEvent.setEnabled(false);
+    }
+
+    @Test
+    @SmallTest
+    @Feature({"Android-AppBase"})
+    public void testWebViewStartupNotFirstInstance() {
+        TraceEvent.setEnabled(true);
+        long startTime = 10;
+        long duration = 50;
+        TraceEvent.webViewStartupNotFirstInstance(startTime, duration);
+        verify(mNativeMock).webViewStartupNotFirstInstance(startTime, duration);
         TraceEvent.setEnabled(false);
     }
 }
diff --git a/tot/base/android/junit/src/org/chromium/base/jank_tracker/JankReportingRunnableTest.java b/tot/base/android/junit/src/org/chromium/base/jank_tracker/JankReportingRunnableTest.java
index b822447..53b4302 100644
--- a/tot/base/android/junit/src/org/chromium/base/jank_tracker/JankReportingRunnableTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/jank_tracker/JankReportingRunnableTest.java
@@ -103,7 +103,7 @@
 
         JankEndScenarioTime endScenarioTime = JankEndScenarioTime.endAt(frameTime);
         Assert.assertTrue(endScenarioTime != null);
-        Assert.assertEquals(endScenarioTime.endScenarioTimeNs, frameTime);
+        Assert.assertEquals(frameTime, endScenarioTime.endScenarioTimeNs);
 
         JankReportingRunnable startReportingRunnable =
                 new JankReportingRunnable(
diff --git a/tot/base/android/junit/src/org/chromium/base/process_launcher/ChildConnectionAllocatorTest.java b/tot/base/android/junit/src/org/chromium/base/process_launcher/ChildConnectionAllocatorTest.java
index c071fc6..4e05163 100644
--- a/tot/base/android/junit/src/org/chromium/base/process_launcher/ChildConnectionAllocatorTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/process_launcher/ChildConnectionAllocatorTest.java
@@ -58,6 +58,7 @@
 
     static class TestConnectionFactory implements ChildConnectionAllocator.ConnectionFactory {
         private ComponentName mLastServiceName;
+        private ComponentName mLastFallbackServiceName;
         private String mLastInstanceName;
 
         private ChildProcessConnection mConnection;
@@ -72,8 +73,11 @@
                 boolean bindToCaller,
                 boolean bindAsExternalService,
                 Bundle serviceBundle,
-                String instanceName) {
+                String instanceName,
+                boolean independentFallback,
+                boolean isSandboxedForHistograms) {
             mLastServiceName = serviceName;
+            mLastFallbackServiceName = fallbackServiceName;
             mLastInstanceName = instanceName;
             if (mConnection == null) {
                 mConnection = mock(ChildProcessConnection.class);
@@ -100,6 +104,12 @@
             return serviceName;
         }
 
+        public ComponentName getAndResetLastFallbackServiceName() {
+            ComponentName fallbackServiceName = mLastFallbackServiceName;
+            mLastFallbackServiceName = null;
+            return fallbackServiceName;
+        }
+
         public String getAndResetLastInstanceName() {
             String instanceName = mLastInstanceName;
             mLastInstanceName = null;
@@ -164,7 +174,9 @@
                         MAX_CONNECTION_NUMBER,
                         /* bindToCaller= */ true,
                         /* bindAsExternalService= */ false,
-                        /* useStrongBinding= */ false);
+                        /* useStrongBinding= */ false,
+                        /* fallbackToNextSlot= */ false,
+                        /* isSandboxedForHistograms= */ false);
         mAllocator.setConnectionFactoryForTesting(mTestConnectionFactory);
 
         mVariableSizeAllocator =
@@ -173,7 +185,7 @@
                         TEST_PACKAGE_NAME,
                         /* freeSlotCallback= */ null,
                         "AllocatorTest",
-                        /* bindTocall= */ true,
+                        /* bindToCaller= */ true,
                         /* bindAsExternalService= */ false,
                         /* useStrongBinding= */ false,
                         10);
@@ -185,7 +197,7 @@
                         TEST_PACKAGE_NAME,
                         /* freeSlotCallback= */ null,
                         "AllocatorTest",
-                        /* bindTocall= */ true,
+                        /* bindToCaller= */ true,
                         /* bindAsExternalService= */ false,
                         /* useStrongBinding= */ false,
                         10);
@@ -196,7 +208,7 @@
     @Feature({"ProcessManagement"})
     public void testPlainAllocate() {
         assertFalse(mAllocator.anyConnectionAllocated());
-        assertEquals(MAX_CONNECTION_NUMBER, mAllocator.getNumberOfServices());
+        assertEquals(MAX_CONNECTION_NUMBER, mAllocator.getMaxNumberOfAllocations());
 
         ChildProcessConnection connection =
                 mAllocator.allocate(
@@ -244,7 +256,9 @@
                         1,
                         /* bindToCaller= */ true,
                         /* bindAsExternalService= */ false,
-                        /* useStrongBinding= */ false);
+                        /* useStrongBinding= */ false,
+                        /* fallbackToNextSlot= */ false,
+                        /* isSandboxedForHistograms= */ false);
         doTestQueueAllocation(mAllocator, freeConnectionCallback);
     }
 
@@ -340,7 +354,9 @@
                             MAX_CONNECTION_NUMBER,
                             /* bindToCaller= */ true,
                             /* bindAsExternalService= */ false,
-                            useStrongBinding);
+                            useStrongBinding,
+                            /* fallbackToNextSlot= */ false,
+                            /* isSandboxedForHistograms= */ false);
             allocator.setConnectionFactoryForTesting(mTestConnectionFactory);
             ChildProcessConnection connection =
                     allocator.allocate(
@@ -349,6 +365,62 @@
         }
     }
 
+    @Test
+    @Feature({"ProcessManagement"})
+    public void testFixedSizeAllocatorFallback() {
+        ChildConnectionAllocator.FixedSizeAllocatorImpl allocator =
+                ChildConnectionAllocator.createFixedForTesting(
+                        null,
+                        TEST_PACKAGE_NAME,
+                        "AllocatorTest",
+                        /* serviceCount= */ 4,
+                        /* bindToCaller= */ true,
+                        /* bindAsExternalService= */ false,
+                        /* useStrongBinding= */ true,
+                        /* fallbackToNextSlot= */ true,
+                        /* isSandboxedForHistograms= */ false);
+
+        assertEquals(2, allocator.getMaxNumberOfAllocations());
+        assertEquals(0, allocator.allocatedConnectionsCountForTesting());
+        assertEquals(true, allocator.isFreeConnectionAvailable());
+        assertEquals(false, allocator.anyConnectionAllocated());
+
+        TestConnectionFactory connection1Factory = new TestConnectionFactory();
+        allocator.setConnectionFactoryForTesting(connection1Factory);
+        ChildProcessConnection connection1 =
+                allocator.allocate(
+                        /* context= */ null, /* serviceBundle= */ null, mServiceCallback);
+        assertEquals(1, allocator.allocatedConnectionsCountForTesting());
+        assertEquals(true, allocator.isFreeConnectionAvailable());
+        assertEquals(true, allocator.anyConnectionAllocated());
+        assertEquals(connection1, allocator.getChildProcessConnectionAtSlotForTesting(0));
+        assertNotNull(connection1Factory.getAndResetLastFallbackServiceName());
+
+        TestConnectionFactory connection2Factory = new TestConnectionFactory();
+        allocator.setConnectionFactoryForTesting(connection2Factory);
+        ChildProcessConnection connection2 =
+                allocator.allocate(
+                        /* context= */ null, /* serviceBundle= */ null, mServiceCallback);
+        assertEquals(2, allocator.allocatedConnectionsCountForTesting());
+        assertEquals(false, allocator.isFreeConnectionAvailable());
+        assertEquals(true, allocator.anyConnectionAllocated());
+        assertEquals(connection2, allocator.getChildProcessConnectionAtSlotForTesting(2));
+        assertNotNull(connection2Factory.getAndResetLastFallbackServiceName());
+
+        connection2Factory.simulateServiceProcessDying();
+        ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
+        assertEquals(1, allocator.allocatedConnectionsCountForTesting());
+        assertEquals(true, allocator.isFreeConnectionAvailable());
+        assertEquals(true, allocator.anyConnectionAllocated());
+
+        connection1Factory.simulateServiceProcessDying();
+        ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
+        assertEquals(2, allocator.getMaxNumberOfAllocations());
+        assertEquals(0, allocator.allocatedConnectionsCountForTesting());
+        assertEquals(true, allocator.isFreeConnectionAvailable());
+        assertEquals(false, allocator.anyConnectionAllocated());
+    }
+
     /**
      * Tests that the various ServiceCallbacks are propagated and posted, so they happen after the
      * ChildProcessAllocator,allocate() method has returned.
diff --git a/tot/base/android/junit/src/org/chromium/base/process_launcher/ChildProcessConnectionTest.java b/tot/base/android/junit/src/org/chromium/base/process_launcher/ChildProcessConnectionTest.java
index e331c6a..7b23aca 100644
--- a/tot/base/android/junit/src/org/chromium/base/process_launcher/ChildProcessConnectionTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/process_launcher/ChildProcessConnectionTest.java
@@ -207,7 +207,9 @@
                 bindAsExternalService,
                 serviceBundle,
                 mServiceConnectionFactory,
-                /* instanceName= */ null);
+                /* instanceName= */ null,
+                /* independentFallback= */ false,
+                /* isSandboxedForHistograms= */ false);
     }
 
     private void sendPid(int pid) throws RemoteException {
@@ -379,7 +381,7 @@
         connection.start(/* useStrongBinding= */ false, /* serviceCallback= */ null);
         connection.setupConnection(
                 /* connectionBundle= */ null,
-                /* callback= */ null,
+                /* clientInterfaces= */ null,
                 /* binderBox= */ null,
                 mConnectionCallback,
                 /* zygoteInfoCallback= */ null);
@@ -398,7 +400,7 @@
         connection.start(/* useStrongBinding= */ false, /* serviceCallback= */ null);
         connection.setupConnection(
                 /* connectionBundle= */ null,
-                /* callback= */ null,
+                /* clientInterfaces= */ null,
                 /* binderBox= */ null,
                 mConnectionCallback,
                 /* zygoteInfoCallback= */ null);
@@ -420,7 +422,7 @@
         connection.start(/* useStrongBinding= */ false, /* serviceCallback= */ null);
         connection.setupConnection(
                 /* connectionBundle= */ null,
-                /* callback= */ null,
+                /* clientInterfaces= */ null,
                 /* binderBox= */ null,
                 mConnectionCallback,
                 /* zygoteInfoCallback= */ null);
@@ -447,7 +449,7 @@
         connection1.start(/* useStrongBinding= */ true, /* serviceCallback= */ null);
         connection1.setupConnection(
                 /* connectionBundle= */ null,
-                /* callback= */ null,
+                /* clientInterfaces= */ null,
                 /* binderBox= */ null,
                 mConnectionCallback,
                 /* zygoteInfoCallback= */ null);
@@ -471,7 +473,7 @@
         connection2.start(/* useStrongBinding= */ false, /* serviceCallback= */ null);
         connection2.setupConnection(
                 /* connectionBundle= */ null,
-                /* callback= */ null,
+                /* clientInterfaces= */ null,
                 /* binderBox= */ null,
                 mConnectionCallback,
                 /* zygoteInfoCallback= */ null);
@@ -497,7 +499,7 @@
         connection.start(/* useStrongBinding= */ false, /* serviceCallback= */ null);
         connection.setupConnection(
                 /* connectionBundle= */ null,
-                /* callback= */ null,
+                /* clientInterfaces= */ null,
                 /* binderBox= */ null,
                 mConnectionCallback,
                 mZygoteInfoCallback);
@@ -528,7 +530,7 @@
         connection.start(/* useStrongBinding= */ false, /* serviceCallback= */ null);
         connection.setupConnection(
                 /* connectionBundle= */ null,
-                /* callback= */ null,
+                /* clientInterfaces= */ null,
                 /* binderBox= */ null,
                 mConnectionCallback,
                 mZygoteInfoCallback);
@@ -557,7 +559,7 @@
         mFirstServiceConnection.notifyServiceConnected(mChildProcessServiceBinder);
         connection.setupConnection(
                 /* connectionBundle= */ null,
-                /* callback= */ null,
+                /* clientInterfaces= */ null,
                 /* binderBox= */ null,
                 mConnectionCallback,
                 /* zygoteInfoCallback= */ null);
@@ -576,7 +578,7 @@
         mFirstServiceConnection.notifyServiceConnected(mChildProcessServiceBinder);
         connection.setupConnection(
                 /* connectionBundle= */ null,
-                /* callback= */ null,
+                /* clientInterfaces= */ null,
                 /* binderBox= */ null,
                 mConnectionCallback,
                 /* zygoteInfoCallback= */ null);
@@ -630,7 +632,7 @@
         mFirstServiceConnection.notifyServiceConnected(mChildProcessServiceBinder);
         connection.setupConnection(
                 /* connectionBundle= */ null,
-                /* callback= */ null,
+                /* clientInterfaces= */ null,
                 /* binderBox= */ null,
                 mConnectionCallback,
                 /* zygoteInfoCallback= */ null);
@@ -681,7 +683,7 @@
 
         connection.setupConnection(
                 /* connectionBundle= */ null,
-                /* callback= */ null,
+                /* clientInterfaces= */ null,
                 /* binderBox= */ null,
                 mConnectionCallback,
                 /* zygoteInfoCallback= */ null);
diff --git a/tot/base/android/junit/src/org/chromium/base/shared_preferences/KeyPrefixTest.java b/tot/base/android/junit/src/org/chromium/base/shared_preferences/KeyPrefixTest.java
index ddac75e..daa01e8 100644
--- a/tot/base/android/junit/src/org/chromium/base/shared_preferences/KeyPrefixTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/shared_preferences/KeyPrefixTest.java
@@ -23,11 +23,11 @@
     public void testSuccess_validPattern() {
         KeyPrefix prefix = new KeyPrefix("Chrome.Feature.KP.*");
 
-        assertEquals(prefix.pattern(), "Chrome.Feature.KP.*");
+        assertEquals("Chrome.Feature.KP.*", prefix.pattern());
 
-        assertEquals(prefix.createKey("DynamicKey"), "Chrome.Feature.KP.DynamicKey");
-        assertEquals(prefix.createKey("Level.DynamicKey"), "Chrome.Feature.KP.Level.DynamicKey");
-        assertEquals(prefix.createKey(42), "Chrome.Feature.KP.42");
+        assertEquals("Chrome.Feature.KP.DynamicKey", prefix.createKey("DynamicKey"));
+        assertEquals("Chrome.Feature.KP.Level.DynamicKey", prefix.createKey("Level.DynamicKey"));
+        assertEquals("Chrome.Feature.KP.42", prefix.createKey(42));
 
         assertTrue(prefix.hasGenerated("Chrome.Feature.KP.DynamicKey"));
         assertTrue(prefix.hasGenerated("Chrome.Feature.KP.Level.DynamicKey"));
@@ -40,8 +40,8 @@
     public void testSuccess_validLegacyPattern() {
         KeyPrefix prefix = new KeyPrefix("legacy_pattern_*");
 
-        assertEquals(prefix.pattern(), "legacy_pattern_*");
-        assertEquals(prefix.createKey("DynamicKey"), "legacy_pattern_DynamicKey");
+        assertEquals("legacy_pattern_*", prefix.pattern());
+        assertEquals("legacy_pattern_DynamicKey", prefix.createKey("DynamicKey"));
 
         assertTrue(prefix.hasGenerated("legacy_pattern_DynamicKey"));
         assertFalse(prefix.hasGenerated("OtherKey"));
diff --git a/tot/base/android/junit/src/org/chromium/base/shared_preferences/SharedPreferencesManagerTest.java b/tot/base/android/junit/src/org/chromium/base/shared_preferences/SharedPreferencesManagerTest.java
index 5f0d7ad..91d745e 100644
--- a/tot/base/android/junit/src/org/chromium/base/shared_preferences/SharedPreferencesManagerTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/shared_preferences/SharedPreferencesManagerTest.java
@@ -403,6 +403,29 @@
 
     @Test
     @SmallTest
+    public void testRemoveKeys_2() {
+        // Write some values
+        mSubject.writeInt(TEST_PREFIX.createKey("infix1"), 111);
+        mSubject.writeInt(TEST_PREFIX.createKey("infix2"), 222);
+        mSubject.writeInt(TEST_PREFIX.createKey("infix3"), 333);
+        mSubject.writeInt(PREFIXED_KEY_1, 444);
+        mSubject.writeInt(PREFIXED_KEY_2, 555);
+        mSubject.writeInt(PREFIXED_KEY_3, 666);
+
+        // Remove some of them
+        mSubject.removeKeysWithPrefix(TEST_PREFIX, "infix");
+
+        // Verify only values with the given prefix were removed.
+        assertEquals(0, mSubject.readInt(TEST_PREFIX.createKey("infix1"), 0));
+        assertEquals(0, mSubject.readInt(TEST_PREFIX.createKey("infix2"), 0));
+        assertEquals(0, mSubject.readInt(TEST_PREFIX.createKey("infix3"), 0));
+        assertEquals(444, mSubject.readInt(PREFIXED_KEY_1, 0));
+        assertEquals(555, mSubject.readInt(PREFIXED_KEY_2, 0));
+        assertEquals(666, mSubject.readInt(PREFIXED_KEY_3, 0));
+    }
+
+    @Test
+    @SmallTest
     public void testReadStringsWithPrefix() {
         // Write some values.
         mSubject.writeString(PREFIXED_KEY_1, "first");
@@ -567,6 +590,8 @@
         verify(mChecker, times(6)).checkIsPrefixInUse(eq(TEST_PREFIX));
         mSubject.removeKeysWithPrefix(TEST_PREFIX);
         verify(mChecker, times(7)).checkIsPrefixInUse(eq(TEST_PREFIX));
+        mSubject.removeKeysWithPrefix(TEST_PREFIX, "some_key");
+        verify(mChecker, times(8)).checkIsPrefixInUse(eq(TEST_PREFIX));
     }
 
     @Test
diff --git a/tot/base/android/junit/src/org/chromium/base/supplier/ObservableSupplierImplTest.java b/tot/base/android/junit/src/org/chromium/base/supplier/ObservableSupplierImplTest.java
index 329d2b7..f15f8ed 100644
--- a/tot/base/android/junit/src/org/chromium/base/supplier/ObservableSupplierImplTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/supplier/ObservableSupplierImplTest.java
@@ -14,9 +14,13 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.robolectric.annotation.Config;
+import org.robolectric.shadows.ShadowLooper;
 
 import org.chromium.base.Callback;
 import org.chromium.base.test.BaseRobolectricTestRunner;
+import org.chromium.build.annotations.Nullable;
+
+import java.util.concurrent.atomic.AtomicBoolean;
 
 /** Unit tests for {@link ObservableSupplierImpl}. */
 @RunWith(BaseRobolectricTestRunner.class)
@@ -25,9 +29,11 @@
     private static final String TEST_STRING_1 = "Test";
     private static final String TEST_STRING_2 = "Test2";
 
+    private final ObservableSupplierImpl<@Nullable String> mSupplier =
+            new ObservableSupplierImpl<>();
+
     private int mCallCount;
     private String mLastSuppliedString;
-    private ObservableSupplierImpl<String> mSupplier = new ObservableSupplierImpl<>();
 
     @Test
     public void testObserverNotification_SetMultiple() {
@@ -51,6 +57,85 @@
     }
 
     @Test
+    public void testAddObserver_ShouldNotifyOnAdd() {
+        mSupplier.set(TEST_STRING_1);
+
+        AtomicBoolean called = new AtomicBoolean(false);
+        Callback<String> supplierObserver = ignored -> called.set(true);
+
+        mSupplier.addObserver(supplierObserver);
+        ShadowLooper.runUiThreadTasks();
+        assertTrue(called.get());
+    }
+
+    @Test
+    public void testAddObserver_ShouldNotNotifyOnAdd() {
+        mSupplier.set(TEST_STRING_1);
+
+        AtomicBoolean called = new AtomicBoolean(false);
+        Callback<String> supplierObserver = ignored -> called.set(true);
+
+        mSupplier.addSyncObserver(supplierObserver);
+        ShadowLooper.runUiThreadTasks();
+        assertFalse(called.get());
+
+        mSupplier.set(TEST_STRING_2);
+        ShadowLooper.runUiThreadTasks();
+        assertTrue(called.get());
+    }
+
+    @Test
+    public void testAddObserver_ShouldOmitNullOnAdd() {
+        AtomicBoolean called = new AtomicBoolean(false);
+        Callback<String> supplierObserver = ignored -> called.set(true);
+
+        mSupplier.addSyncObserverAndCallIfNonNull(supplierObserver);
+        ShadowLooper.runUiThreadTasks();
+        assertFalse(called.get());
+
+        mSupplier.set(TEST_STRING_2);
+        ShadowLooper.runUiThreadTasks();
+        assertTrue(called.get());
+    }
+
+    @Test
+    public void testAddObserver_ShouldPostOnAdd() {
+        mSupplier.set(TEST_STRING_1);
+        AtomicBoolean called = new AtomicBoolean(false);
+        Callback<String> supplierObserver = ignored -> called.set(true);
+
+        mSupplier.addSyncObserverAndPostIfNonNull(supplierObserver);
+        ShadowLooper.runUiThreadTasks();
+        assertTrue(called.get());
+    }
+
+    @Test
+    public void testAddObserver_ShouldCallOnAdd() {
+        mSupplier.set(TEST_STRING_1);
+        AtomicBoolean called = new AtomicBoolean(false);
+        Callback<String> supplierObserver = ignored -> called.set(true);
+
+        mSupplier.addSyncObserverAndCallIfNonNull(supplierObserver); // !NotifyBehavior.POST_ON_ADD
+        boolean idle = ShadowLooper.shadowMainLooper().isIdle();
+        assertTrue(idle);
+    }
+
+    @Test
+    public void testAddObserver_ShouldCallOnChange() {
+        mSupplier.set(TEST_STRING_1);
+        AtomicBoolean called = new AtomicBoolean(false);
+        Callback<String> supplierObserver = ignored -> called.set(true);
+
+        mSupplier.addSyncObserver(supplierObserver); // !NotifyBehavior.POST_ON_CHANGE
+        boolean idle = ShadowLooper.shadowMainLooper().isIdle();
+        assertTrue(idle);
+
+        mSupplier.set(TEST_STRING_2);
+        idle = ShadowLooper.shadowMainLooper().isIdle();
+        assertTrue(idle);
+    }
+
+    @Test
     public void testObserverNotification_SetSame() {
         Callback<String> supplierObserver =
                 result -> {
diff --git a/tot/base/android/junit/src/org/chromium/base/supplier/TransitiveObservableSupplierTest.java b/tot/base/android/junit/src/org/chromium/base/supplier/TransitiveObservableSupplierTest.java
index f4d349d..a35bed3 100644
--- a/tot/base/android/junit/src/org/chromium/base/supplier/TransitiveObservableSupplierTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/supplier/TransitiveObservableSupplierTest.java
@@ -164,4 +164,52 @@
         ShadowLooper.idleMainLooper();
         verify(mOnChangeCallback).onResult(eq(mObject1));
     }
+
+    @Test
+    public void testAddObserver_ShouldNotifyOnAdd() {
+        ObservableSupplierImpl<ObservableSupplier<Object>> parentSupplier =
+                new ObservableSupplierImpl<>();
+        ObservableSupplierImpl<Object> targetSupplier1 = new ObservableSupplierImpl<>();
+
+        ObservableSupplier<Object> transitiveSupplier = make(parentSupplier);
+        assertNull(transitiveSupplier.get());
+
+        parentSupplier.set(targetSupplier1);
+        assertNull(transitiveSupplier.get());
+        verifyNoInteractions(mOnChangeCallback);
+
+        targetSupplier1.set(mObject1);
+        assertEquals(mObject1, transitiveSupplier.get());
+        verifyNoInteractions(mOnChangeCallback);
+
+        assertEquals(transitiveSupplier.addSyncObserverAndCallIfNonNull(mOnChangeCallback), mObject1);
+        ShadowLooper.runUiThreadTasks();
+        verify(mOnChangeCallback).onResult(eq(mObject1));
+    }
+
+    @Test
+    public void testAddObserver_ShouldNotNotifyOnAdd() {
+        ObservableSupplierImpl<ObservableSupplier<Object>> parentSupplier =
+                new ObservableSupplierImpl<>();
+        ObservableSupplierImpl<Object> targetSupplier1 = new ObservableSupplierImpl<>();
+
+        ObservableSupplier<Object> transitiveSupplier = make(parentSupplier);
+        assertNull(transitiveSupplier.get());
+
+        parentSupplier.set(targetSupplier1);
+        assertNull(transitiveSupplier.get());
+        verifyNoInteractions(mOnChangeCallback);
+
+        targetSupplier1.set(mObject1);
+        assertEquals(mObject1, transitiveSupplier.get());
+        verifyNoInteractions(mOnChangeCallback);
+
+        assertEquals(transitiveSupplier.addSyncObserver(mOnChangeCallback), mObject1);
+        ShadowLooper.runUiThreadTasks();
+        verifyNoInteractions(mOnChangeCallback);
+
+        targetSupplier1.set(mObject2);
+        assertEquals(mObject2, transitiveSupplier.get());
+        verify(mOnChangeCallback).onResult(eq(mObject2));
+    }
 }
diff --git a/tot/base/android/junit/src/org/chromium/base/supplier/UnwrapObservableSupplierTest.java b/tot/base/android/junit/src/org/chromium/base/supplier/UnwrapObservableSupplierTest.java
index 343e905..2de0c39 100644
--- a/tot/base/android/junit/src/org/chromium/base/supplier/UnwrapObservableSupplierTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/supplier/UnwrapObservableSupplierTest.java
@@ -7,9 +7,12 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
 
 import org.junit.Rule;
 import org.junit.Test;
@@ -67,7 +70,7 @@
 
         ShadowLooper.idleMainLooper();
         assertTrue(parentSupplier.hasObservers());
-        verify(mOnChangeCallback).onResult(eq(0));
+        verify(mOnChangeCallback, never()).onResult(anyInt());
 
         parentSupplier.set(mObject1);
         verify(mOnChangeCallback).onResult(eq(mObject1.hashCode()));
@@ -76,8 +79,7 @@
         verify(mOnChangeCallback).onResult(eq(mObject2.hashCode()));
 
         parentSupplier.set(null);
-        // times(2) because it was already called with this value once at the start.
-        verify(mOnChangeCallback, times(2)).onResult(eq(0));
+        verify(mOnChangeCallback, times(1)).onResult(eq(0));
 
         unwrapSupplier.removeObserver(mOnChangeCallback);
         assertFalse(parentSupplier.hasObservers());
@@ -94,4 +96,31 @@
         ShadowLooper.idleMainLooper();
         verify(mOnChangeCallback).onResult(eq(mObject1.hashCode()));
     }
+
+    @Test
+    public void testAddObserver_ShouldNotifyOnAdd() {
+        ObservableSupplierImpl<Object> parentSupplier = new ObservableSupplierImpl<>();
+        parentSupplier.set(3);
+        ObservableSupplier<Integer> unwrapSupplier = make(parentSupplier);
+        unwrapSupplier.addObserver(mOnChangeCallback);
+
+        ShadowLooper.idleMainLooper();
+        verify(mOnChangeCallback).onResult(eq(3));
+
+        parentSupplier.set(mObject1);
+        verify(mOnChangeCallback).onResult(eq(mObject1.hashCode()));
+    }
+
+    @Test
+    public void testAddObserver_ShouldNotNotifyOnAdd() {
+        ObservableSupplierImpl<Object> parentSupplier = new ObservableSupplierImpl<>();
+        ObservableSupplier<Integer> unwrapSupplier = make(parentSupplier);
+        unwrapSupplier.addSyncObserver(mOnChangeCallback);
+
+        ShadowLooper.idleMainLooper();
+        verifyNoInteractions(mOnChangeCallback);
+
+        parentSupplier.set(mObject1);
+        verify(mOnChangeCallback).onResult(eq(mObject1.hashCode()));
+    }
 }
diff --git a/tot/base/android/junit/src/org/chromium/base/task/SequencedTaskRunnerTaskMigrationTest.java b/tot/base/android/junit/src/org/chromium/base/task/SequencedTaskRunnerTaskMigrationTest.java
index dcc53d5..b90e66c 100644
--- a/tot/base/android/junit/src/org/chromium/base/task/SequencedTaskRunnerTaskMigrationTest.java
+++ b/tot/base/android/junit/src/org/chromium/base/task/SequencedTaskRunnerTaskMigrationTest.java
@@ -182,10 +182,9 @@
         public void destroy(long nativeTaskRunnerAndroid) {}
 
         @Override
-        public void postDelayedTask(
-                long nativeTaskRunnerAndroid, Runnable task, long delay, String runnableClassName) {
+        public void postDelayedTask(long nativeTaskRunnerAndroid, long delay, int taskIndex) {
             mReceivedTasksCount.incrementAndGet();
-            mExecutor.execute(task);
+            TaskRunnerImpl.runTask(taskIndex);
         }
 
         public boolean hasReceivedTasks() {
diff --git a/tot/base/android/library_loader/anchor_functions.h b/tot/base/android/library_loader/anchor_functions.h
index 05841e1..5afbe4f 100644
--- a/tot/base/android/library_loader/anchor_functions.h
+++ b/tot/base/android/library_loader/anchor_functions.h
@@ -6,8 +6,8 @@
 #define BASE_ANDROID_LIBRARY_LOADER_ANCHOR_FUNCTIONS_H_
 
 #include <cstdint>
-#include "base/android/library_loader/anchor_functions_buildflags.h"
 
+#include "base/android/library_loader/anchor_functions_buildflags.h"
 #include "base/base_export.h"
 
 #if BUILDFLAG(SUPPORTS_CODE_ORDERING)
diff --git a/tot/base/android/library_loader/library_loader_hooks.cc b/tot/base/android/library_loader/library_loader_hooks.cc
index 361dfa7..c95ae4c 100644
--- a/tot/base/android/library_loader/library_loader_hooks.cc
+++ b/tot/base/android/library_loader/library_loader_hooks.cc
@@ -10,22 +10,18 @@
 #include "base/android/library_loader/anchor_functions_buildflags.h"
 #include "base/android/library_loader/library_prefetcher.h"
 #include "base/android/orderfile/orderfile_buildflags.h"
-#include "base/android/sys_utils.h"
 #include "base/at_exit.h"
 #include "base/base_switches.h"
 #include "base/metrics/histogram.h"
 #include "base/metrics/histogram_functions.h"
 #include "base/metrics/histogram_macros.h"
-#include "build/robolectric_buildflags.h"
+#include "base/system/sys_info.h"
 
-#if BUILDFLAG(IS_ROBOLECTRIC)
-#include "base/base_robolectric_jni/LibraryLoader_jni.h"  // nogncheck
-#else
+// Must come after all headers that specialize FromJniType() / ToJniType().
 #include "base/library_loader_jni/LibraryLoader_jni.h"
-#endif
 
 #if BUILDFLAG(ORDERFILE_INSTRUMENTATION)
-#include "base/android/orderfile/orderfile_instrumentation.h"
+#include "base/android/orderfile/orderfile_instrumentation.h"  // nogncheck
 #endif
 
 namespace base {
@@ -46,7 +42,7 @@
 
 bool IsUsingOrderfileOptimization() {
 #if BUILDFLAG(SUPPORTS_CODE_ORDERING)
-  return SysUtils::IsLowEndDeviceFromJni();
+  return SysInfo::IsLowEndDevice();
 #else  //  !SUPPORTS_CODE_ORDERING
   return false;
 #endif
@@ -61,9 +57,8 @@
   g_registration_callback = func;
 }
 
-static jboolean JNI_LibraryLoader_LibraryLoaded(
-    JNIEnv* env,
-    jint library_process_type) {
+static jboolean JNI_LibraryLoader_LibraryLoaded(JNIEnv* env,
+                                                jint library_process_type) {
   DCHECK_EQ(g_library_process_type, PROCESS_UNINITIALIZED);
   g_library_process_type =
       static_cast<LibraryProcessType>(library_process_type);
@@ -83,8 +78,9 @@
 
   if (g_native_initialization_hook &&
       !g_native_initialization_hook(
-          static_cast<LibraryProcessType>(library_process_type)))
+          static_cast<LibraryProcessType>(library_process_type))) {
     return false;
+  }
   if (g_registration_callback &&
       !g_registration_callback(
           env, nullptr,
diff --git a/tot/base/android/library_loader/library_prefetcher.cc b/tot/base/android/library_loader/library_prefetcher.cc
index cdf01dd..6233ad4 100644
--- a/tot/base/android/library_loader/library_prefetcher.cc
+++ b/tot/base/android/library_loader/library_prefetcher.cc
@@ -15,6 +15,7 @@
 #include <sys/wait.h>
 #include <unistd.h>
 
+#include <algorithm>
 #include <atomic>
 #include <cstdlib>
 #include <memory>
@@ -28,15 +29,15 @@
 #include "base/files/file.h"
 #include "base/format_macros.h"
 #include "base/logging.h"
+#include "base/metrics/histogram_functions.h"
 #include "base/posix/eintr_wrapper.h"
 #include "base/process/process_metrics.h"
-#include "base/ranges/algorithm.h"
 #include "base/strings/string_util.h"
 #include "base/strings/stringprintf.h"
 #include "build/build_config.h"
 
 #if BUILDFLAG(ORDERFILE_INSTRUMENTATION)
-#include "base/android/orderfile/orderfile_instrumentation.h"
+#include "base/android/orderfile/orderfile_instrumentation.h"  // nogncheck
 #endif
 
 #if BUILDFLAG(SUPPORTS_CODE_ORDERING)
@@ -53,12 +54,14 @@
 // successful, |residency| has the size of |end| - |start| in pages.
 // Returns true for success.
 bool Mincore(size_t start, size_t end, std::vector<unsigned char>* residency) {
-  if (start % kPageSize || end % kPageSize)
+  if (start % kPageSize || end % kPageSize) {
     return false;
+  }
   size_t size = end - start;
   size_t size_in_pages = size / kPageSize;
-  if (residency->size() != size_in_pages)
+  if (residency->size() != size_in_pages) {
     residency->resize(size_in_pages);
+  }
   int err = HANDLE_EINTR(
       mincore(reinterpret_cast<void*>(start), size, &(*residency)[0]));
   PLOG_IF(ERROR, err) << "mincore() failed";
@@ -125,8 +128,9 @@
   uint64_t now = static_cast<uint64_t>(ts.tv_sec) * 1000 * 1000 * 1000 +
                  static_cast<uint64_t>(ts.tv_nsec);
   std::vector<unsigned char> residency;
-  if (!Mincore(start, end, &residency))
+  if (!Mincore(start, end, &residency)) {
     return false;
+  }
 
   data->emplace_back(now, std::move(residency));
   return true;
@@ -192,6 +196,8 @@
 
 // These values were used in the past for recording
 // "LibraryLoader.PrefetchDetailedStatus".
+// These values are persisted to logs. Entries should not be renumbered and
+// numeric values should never be reused. See PrefetchStatus in enums.xml.
 enum class PrefetchStatus {
   kSuccess = 0,
   kWrongOrdering = 1,
@@ -216,8 +222,9 @@
   // Always prefetch the ordered section first, as it's reached early during
   // startup, and not necessarily located at the beginning of .text.
   std::vector<std::pair<size_t, size_t>> ranges = {GetOrderedTextRange()};
-  if (!ordered_only)
+  if (!ordered_only) {
     ranges.push_back(GetTextRange());
+  }
 
   pid_t pid = fork();
   if (pid == 0) {
@@ -237,8 +244,9 @@
     int status;
     const pid_t result = HANDLE_EINTR(waitpid(pid, &status, 0));
     if (result == pid) {
-      if (WIFEXITED(status))
+      if (WIFEXITED(status)) {
         return PrefetchStatus::kSuccess;
+      }
       if (WIFSIGNALED(status)) {
         int signal = WTERMSIG(status);
         switch (signal) {
@@ -270,7 +278,12 @@
   // would create a dump as well.
   return;
 #else
+  base::TimeTicks start_time = base::TimeTicks::Now();
   PrefetchStatus status = ForkAndPrefetch(ordered_only);
+  base::UmaHistogramMediumTimes("Android.LibraryLoader.Prefetch.Duration",
+                                base::TimeTicks::Now() - start_time);
+  base::UmaHistogramEnumeration("Android.LibraryLoader.Prefetch.Status",
+                                status);
   if (status != PrefetchStatus::kSuccess) {
     LOG(WARNING) << "Cannot prefetch the library. status = "
                  << static_cast<int>(status);
@@ -286,13 +299,15 @@
 
   std::vector<unsigned char> residency;
   bool ok = Mincore(start, end, &residency);
-  if (!ok)
+  if (!ok) {
     return -1;
+  }
   total_pages += residency.size();
   resident_pages += static_cast<size_t>(
-      ranges::count_if(residency, [](unsigned char x) { return x & 1; }));
-  if (total_pages == 0)
+      std::ranges::count_if(residency, [](unsigned char x) { return x & 1; }));
+  if (total_pages == 0) {
     return -1;
+  }
   return static_cast<int>((100 * resident_pages) / total_pages);
 }
 
@@ -316,8 +331,9 @@
   // Collect residency for about minute (the actual time spent collecting
   // residency can vary, so this is only approximate).
   for (int i = 0; i < 120; ++i) {
-    if (!CollectResidency(range.first, range.second, data.get()))
+    if (!CollectResidency(range.first, range.second, data.get())) {
       return;
+    }
     usleep(5e5);
   }
   DumpResidency(range.first, range.second, std::move(data));
diff --git a/tot/base/android/library_loader/library_prefetcher.h b/tot/base/android/library_loader/library_prefetcher.h
index d1e344e..d9f8b2a 100644
--- a/tot/base/android/library_loader/library_prefetcher.h
+++ b/tot/base/android/library_loader/library_prefetcher.h
@@ -6,7 +6,6 @@
 #define BASE_ANDROID_LIBRARY_LOADER_LIBRARY_PREFETCHER_H_
 
 #include <jni.h>
-
 #include <stdint.h>
 
 #include "base/android/library_loader/anchor_functions_buildflags.h"
diff --git a/tot/base/android/library_loader/library_prefetcher_hooks.cc b/tot/base/android/library_loader/library_prefetcher_hooks.cc
index c82e0c1..172428e 100644
--- a/tot/base/android/library_loader/library_prefetcher_hooks.cc
+++ b/tot/base/android/library_loader/library_prefetcher_hooks.cc
@@ -25,6 +25,12 @@
 #endif
 }
 
+static void JNI_LibraryPrefetcher_PrefetchNativeLibraryForWebView(JNIEnv* env) {
+#if BUILDFLAG(SUPPORTS_CODE_ORDERING)
+  return NativeLibraryPrefetcher::ForkAndPrefetchNativeLibrary(false);
+#endif
+}
+
 static jint JNI_LibraryPrefetcher_PercentageOfResidentNativeLibraryCode(
     JNIEnv* env) {
 #if BUILDFLAG(SUPPORTS_CODE_ORDERING)
diff --git a/tot/base/android/library_loader/library_prefetcher_unittest.cc b/tot/base/android/library_loader/library_prefetcher_unittest.cc
index 9787075..27d4eb2 100644
--- a/tot/base/android/library_loader/library_prefetcher_unittest.cc
+++ b/tot/base/android/library_loader/library_prefetcher_unittest.cc
@@ -7,6 +7,7 @@
 #include <stddef.h>
 #include <stdint.h>
 #include <sys/mman.h>
+
 #include "base/android/library_loader/anchor_functions_buildflags.h"
 #include "base/memory/writable_shared_memory_region.h"
 #include "build/build_config.h"
diff --git a/tot/base/android/linker/linker_jni.cc b/tot/base/android/linker/linker_jni.cc
index 975f94d..03c0c07 100644
--- a/tot/base/android/linker/linker_jni.cc
+++ b/tot/base/android/linker/linker_jni.cc
@@ -79,8 +79,9 @@
                         uintptr_t* out_address,
                         size_t* out_size) {
   const char* position = strstr(buf, "[anon:libwebview reservation]");
-  if (!position)
+  if (!position) {
     return false;
+  }
 
   const char* line_start = position;
   while (line_start > buf) {
@@ -104,8 +105,9 @@
     return false;
   }
 
-  if (strcmp(permissions, "---p"))
+  if (strcmp(permissions, "---p")) {
     return false;
+  }
 
   const size_t kPageSize = GetPageSize();
   if (vma_start % kPageSize || vma_end % kPageSize) {
@@ -155,12 +157,14 @@
     } while (!reached_end && (bytes_read < bytes_requested));
 
     // Return results if the buffer contains the pattern.
-    if (ScanRegionInBuffer(buf, pos + bytes_read, out_address, out_size))
+    if (ScanRegionInBuffer(buf, pos + bytes_read, out_address, out_size)) {
       return true;
+    }
 
     // Did not find the pattern.
-    if (reached_end)
+    if (reached_end) {
       return false;
+    }
 
     // The buffer is filled to the end. Copy the end bytes to the beginning,
     // allowing to scan these bytes on the next iteration.
@@ -350,8 +354,9 @@
   }
 
   ~SharedMemoryFunctions() {
-    if (library_handle)
+    if (library_handle) {
       dlclose(library_handle);
+    }
   }
 
   typedef int (*CreateFunction)(const char*, size_t);
@@ -364,21 +369,24 @@
 };
 
 void NativeLibInfo::ExportLoadInfoToJava() const {
-  if (!env_)
+  if (!env_) {
     return;
+  }
   s_lib_info_fields.SetLoadInfo(env_, java_object_, load_address_, load_size_);
 }
 
 void NativeLibInfo::ExportRelroInfoToJava() const {
-  if (!env_)
+  if (!env_) {
     return;
+  }
   s_lib_info_fields.SetRelroInfo(env_, java_object_, relro_start_, relro_size_,
                                  relro_fd_);
 }
 
 void NativeLibInfo::CloseRelroFd() {
-  if (relro_fd_ == kInvalidFd)
+  if (relro_fd_ == kInvalidFd) {
     return;
+  }
   close(relro_fd_);
   relro_fd_ = kInvalidFd;
 }
@@ -427,10 +435,12 @@
     const ElfW(Phdr)* phdr = &phdrs[i];
     switch (phdr->p_type) {
       case PT_LOAD:
-        if (phdr->p_vaddr < min_vaddr)
+        if (phdr->p_vaddr < min_vaddr) {
           min_vaddr = phdr->p_vaddr;
-        if (phdr->p_vaddr + phdr->p_memsz > max_vaddr)
+        }
+        if (phdr->p_vaddr + phdr->p_memsz > max_vaddr) {
           max_vaddr = phdr->p_vaddr + phdr->p_memsz;
+        }
         break;
       case PT_GNU_RELRO:
         min_relro_vaddr = PageStart(kPageSize, phdr->p_vaddr);
@@ -441,10 +451,12 @@
         // the future. Include the RELRO segment as part of the 'load size'.
         // This way a potential future change in layout of LOAD segments would
         // not open address space for racy mmap(MAP_FIXED).
-        if (min_relro_vaddr < min_vaddr)
+        if (min_relro_vaddr < min_vaddr) {
           min_vaddr = min_relro_vaddr;
-        if (max_vaddr < max_relro_vaddr)
+        }
+        if (max_vaddr < max_relro_vaddr) {
           max_vaddr = max_relro_vaddr;
+        }
         break;
       default:
         break;
@@ -580,8 +592,9 @@
     : env_(env), java_object_(java_object) {}
 
 bool NativeLibInfo::CopyFromJavaObject() {
-  if (!env_)
+  if (!env_) {
     return false;
+  }
 
   if (!s_lib_info_fields.GetLoadInfo(env_, java_object_, &load_address_,
                                      &load_size_)) {
@@ -600,20 +613,23 @@
     LOG_ERROR("Failed to load native library: %s", library_path.c_str());
     return false;
   }
-  if (!CallJniOnLoad(handle))
+  if (!CallJniOnLoad(handle)) {
     return false;
+  }
 
   // Publish the library size and load address back to LibInfo in Java.
   ExportLoadInfoToJava();
 
-  if (!spawn_relro_region)
+  if (!spawn_relro_region) {
     return true;
+  }
 
   // Spawn RELRO to a shared memory region by copying and remapping on top of
   // itself.
   SharedMemoryFunctions functions;
-  if (!functions.IsWorking())
+  if (!functions.IsWorking()) {
     return false;
+  }
   if (!CreateSharedRelroFd(functions)) {
     LOG_ERROR("Failed to create shared RELRO");
     return false;
@@ -716,8 +732,9 @@
   // The library providing these functions will be dlclose()-ed after returning
   // from this context. The extra overhead of dlopen() is OK for testing.
   SharedMemoryFunctions functions;
-  if (!functions.IsWorking())
+  if (!functions.IsWorking()) {
     abort();
+  }
   return CreateSharedRelroFd(functions);
 }
 
@@ -760,8 +777,9 @@
   LOG_INFO("Entering");
   uintptr_t address;
   size_t size;
-  if (!FindWebViewReservation(&address, &size))
+  if (!FindWebViewReservation(&address, &size)) {
     return false;
+  }
   s_lib_info_fields.SetLoadInfo(env, lib_info_obj, address, size);
   return true;
 }
@@ -777,8 +795,9 @@
 
   // Copy the contents from the Java-side LibInfo object.
   NativeLibInfo lib_info = {env, lib_info_obj};
-  if (!lib_info.CopyFromJavaObject())
+  if (!lib_info.CopyFromJavaObject()) {
     return false;
+  }
 
   String library_path(env, jdlopen_ext_path);
   if (!lib_info.LoadLibrary(library_path, spawn_relro_region)) {
diff --git a/tot/base/android/linker/linker_jni.h b/tot/base/android/linker/linker_jni.h
index 0508f07..ed04e66 100644
--- a/tot/base/android/linker/linker_jni.h
+++ b/tot/base/android/linker/linker_jni.h
@@ -186,8 +186,9 @@
                    size_t* load_size) {
     if (load_address) {
       jlong java_address = env->GetLongField(library_info_obj, load_address_id);
-      if (!IsValidAddress(java_address))
+      if (!IsValidAddress(java_address)) {
         return false;
+      }
       *load_address = static_cast<uintptr_t>(java_address);
     }
     if (load_size) {
diff --git a/tot/base/android/linker/linker_jni_onload.cc b/tot/base/android/linker/linker_jni_onload.cc
index b20326f..b0dfdce 100644
--- a/tot/base/android/linker/linker_jni_onload.cc
+++ b/tot/base/android/linker/linker_jni_onload.cc
@@ -24,8 +24,9 @@
     LOG_ERROR("Could not create JNIEnv");
     return -1;
   }
-  if (!LinkerJNIInit(vm, env))
+  if (!LinkerJNIInit(vm, env)) {
     return -1;
+  }
   LOG_INFO("Done");
   return JNI_VERSION_1_4;
 }
diff --git a/tot/base/android/linker/linker_minimal_libcxx.cc b/tot/base/android/linker/linker_minimal_libcxx.cc
index 6969005..cdb6cdc 100644
--- a/tot/base/android/linker/linker_minimal_libcxx.cc
+++ b/tot/base/android/linker/linker_minimal_libcxx.cc
@@ -4,6 +4,7 @@
 
 #include <android/log.h>
 #include <unistd.h>
+
 #include <cstddef>
 #include <cstdlib>
 
@@ -16,8 +17,9 @@
 // it will load, only the linker binary itself.
 void* operator new(size_t size) {
   void* ptr = ::malloc(size);
-  if (ptr != nullptr)
+  if (ptr != nullptr) {
     return ptr;
+  }
 
   // Don't assume it is possible to call any C library function like
   // snprintf() here, since it might allocate heap memory and crash at
diff --git a/tot/base/android/linker/linker_unittest.cc b/tot/base/android/linker/linker_unittest.cc
index 1d12e64..aa72df0 100644
--- a/tot/base/android/linker/linker_unittest.cc
+++ b/tot/base/android/linker/linker_unittest.cc
@@ -90,13 +90,16 @@
         //     address == info->dlpi_addr + program_header->p_vaddr
         // that is, the p_vaddr fields is relative to the object base address.
         // See dl_iterate_phdr(3) for details.
-        if (lookup_address == info->dlpi_addr + phdr->p_vaddr)
+        if (lookup_address == info->dlpi_addr + phdr->p_vaddr) {
           is_matching = true;
+        }
 
-        if (phdr->p_vaddr < min_vaddr)
+        if (phdr->p_vaddr < min_vaddr) {
           min_vaddr = phdr->p_vaddr;
-        if (phdr->p_vaddr + phdr->p_memsz > max_vaddr)
+        }
+        if (phdr->p_vaddr + phdr->p_memsz > max_vaddr) {
           max_vaddr = phdr->p_vaddr + phdr->p_memsz;
+        }
         break;
       case PT_GNU_RELRO:
         min_relro_vaddr = PageStart(kPageSize, phdr->p_vaddr);
@@ -107,10 +110,12 @@
         // the future. Include the RELRO segment as part of the 'load size'.
         // This way a potential future change in layout of LOAD segments would
         // not open address space for racy mmap(MAP_FIXED).
-        if (min_relro_vaddr < min_vaddr)
+        if (min_relro_vaddr < min_vaddr) {
           min_vaddr = min_relro_vaddr;
-        if (max_vaddr < max_relro_vaddr)
+        }
+        if (max_vaddr < max_relro_vaddr) {
           max_vaddr = max_relro_vaddr;
+        }
         break;
       default:
         break;
diff --git a/tot/base/android/locale_utils.cc b/tot/base/android/locale_utils.cc
index 285a3da..f50549b 100644
--- a/tot/base/android/locale_utils.cc
+++ b/tot/base/android/locale_utils.cc
@@ -15,21 +15,17 @@
 
 std::string GetDefaultCountryCode() {
   JNIEnv* env = base::android::AttachCurrentThread();
-  return ConvertJavaStringToUTF8(Java_LocaleUtils_getDefaultCountryCode(env));
+  return Java_LocaleUtils_getDefaultCountryCode(env);
 }
 
 std::string GetDefaultLocaleString() {
   JNIEnv* env = base::android::AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> locale =
-      Java_LocaleUtils_getDefaultLocaleString(env);
-  return ConvertJavaStringToUTF8(locale);
+  return Java_LocaleUtils_getDefaultLocaleString(env);
 }
 
 std::string GetDefaultLocaleListString() {
   JNIEnv* env = base::android::AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> locales =
-      Java_LocaleUtils_getDefaultLocaleListString(env);
-  return ConvertJavaStringToUTF8(locales);
+  return Java_LocaleUtils_getDefaultLocaleListString(env);
 }
 
 }  // namespace android
diff --git a/tot/base/android/meminfo_dump_provider.cc b/tot/base/android/meminfo_dump_provider.cc
index cf621aa..d4f3afc 100644
--- a/tot/base/android/meminfo_dump_provider.cc
+++ b/tot/base/android/meminfo_dump_provider.cc
@@ -3,7 +3,9 @@
 // found in the LICENSE file.
 
 #include "base/android/meminfo_dump_provider.h"
+
 #include <jni.h>
+
 #include "base/android/jni_android.h"
 #include "base/logging.h"
 #include "base/time/time.h"
diff --git a/tot/base/android/meminfo_dump_provider_unittest.cc b/tot/base/android/meminfo_dump_provider_unittest.cc
index f988d65..f587355 100644
--- a/tot/base/android/meminfo_dump_provider_unittest.cc
+++ b/tot/base/android/meminfo_dump_provider_unittest.cc
@@ -3,14 +3,15 @@
 // found in the LICENSE file.
 
 #include "base/android/meminfo_dump_provider.h"
-#include "base/android/build_info.h"
-#include "base/trace_event/base_tracing.h"
-#include "testing/gtest/include/gtest/gtest.h"
 
 #include <cstdint>
 #include <map>
 #include <string>
 
+#include "base/android/build_info.h"
+#include "base/trace_event/base_tracing.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
 namespace base::android {
 
 namespace {
diff --git a/tot/base/android/memory_purge_manager_android.cc b/tot/base/android/memory_purge_manager_android.cc
index 7ae9138..7d98a12 100644
--- a/tot/base/android/memory_purge_manager_android.cc
+++ b/tot/base/android/memory_purge_manager_android.cc
@@ -30,7 +30,3 @@
     JNIEnv* env) {
   return base::android::PreFreezeBackgroundMemoryTrimmer::ShouldUseModernTrim();
 }
-
-static jboolean JNI_MemoryPurgeManager_IsSelfFreezeEnabled(JNIEnv* env) {
-  return base::FeatureList::IsEnabled(base::android::kShouldFreezeSelf);
-}
diff --git a/tot/base/android/native_uma_recorder.cc b/tot/base/android/native_uma_recorder.cc
index 93400df..ff128e3 100644
--- a/tot/base/android/native_uma_recorder.cc
+++ b/tot/base/android/native_uma_recorder.cc
@@ -2,10 +2,13 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include <map>
+
 #include "base/android/callback_android.h"
 #include "base/android/jni_android.h"
 #include "base/android/jni_array.h"
 #include "base/android/jni_string.h"
+#include "base/containers/map_util.h"
 #include "base/format_macros.h"
 #include "base/metrics/histogram.h"
 #include "base/metrics/histogram_base.h"
@@ -14,14 +17,9 @@
 #include "base/metrics/user_metrics.h"
 #include "base/strings/stringprintf.h"
 #include "base/time/time.h"
-#include "build/robolectric_buildflags.h"
 
 // Must come after all headers that specialize FromJniType() / ToJniType().
-#if BUILDFLAG(IS_ROBOLECTRIC)
-#include "base/base_robolectric_jni/NativeUmaRecorder_jni.h"  // nogncheck
-#else
 #include "base/metrics_jni/NativeUmaRecorder_jni.h"
-#endif
 
 namespace base {
 namespace android {
@@ -29,25 +27,25 @@
 namespace {
 
 using HistogramsSnapshot =
-    std::map<std::string, std::unique_ptr<HistogramSamples>>;
+    std::map<std::string, std::unique_ptr<HistogramSamples>, std::less<>>;
 
 std::string HistogramConstructionParamsToString(HistogramBase* histogram) {
-  std::string params_str = histogram->histogram_name();
+  std::string_view name = histogram->histogram_name();
   switch (histogram->GetHistogramType()) {
     case HISTOGRAM:
     case LINEAR_HISTOGRAM:
     case BOOLEAN_HISTOGRAM:
     case CUSTOM_HISTOGRAM: {
       Histogram* hist = static_cast<Histogram*>(histogram);
-      params_str += StringPrintf("/%d/%d/%" PRIuS, hist->declared_min(),
-                                 hist->declared_max(), hist->bucket_count());
-      break;
+      return StringPrintf("%.*s/%d/%d/%" PRIuS, name.length(), name.data(),
+                          hist->declared_min(), hist->declared_max(),
+                          hist->bucket_count());
     }
     case SPARSE_HISTOGRAM:
     case DUMMY_HISTOGRAM:
       break;
   }
-  return params_str;
+  return std::string(name);
 }
 
 // Convert a jlong |histogram_hint| from Java to a HistogramBase* via a cast.
@@ -58,12 +56,11 @@
 }
 
 void CheckHistogramArgs(JNIEnv* env,
-                        jstring j_histogram_name,
+                        std::string& histogram_name,
                         int32_t expected_min,
                         int32_t expected_max,
                         size_t expected_bucket_count,
                         HistogramBase* histogram) {
-  std::string histogram_name = ConvertJavaStringToUTF8(env, j_histogram_name);
   bool valid_arguments = Histogram::InspectConstructionArguments(
       histogram_name, &expected_min, &expected_max, &expected_bucket_count);
   DCHECK(valid_arguments);
@@ -75,50 +72,46 @@
 }
 
 HistogramBase* BooleanHistogram(JNIEnv* env,
-                                jstring j_histogram_name,
+                                std::string& histogram_name,
                                 jlong j_histogram_hint) {
-  DCHECK(j_histogram_name);
   HistogramBase* histogram = HistogramFromHint(j_histogram_hint);
-  if (histogram)
+  if (histogram) {
     return histogram;
+  }
 
-  std::string histogram_name = ConvertJavaStringToUTF8(env, j_histogram_name);
   histogram = BooleanHistogram::FactoryGet(
       histogram_name, HistogramBase::kUmaTargetedHistogramFlag);
   return histogram;
 }
 
 HistogramBase* ExponentialHistogram(JNIEnv* env,
-                                    jstring j_histogram_name,
+                                    std::string& histogram_name,
                                     jlong j_histogram_hint,
                                     jint j_min,
                                     jint j_max,
                                     jint j_num_buckets) {
-  DCHECK(j_histogram_name);
   int32_t min = static_cast<int32_t>(j_min);
   int32_t max = static_cast<int32_t>(j_max);
   size_t num_buckets = static_cast<size_t>(j_num_buckets);
   HistogramBase* histogram = HistogramFromHint(j_histogram_hint);
   if (histogram) {
-    CheckHistogramArgs(env, j_histogram_name, min, max, num_buckets, histogram);
+    CheckHistogramArgs(env, histogram_name, min, max, num_buckets, histogram);
     return histogram;
   }
 
   DCHECK_GE(min, 1) << "The min expected sample must be >= 1";
 
-  std::string histogram_name = ConvertJavaStringToUTF8(env, j_histogram_name);
   histogram = Histogram::FactoryGet(histogram_name, min, max, num_buckets,
                                     HistogramBase::kUmaTargetedHistogramFlag);
   return histogram;
 }
 
 HistogramBase* LinearHistogram(JNIEnv* env,
-                               jstring j_histogram_name,
+                               std::string& j_histogram_name,
                                jlong j_histogram_hint,
                                jint j_min,
                                jint j_max,
                                jint j_num_buckets) {
-  DCHECK(j_histogram_name);
   int32_t min = static_cast<int32_t>(j_min);
   int32_t max = static_cast<int32_t>(j_max);
   size_t num_buckets = static_cast<size_t>(j_num_buckets);
@@ -128,7 +121,7 @@
     return histogram;
   }
 
-  std::string histogram_name = ConvertJavaStringToUTF8(env, j_histogram_name);
+  std::string histogram_name = j_histogram_name;
   histogram =
       LinearHistogram::FactoryGet(histogram_name, min, max, num_buckets,
                                   HistogramBase::kUmaTargetedHistogramFlag);
@@ -136,14 +129,13 @@
 }
 
 HistogramBase* SparseHistogram(JNIEnv* env,
-                               jstring j_histogram_name,
+                               std::string& histogram_name,
                                jlong j_histogram_hint) {
-  DCHECK(j_histogram_name);
   HistogramBase* histogram = HistogramFromHint(j_histogram_hint);
-  if (histogram)
+  if (histogram) {
     return histogram;
+  }
 
-  std::string histogram_name = ConvertJavaStringToUTF8(env, j_histogram_name);
   histogram = SparseHistogram::FactoryGet(
       histogram_name, HistogramBase::kUmaTargetedHistogramFlag);
   return histogram;
@@ -163,7 +155,7 @@
 
 jlong JNI_NativeUmaRecorder_RecordBooleanHistogram(
     JNIEnv* env,
-    const JavaParamRef<jstring>& j_histogram_name,
+    std::string& j_histogram_name,
     jlong j_histogram_hint,
     jboolean j_sample) {
   bool sample = static_cast<bool>(j_sample);
@@ -175,7 +167,7 @@
 
 jlong JNI_NativeUmaRecorder_RecordExponentialHistogram(
     JNIEnv* env,
-    const JavaParamRef<jstring>& j_histogram_name,
+    std::string& j_histogram_name,
     jlong j_histogram_hint,
     jint j_sample,
     jint j_min,
@@ -188,14 +180,13 @@
   return reinterpret_cast<jlong>(histogram);
 }
 
-jlong JNI_NativeUmaRecorder_RecordLinearHistogram(
-    JNIEnv* env,
-    const JavaParamRef<jstring>& j_histogram_name,
-    jlong j_histogram_hint,
-    jint j_sample,
-    jint j_min,
-    jint j_max,
-    jint j_num_buckets) {
+jlong JNI_NativeUmaRecorder_RecordLinearHistogram(JNIEnv* env,
+                                                  std::string& j_histogram_name,
+                                                  jlong j_histogram_hint,
+                                                  jint j_sample,
+                                                  jint j_min,
+                                                  jint j_max,
+                                                  jint j_num_buckets) {
   int sample = static_cast<int>(j_sample);
   HistogramBase* histogram = LinearHistogram(
       env, j_histogram_name, j_histogram_hint, j_min, j_max, j_num_buckets);
@@ -203,11 +194,10 @@
   return reinterpret_cast<jlong>(histogram);
 }
 
-jlong JNI_NativeUmaRecorder_RecordSparseHistogram(
-    JNIEnv* env,
-    const JavaParamRef<jstring>& j_histogram_name,
-    jlong j_histogram_hint,
-    jint j_sample) {
+jlong JNI_NativeUmaRecorder_RecordSparseHistogram(JNIEnv* env,
+                                                  std::string& j_histogram_name,
+                                                  jlong j_histogram_hint,
+                                                  jint j_sample) {
   int sample = static_cast<int>(j_sample);
   HistogramBase* histogram =
       SparseHistogram(env, j_histogram_name, j_histogram_hint);
@@ -242,8 +232,9 @@
   if (snapshot_ptr) {
     auto* snapshot = reinterpret_cast<HistogramsSnapshot*>(snapshot_ptr);
     auto snapshot_data = snapshot->find(name);
-    if (snapshot_data != snapshot->end())
+    if (snapshot_data != snapshot->end()) {
       actual_count -= snapshot_data->second->GetCount(sample);
+    }
   }
 
   return actual_count;
@@ -263,8 +254,9 @@
   if (snapshot_ptr) {
     auto* snapshot = reinterpret_cast<HistogramsSnapshot*>(snapshot_ptr);
     auto snapshot_data = snapshot->find(name);
-    if (snapshot_data != snapshot->end())
+    if (snapshot_data != snapshot->end()) {
       actual_count -= snapshot_data->second->TotalCount();
+    }
   }
   return actual_count;
 }
@@ -285,9 +277,9 @@
   std::unique_ptr<HistogramSamples> samples = histogram->SnapshotSamples();
   for (auto sampleCountIterator = samples->Iterator();
        !sampleCountIterator->Done(); sampleCountIterator->Next()) {
-    HistogramBase::Sample min;
+    HistogramBase::Sample32 min;
     int64_t max;
-    HistogramBase::Count count;
+    HistogramBase::Count32 count;
     sampleCountIterator->Get(&min, &max, &count);
     buckets.push_back(min);
     buckets.push_back(max);
@@ -300,7 +292,8 @@
 jlong JNI_NativeUmaRecorder_CreateHistogramSnapshotForTesting(JNIEnv* env) {
   HistogramsSnapshot* snapshot = new HistogramsSnapshot();
   for (const auto* const histogram : StatisticsRecorder::GetHistograms()) {
-    (*snapshot)[histogram->histogram_name()] = histogram->SnapshotSamples();
+    InsertOrAssign(*snapshot, histogram->histogram_name(),
+                   histogram->SnapshotSamples());
   }
   return reinterpret_cast<intptr_t>(snapshot);
 }
diff --git a/tot/base/android/orderfile/orderfile_instrumentation.cc b/tot/base/android/orderfile/orderfile_instrumentation.cc
index 391279b..0c4969d 100644
--- a/tot/base/android/orderfile/orderfile_instrumentation.cc
+++ b/tot/base/android/orderfile/orderfile_instrumentation.cc
@@ -127,8 +127,9 @@
 __attribute__((always_inline, no_instrument_function)) void RecordAddress(
     size_t address) {
   int index = g_data_index.load(std::memory_order_relaxed);
-  if (index >= kPhases)
+  if (index >= kPhases) {
     return;
+  }
 
   const size_t start =
       for_testing ? kStartOfTextForTesting : base::android::kStartOfText;
@@ -171,12 +172,14 @@
   // allows the cache line to remain shared acoss CPUs in this case.
   uint32_t value = element->load(std::memory_order_relaxed);
   uint32_t mask = 1 << (offset_index % 32);
-  if (value & mask)
+  if (value & mask) {
     return;
+  }
 
   auto before = element->fetch_or(mask, std::memory_order_relaxed);
-  if (before & mask)
+  if (before & mask) {
     return;
+  }
 
   // We were the first one to set the element, record it in the ordered
   // elements list.
@@ -214,8 +217,9 @@
     // visible in this thread yet. Safe to skip, also because the function at
     // the start of text is never called.
     auto offset = data.ordered_offsets[i].load(std::memory_order_relaxed);
-    if (!offset)
+    if (!offset) {
       continue;
+    }
     auto offset_str = base::StringPrintf("%" PRIuS "\n", offset);
     if (!file.WriteAtCurrentPosAndCheck(base::as_byte_span(offset_str))) {
       // If the file could be opened, but writing has failed, it's likely that
@@ -236,8 +240,9 @@
 
   for (int phase = 0; phase < kPhases; phase++) {
     std::string tag_str;
-    if (!tag.empty())
+    if (!tag.empty()) {
       tag_str = base::StringPrintf("%s-", tag.c_str());
+    }
     auto path = base::StringPrintf(
         "/data/local/tmp/chrome/orderfile/profile-hitmap-%s%d-%" PRIu64
         ".txt_%d",
@@ -286,8 +291,9 @@
   // Using std::thread and not using base::TimeTicks() in order to to not call
   // too many base:: symbols that would pollute the reached symbol dumps.
   struct timespec ts;
-  if (clock_gettime(CLOCK_MONOTONIC, &ts))
+  if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
     PLOG(FATAL) << "clock_gettime.";
+  }
   uint64_t start_ns_since_epoch =
       static_cast<uint64_t>(ts.tv_sec) * 1000 * 1000 * 1000 + ts.tv_nsec;
   int pid = getpid();
@@ -343,8 +349,9 @@
   size_t max_index = g_data[0].index.load(std::memory_order_relaxed);
   for (size_t i = 0; i < max_index; ++i) {
     auto value = g_data[0].ordered_offsets[i].load(std::memory_order_relaxed);
-    if (value)
+    if (value) {
       result.push_back(value);
+    }
   }
   return result;
 }
diff --git a/tot/base/android/orderfile/orderfile_instrumentation_perftest.cc b/tot/base/android/orderfile/orderfile_instrumentation_perftest.cc
index 551fcf0..8d60f20 100644
--- a/tot/base/android/orderfile/orderfile_instrumentation_perftest.cc
+++ b/tot/base/android/orderfile/orderfile_instrumentation_perftest.cc
@@ -31,8 +31,9 @@
     }
   };
   if (threads != 1) {
-    for (int i = 0; i < threads - 1; ++i)
+    for (int i = 0; i < threads - 1; ++i) {
       std::thread(iterate).detach();
+    }
   }
   auto tick = base::TimeTicks::Now();
   iterate();
diff --git a/tot/base/android/path_utils.cc b/tot/base/android/path_utils.cc
index 9e8ec4e..7ca92ec 100644
--- a/tot/base/android/path_utils.cc
+++ b/tot/base/android/path_utils.cc
@@ -18,33 +18,32 @@
 
 bool GetDataDirectory(FilePath* result) {
   JNIEnv* env = AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> path = Java_PathUtils_getDataDirectory(env);
-  FilePath data_path(ConvertJavaStringToUTF8(path));
+  std::string path = Java_PathUtils_getDataDirectory(env);
+  FilePath data_path(path);
   *result = data_path;
   return true;
 }
 
 bool GetCacheDirectory(FilePath* result) {
   JNIEnv* env = AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> path = Java_PathUtils_getCacheDirectory(env);
-  FilePath cache_path(ConvertJavaStringToUTF8(path));
+  std::string path = Java_PathUtils_getCacheDirectory(env);
+  FilePath cache_path(path);
   *result = cache_path;
   return true;
 }
 
 bool GetThumbnailCacheDirectory(FilePath* result) {
   JNIEnv* env = AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> path =
-      Java_PathUtils_getThumbnailCacheDirectory(env);
-  FilePath thumbnail_cache_path(ConvertJavaStringToUTF8(path));
+  std::string path = Java_PathUtils_getThumbnailCacheDirectory(env);
+  FilePath thumbnail_cache_path(path);
   *result = thumbnail_cache_path;
   return true;
 }
 
 bool GetDownloadsDirectory(FilePath* result) {
   JNIEnv* env = AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> path = Java_PathUtils_getDownloadsDirectory(env);
-  FilePath downloads_path(ConvertJavaStringToUTF8(path));
+  std::string path = Java_PathUtils_getDownloadsDirectory(env);
+  FilePath downloads_path(path);
   *result = downloads_path;
   return true;
 }
@@ -56,8 +55,9 @@
   base::android::AppendJavaStringArrayToStringVector(env, jarray, &dirs);
 
   std::vector<base::FilePath> file_paths;
-  for (const auto& dir : dirs)
+  for (const auto& dir : dirs) {
     file_paths.emplace_back(dir);
+  }
   return file_paths;
 }
 
@@ -68,25 +68,24 @@
   base::android::AppendJavaStringArrayToStringVector(env, jarray, &dirs);
 
   std::vector<base::FilePath> file_paths;
-  for (const auto& dir : dirs)
+  for (const auto& dir : dirs) {
     file_paths.emplace_back(dir);
+  }
   return file_paths;
 }
 
 bool GetNativeLibraryDirectory(FilePath* result) {
   JNIEnv* env = AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> path =
-      Java_PathUtils_getNativeLibraryDirectory(env);
-  FilePath library_path(ConvertJavaStringToUTF8(path));
+  std::string path = Java_PathUtils_getNativeLibraryDirectory(env);
+  FilePath library_path(path);
   *result = library_path;
   return true;
 }
 
 bool GetExternalStorageDirectory(FilePath* result) {
   JNIEnv* env = AttachCurrentThread();
-  ScopedJavaLocalRef<jstring> path =
-      Java_PathUtils_getExternalStorageDirectory(env);
-  FilePath storage_path(ConvertJavaStringToUTF8(path));
+  std::string path = Java_PathUtils_getExternalStorageDirectory(env);
+  FilePath storage_path(path);
   *result = storage_path;
   return true;
 }
diff --git a/tot/base/android/path_utils.h b/tot/base/android/path_utils.h
index 216bb73..af4deb9 100644
--- a/tot/base/android/path_utils.h
+++ b/tot/base/android/path_utils.h
@@ -6,6 +6,7 @@
 #define BASE_ANDROID_PATH_UTILS_H_
 
 #include <jni.h>
+
 #include <vector>
 
 #include "base/base_export.h"
diff --git a/tot/base/android/path_utils_unittest.cc b/tot/base/android/path_utils_unittest.cc
index 53776cf..40e9815 100644
--- a/tot/base/android/path_utils_unittest.cc
+++ b/tot/base/android/path_utils_unittest.cc
@@ -3,10 +3,10 @@
 // found in the LICENSE file.
 
 #include "base/android/path_utils.h"
+
 #include "base/files/file_path.h"
 #include "base/files/file_util.h"
 #include "base/strings/string_util.h"
-
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace base {
@@ -44,8 +44,7 @@
   FilePath path;
   GetCacheDirectory(&path);
   ExpectEither("/data/data/org.chromium.native_test/cache",
-               "/data/user/0/org.chromium.native_test/cache",
-               path.value());
+               "/data/user/0/org.chromium.native_test/cache", path.value());
 }
 
 TEST_F(PathUtilsTest, TestGetNativeLibraryDirectory) {
diff --git a/tot/base/android/pre_freeze_background_memory_trimmer.cc b/tot/base/android/pre_freeze_background_memory_trimmer.cc
index 1815ef9..4ea9428 100644
--- a/tot/base/android/pre_freeze_background_memory_trimmer.cc
+++ b/tot/base/android/pre_freeze_background_memory_trimmer.cc
@@ -19,13 +19,16 @@
 #include "base/functional/bind.h"
 #include "base/logging.h"
 #include "base/memory/page_size.h"
+#include "base/metrics/field_trial_params.h"
 #include "base/metrics/histogram_functions.h"
+#include "base/rand_util.h"
 #include "base/strings/strcat.h"
 #include "base/task/sequenced_task_runner.h"
 #include "base/task/thread_pool.h"
 #include "base/task/thread_pool/thread_pool_instance.h"
 #include "base/time/time.h"
 #include "base/trace_event/base_tracing.h"
+#include "base/trace_event/named_trigger.h"  // no-presubmit-check
 
 namespace base::android {
 namespace {
@@ -36,9 +39,15 @@
 enum class MetricsFailure {
   kAlreadyRunning,
   kSizeMismatch,
-  kMaxValue = kSizeMismatch
+  kMeasureFailure,
+  kMaxValue = kMeasureFailure
 };
 
+// These values are logged to UMA. Entries should not be renumbered and
+// numeric values should never be reused. Please keep in sync with
+// "PreFreezeReadProcMapsType" in tools/metrics/histograms/enums.xml.
+enum class ReadProcMaps { kFailed, kEmpty, kSuccess, kMaxValue = kSuccess };
+
 // This constant is chosen arbitrarily, to allow time for the background tasks
 // to finish running BEFORE collecting metrics.
 const base::TimeDelta kDelayForMetrics = base::Seconds(2);
@@ -47,6 +56,10 @@
   return v / 1024 / 1024;
 }
 
+uint64_t MiBToBytes(uint64_t v) {
+  return v * 1024 * 1024;
+}
+
 const char* GetProcessType() {
   CHECK(base::CommandLine::InitializedForCurrentProcess());
   const std::string type =
@@ -59,11 +72,17 @@
   return process_type;
 }
 
-std::string GetMetricName(std::string_view name, std::string_view suffix) {
+std::string GetPreFreezeMetricName(std::string_view name,
+                                   std::string_view suffix) {
   const char* process_type = GetProcessType();
   return StrCat({"Memory.PreFreeze2.", process_type, ".", name, ".", suffix});
 }
 
+std::string GetSelfCompactionMetricName(std::string_view name,
+                                        std::string_view suffix) {
+  return StrCat({"Memory.SelfCompact2.Renderer.", name, ".", suffix});
+}
+
 class PrivateMemoryFootprintMetric
     : public PreFreezeBackgroundMemoryTrimmer::PreFreezeMetric {
  public:
@@ -85,18 +104,59 @@
 
 bool PrivateMemoryFootprintMetric::did_register_ = false;
 
-void MaybeRecordMetric(std::optional<uint64_t> value_bytes,
-                       std::string_view metric_name,
-                       std::string_view suffix) {
+void MaybeRecordPreFreezeMetric(std::optional<uint64_t> value_bytes,
+                                std::string_view metric_name,
+                                std::string_view suffix) {
   // Skip recording the metric if we failed to get the PMF.
   if (!value_bytes.has_value()) {
     return;
   }
 
-  UmaHistogramMemoryMB(GetMetricName(metric_name, suffix),
+  UmaHistogramMemoryMB(GetPreFreezeMetricName(metric_name, suffix),
                        static_cast<int>(BytesToMiB(value_bytes.value())));
 }
 
+void RecordSelfCompactionMetric(size_t value_bytes,
+                                std::string_view metric_name,
+                                std::string_view suffix) {
+  UmaHistogramMemoryMB(GetSelfCompactionMetricName(metric_name, suffix),
+                       static_cast<int>(BytesToMiB(value_bytes)));
+}
+
+void RecordSelfCompactionMetrics(const debug::SmapsRollup& value,
+                                 std::string_view suffix) {
+  RecordSelfCompactionMetric(value.rss, "Rss", suffix);
+  RecordSelfCompactionMetric(value.pss, "Pss", suffix);
+  RecordSelfCompactionMetric(value.pss_anon, "PssAnon", suffix);
+  RecordSelfCompactionMetric(value.pss_file, "PssFile", suffix);
+  RecordSelfCompactionMetric(value.swap_pss, "SwapPss", suffix);
+}
+
+void RecordSelfCompactionDiffMetric(size_t before_value_bytes,
+                                    size_t after_value_bytes,
+                                    std::string_view name,
+                                    std::string_view suffix) {
+  size_t diff_non_negative = std::max(before_value_bytes, after_value_bytes) -
+                             std::min(before_value_bytes, after_value_bytes);
+  const std::string full_suffix = StrCat(
+      {"Diff.", suffix, ".",
+       before_value_bytes < after_value_bytes ? "Increase" : "Decrease"});
+  RecordSelfCompactionMetric(diff_non_negative, name, full_suffix);
+}
+
+void RecordSelfCompactionDiffMetrics(const debug::SmapsRollup before,
+                                     const debug::SmapsRollup after,
+                                     std::string_view suffix) {
+  RecordSelfCompactionDiffMetric(before.rss, after.rss, "Rss", suffix);
+  RecordSelfCompactionDiffMetric(before.pss, after.pss, "Pss", suffix);
+  RecordSelfCompactionDiffMetric(before.pss_anon, after.pss_anon, "PssAnon",
+                                 suffix);
+  RecordSelfCompactionDiffMetric(before.pss_file, after.pss_file, "PssFile",
+                                 suffix);
+  RecordSelfCompactionDiffMetric(before.swap_pss, after.swap_pss, "SwapPss",
+                                 suffix);
+}
+
 std::optional<uint64_t> Diff(std::optional<uint64_t> before,
                              std::optional<uint64_t> after) {
   if (!before.has_value() || !before.has_value()) {
@@ -134,18 +194,24 @@
 
 }  // namespace
 
-BASE_FEATURE(kOnPreFreezeMemoryTrim,
-             "OnPreFreezeMemoryTrim",
-             FEATURE_ENABLED_BY_DEFAULT);
-
-BASE_FEATURE(kIsTrimMemoryBackgroundCritical,
-             "IsTrimMemoryBackgroundCritical",
-             FEATURE_ENABLED_BY_DEFAULT);
-
 BASE_FEATURE(kShouldFreezeSelf,
              "ShouldFreezeSelf",
              FEATURE_DISABLED_BY_DEFAULT);
 
+// Max amount of compaction to do in each chunk, measured in MiB.
+BASE_FEATURE_PARAM(size_t,
+                   kShouldFreezeSelfMaxSize,
+                   &kShouldFreezeSelf,
+                   "max_chunk_size",
+                   10);
+
+// Delay between running pre-freeze tasks and doing self-freeze, measured in s.
+BASE_FEATURE_PARAM(size_t,
+                   kShouldFreezeSelfDelayAfterPreFreezeTasks,
+                   &kShouldFreezeSelf,
+                   "delay_after_tasks",
+                   30);
+
 PreFreezeBackgroundMemoryTrimmer::PreFreezeBackgroundMemoryTrimmer()
     : supports_modern_trim_(BuildInfo::GetInstance()->sdk_int() >=
                             SDK_VERSION_U) {}
@@ -161,7 +227,7 @@
   // determine the current process, which is used for the names of metrics
   // below.
   CHECK(base::CommandLine::InitializedForCurrentProcess());
-  base::AutoLock locker(lock_);
+  base::AutoLock locker(lock());
   if (metrics_.size() != values_before_.size()) {
     UmaHistogramEnumeration("Memory.PreFreeze2.RecordMetricsFailureType",
                             MetricsFailure::kSizeMismatch);
@@ -175,9 +241,16 @@
 
     std::optional<uint64_t> value_after = metric->Measure();
 
-    MaybeRecordMetric(value_before, metric->name(), "Before");
-    MaybeRecordMetric(value_after, metric->name(), "After");
-    MaybeRecordMetric(Diff(value_before, value_after), metric->name(), "Diff");
+    if (!value_after) {
+      UmaHistogramEnumeration("Memory.PreFreeze2.RecordMetricsFailureType",
+                              MetricsFailure::kMeasureFailure);
+      continue;
+    }
+
+    MaybeRecordPreFreezeMetric(value_before, metric->name(), "Before");
+    MaybeRecordPreFreezeMetric(value_after, metric->name(), "After");
+    MaybeRecordPreFreezeMetric(Diff(value_before, value_after), metric->name(),
+                               "Diff");
   }
 
   values_before_.clear();
@@ -234,6 +307,62 @@
       kDelayForMetrics);
 }
 
+void PreFreezeBackgroundMemoryTrimmer::CompactionMetric::
+    MaybeRecordCompactionMetrics() {
+  // If we did not record smaps_rollup for any reason, such as returning to
+  // foreground, being frozen by App Freezer, or failing to read
+  // /proc/self/smaps_rollup, skip emitting metrics.
+  if (!smaps_before_.has_value() || !smaps_after_.has_value() ||
+      !smaps_after_1s_.has_value() || !smaps_after_10s_.has_value() ||
+      !smaps_after_60s_.has_value()) {
+    return;
+  }
+
+  if (!ShouldContinueSelfCompaction(self_compaction_triggered_at_)) {
+    return;
+  }
+
+  // Record absolute values of each metric.
+  RecordSelfCompactionMetrics(*smaps_before_, "Before");
+  RecordSelfCompactionMetrics(*smaps_after_, "After");
+  RecordSelfCompactionMetrics(*smaps_after_1s_, "After1s");
+  RecordSelfCompactionMetrics(*smaps_after_10s_, "After10s");
+  RecordSelfCompactionMetrics(*smaps_after_60s_, "After60s");
+
+  // Record diff of before and after to see how much memory was compacted.
+  RecordSelfCompactionDiffMetrics(*smaps_before_, *smaps_after_, "BeforeAfter");
+
+  // Record diff after a delay, so we can see if any memory comes back after
+  // compaction.
+  RecordSelfCompactionDiffMetrics(*smaps_after_, *smaps_after_1s_, "After1s");
+  RecordSelfCompactionDiffMetrics(*smaps_after_, *smaps_after_10s_, "After10s");
+  RecordSelfCompactionDiffMetrics(*smaps_after_, *smaps_after_60s_, "After60s");
+}
+
+void PreFreezeBackgroundMemoryTrimmer::CompactionMetric::RecordSmapsRollup(
+    std::optional<debug::SmapsRollup>* target) {
+  if (!ShouldContinueSelfCompaction(self_compaction_triggered_at_)) {
+    return;
+  }
+
+  *target = debug::ReadAndParseSmapsRollup();
+
+  MaybeRecordCompactionMetrics();
+}
+
+void PreFreezeBackgroundMemoryTrimmer::CompactionMetric::
+    RecordSmapsRollupWithDelay(std::optional<debug::SmapsRollup>* target,
+                               base::TimeDelta delay) {
+  base::ThreadPool::PostDelayedTask(
+      FROM_HERE, {base::TaskPriority::BEST_EFFORT, MayBlock()},
+      base::BindOnce(&PreFreezeBackgroundMemoryTrimmer::CompactionMetric::
+                         RecordSmapsRollup,
+                     // target is a member a of |this|, so it's lifetime is
+                     // always ok here.
+                     this, base::Unretained(target)),
+      delay);
+}
+
 // static
 void PreFreezeBackgroundMemoryTrimmer::PostDelayedBackgroundTask(
     scoped_refptr<base::SequencedTaskRunner> task_runner,
@@ -262,14 +391,6 @@
 
   RegisterPrivateMemoryFootprintMetric();
 
-  if (!base::FeatureList::IsEnabled(kOnPreFreezeMemoryTrim)) {
-    task_runner->PostDelayedTask(
-        from_here,
-        BindOnce(std::move(task), MemoryReductionTaskContext::kDelayExpired),
-        delay);
-    return;
-  }
-
   PostDelayedBackgroundTaskModern(task_runner, from_here, std::move(task),
                                   delay);
 }
@@ -293,7 +414,7 @@
     return;
   }
 
-  base::AutoLock locker(lock_);
+  base::AutoLock locker(lock());
   PostDelayedBackgroundTaskModernHelper(std::move(task_runner), from_here,
                                         std::move(task), delay);
 }
@@ -314,7 +435,7 @@
 // static
 void PreFreezeBackgroundMemoryTrimmer::RegisterMemoryMetric(
     const PreFreezeMetric* metric) {
-  base::AutoLock locker(Instance().lock_);
+  base::AutoLock locker(lock());
   Instance().RegisterMemoryMetricInternal(metric);
 }
 
@@ -332,7 +453,7 @@
 // static
 void PreFreezeBackgroundMemoryTrimmer::UnregisterMemoryMetric(
     const PreFreezeMetric* metric) {
-  base::AutoLock locker(Instance().lock_);
+  base::AutoLock locker(lock());
   Instance().UnregisterMemoryMetricInternal(metric);
 }
 
@@ -348,38 +469,163 @@
   metrics_.erase(metrics_.begin() + index);
 }
 
+void PreFreezeBackgroundMemoryTrimmer::SetOnStartSelfCompactionCallback(
+    base::RepeatingCallback<void(void)> callback) {
+  base::AutoLock locker(lock());
+  Instance().on_self_compact_callback_ = callback;
+}
+
 // static
 bool PreFreezeBackgroundMemoryTrimmer::SelfCompactionIsSupported() {
   return IsMadvisePageoutSupported();
 }
 
 // static
-std::optional<int64_t> PreFreezeBackgroundMemoryTrimmer::CompactSelf() {
-  // MADV_PAGEOUT was only added in Linux 5.4, so do nothing in earlier
-  // versions.
-  if (!SelfCompactionIsSupported()) {
-    return std::nullopt;
+bool PreFreezeBackgroundMemoryTrimmer::ShouldContinueSelfCompaction(
+    base::TimeTicks self_compaction_triggered_at) {
+  base::AutoLock locker(lock());
+  return Instance().self_compaction_last_cancelled_ <
+         self_compaction_triggered_at;
+}
+
+void PreFreezeBackgroundMemoryTrimmer::MaybePostSelfCompactionTask(
+    scoped_refptr<base::SequencedTaskRunner> task_runner,
+    std::vector<debug::MappedMemoryRegion> regions,
+    scoped_refptr<CompactionMetric> metric,
+    uint64_t max_size,
+    base::TimeTicks triggered_at) {
+  TRACE_EVENT0("base", "MaybePostSelfCompactionTask");
+  if (ShouldContinueSelfCompaction(triggered_at) && !regions.empty()) {
+    task_runner->PostDelayedTask(
+        FROM_HERE,
+        // |base::Unretained| is safe here because we never destroy |this|.
+        base::BindOnce(&PreFreezeBackgroundMemoryTrimmer::SelfCompactionTask,
+                       base::Unretained(this), task_runner, std::move(regions),
+                       std::move(metric), max_size, triggered_at),
+        GetDelayBetweenSelfCompaction());
+  } else {
+    FinishSelfCompaction(std::move(metric), triggered_at);
+  }
+}
+
+void PreFreezeBackgroundMemoryTrimmer::SelfCompactionTask(
+    scoped_refptr<base::SequencedTaskRunner> task_runner,
+    std::vector<debug::MappedMemoryRegion> regions,
+    scoped_refptr<CompactionMetric> metric,
+    uint64_t max_size,
+    base::TimeTicks triggered_at) {
+  if (!ShouldContinueSelfCompaction(triggered_at)) {
+    return;
   }
 
-  std::vector<debug::MappedMemoryRegion> regions;
+  TRACE_EVENT0("base", "SelfCompactionTask");
 
-  std::string proc_maps;
-  if (!debug::ReadProcMaps(&proc_maps) || !ParseProcMaps(proc_maps, &regions)) {
-    return std::nullopt;
+  CompactMemory(&regions, max_size);
+
+  MaybePostSelfCompactionTask(std::move(task_runner), std::move(regions),
+                              std::move(metric), max_size, triggered_at);
+}
+
+void PreFreezeBackgroundMemoryTrimmer::StartSelfCompaction(
+    scoped_refptr<base::SequencedTaskRunner> task_runner,
+    std::vector<debug::MappedMemoryRegion> regions,
+    uint64_t max_bytes,
+    base::TimeTicks triggered_at) {
+  scoped_refptr<CompactionMetric> metric =
+      MakeRefCounted<CompactionMetric>(triggered_at, base::TimeTicks::Now());
+  TRACE_EVENT0("base", "StartSelfCompaction");
+  base::trace_event::EmitNamedTrigger("start-self-compaction");
+  {
+    base::AutoLock locker(lock());
+    process_compacted_metadata_.emplace(
+        "PreFreezeBackgroundMemoryTrimmer.ProcessCompacted",
+        /*is_compacted=*/1, base::SampleMetadataScope::kProcess);
+    if (on_self_compact_callback_) {
+      on_self_compact_callback_.Run();
+    }
   }
+  metric->RecordBeforeMetrics();
+  MaybePostSelfCompactionTask(std::move(task_runner), std::move(regions),
+                              std::move(metric), max_bytes, triggered_at);
+}
 
-  if (regions.size() == 0) {
-    return std::nullopt;
+void PreFreezeBackgroundMemoryTrimmer::FinishSelfCompaction(
+    scoped_refptr<CompactionMetric> metric,
+    base::TimeTicks triggered_at) {
+  TRACE_EVENT0("base", "FinishSelfCompaction");
+  if (ShouldContinueSelfCompaction(triggered_at)) {
+    metric->RecordDelayedMetrics();
+    base::AutoLock locker(lock());
+    metric->RecordTimeMetrics(self_compaction_last_cancelled_);
   }
-
-  // TODO(crbug.com/344547190): This may run for a long time. Add a way to
-  // cancel this part-way through if we return to the foreground while this is
-  // running.
-  return CompactMemory(std::move(regions));
 }
 
 // static
-std::optional<int64_t> PreFreezeBackgroundMemoryTrimmer::CompactRegion(
+base::TimeDelta
+PreFreezeBackgroundMemoryTrimmer::GetDelayBetweenSelfCompaction() {
+  // We choose a random, small amount of time here, so that we are not trying
+  // to compact in every process at the same time.
+  return base::Milliseconds(base::RandInt(100, 300));
+}
+
+// static
+void PreFreezeBackgroundMemoryTrimmer::MaybeCancelSelfCompaction(
+    SelfCompactCancellationReason cancellation_reason) {
+  Instance().MaybeCancelSelfCompactionInternal(cancellation_reason);
+}
+
+void PreFreezeBackgroundMemoryTrimmer::MaybeCancelSelfCompactionInternal(
+    SelfCompactCancellationReason cancellation_reason) {
+  base::AutoLock locker(lock());
+  process_compacted_metadata_.reset();
+  // Check for the last time cancelled here in order to avoid recording this
+  // metric multiple times.
+  if (self_compaction_last_cancelled_ < self_compaction_last_triggered_) {
+    UmaHistogramEnumeration("Memory.SelfCompact2.Renderer.CancellationReason",
+                            cancellation_reason);
+  }
+  self_compaction_last_cancelled_ = base::TimeTicks::Now();
+}
+
+// static
+void PreFreezeBackgroundMemoryTrimmer::CompactSelf(
+    scoped_refptr<base::SequencedTaskRunner> task_runner,
+    base::TimeTicks triggered_at) {
+  // MADV_PAGEOUT was only added in Linux 5.4, so do nothing in earlier
+  // versions.
+  if (!SelfCompactionIsSupported()) {
+    return;
+  }
+
+  if (!ShouldContinueSelfCompaction(triggered_at)) {
+    return;
+  }
+
+  TRACE_EVENT0("base", "CompactSelf");
+  std::vector<debug::MappedMemoryRegion> regions;
+  auto did_read_proc_maps = ReadProcMaps::kSuccess;
+
+  // We still start the task in the control group, in order to record metrics.
+  if (base::FeatureList::IsEnabled(kShouldFreezeSelf)) {
+    std::string proc_maps;
+    if (!debug::ReadProcMaps(&proc_maps) ||
+        !ParseProcMaps(proc_maps, &regions)) {
+      did_read_proc_maps = ReadProcMaps::kFailed;
+    } else if (regions.size() == 0) {
+      did_read_proc_maps = ReadProcMaps::kEmpty;
+    }
+  }
+
+  UmaHistogramEnumeration("Memory.SelfCompact2.Renderer.ReadProcMaps",
+                          did_read_proc_maps);
+
+  Instance().StartSelfCompaction(std::move(task_runner), std::move(regions),
+                                 MiBToBytes(kShouldFreezeSelfMaxSize.Get()),
+                                 triggered_at);
+}
+
+// static
+std::optional<uint64_t> PreFreezeBackgroundMemoryTrimmer::CompactRegion(
     debug::MappedMemoryRegion region) {
 #if defined(MADV_PAGEOUT)
   // Skip file-backed regions
@@ -419,17 +665,23 @@
 }
 
 // static
-std::optional<int64_t> PreFreezeBackgroundMemoryTrimmer::CompactMemory(
-    std::vector<debug::MappedMemoryRegion> regions) {
-  TRACE_EVENT1("base", __PRETTY_FUNCTION__, "count", regions.size());
-  int64_t total_bytes_processed = 0;
-  for (const auto& region : regions) {
+std::optional<uint64_t> PreFreezeBackgroundMemoryTrimmer::CompactMemory(
+    std::vector<debug::MappedMemoryRegion>* regions,
+    const uint64_t max_bytes) {
+  TRACE_EVENT1("base", __PRETTY_FUNCTION__, "count", regions->size());
+  DCHECK(!regions->empty());
+
+  uint64_t total_bytes_processed = 0;
+  do {
+    const auto region = regions->back();
+    regions->pop_back();
     const auto bytes_processed = CompactRegion(region);
     if (!bytes_processed) {
       return std::nullopt;
     }
     total_bytes_processed += bytes_processed.value();
-  }
+  } while (!regions->empty() && total_bytes_processed < max_bytes);
+
   return total_bytes_processed;
 }
 
@@ -442,22 +694,38 @@
 
 // static
 void PreFreezeBackgroundMemoryTrimmer::OnSelfFreeze() {
-  // TODO
+  TRACE_EVENT0("base", "OnSelfFreeze");
+
+  auto task_runner = base::ThreadPool::CreateSequencedTaskRunner(
+      {base::TaskPriority::BEST_EFFORT, MayBlock()});
+  Instance().OnSelfFreezeInternal(std::move(task_runner));
+}
+
+void PreFreezeBackgroundMemoryTrimmer::OnSelfFreezeInternal(
+    scoped_refptr<SequencedTaskRunner> task_runner) {
+  const auto triggered_at = base::TimeTicks::Now();
+  base::AutoLock locker(lock());
+  self_compaction_last_triggered_ = triggered_at;
+  if (base::FeatureList::IsEnabled(kShouldFreezeSelf)) {
+    RunPreFreezeTasks();
+  }
+  task_runner->PostDelayedTask(
+      FROM_HERE,
+      base::BindOnce(&PreFreezeBackgroundMemoryTrimmer::CompactSelf,
+                     base::Unretained(this), task_runner, triggered_at),
+      base::Seconds(kShouldFreezeSelfDelayAfterPreFreezeTasks.Get()));
 }
 
 // static
 void PreFreezeBackgroundMemoryTrimmer::OnPreFreeze() {
+  // If we have scheduled a self compaction task, cancel it, since App Freezer
+  // will handle the compaction for us, and we don't want to potentially run
+  // self compaction after we have resumed.
+  MaybeCancelSelfCompaction(SelfCompactCancellationReason::kAppFreezer);
   Instance().OnPreFreezeInternal();
 }
 
-void PreFreezeBackgroundMemoryTrimmer::OnPreFreezeInternal() {
-  base::AutoLock locker(lock_);
-  PostMetricsTasksIfModern();
-
-  if (!ShouldUseModernTrim()) {
-    return;
-  }
-
+void PreFreezeBackgroundMemoryTrimmer::RunPreFreezeTasks() {
   // We check |num_pending_tasks-- > 0| so that we have an upper limit on the
   // number of tasks that we run.
   // We check |!background_tasks_.empty()| so that we exit as soon as we have
@@ -478,11 +746,22 @@
     // (1) To avoid holding it too long while running all the background tasks.
     // (2) To prevent a deadlock if the |background_task| needs to acquire the
     //     lock (e.g. to post another task).
-    base::AutoUnlock unlocker(lock_);
+    base::AutoUnlock unlocker(lock());
     BackgroundTask::RunNow(std::move(background_task));
   }
 }
 
+void PreFreezeBackgroundMemoryTrimmer::OnPreFreezeInternal() {
+  base::AutoLock locker(lock());
+  PostMetricsTasksIfModern();
+
+  if (!ShouldUseModernTrim()) {
+    return;
+  }
+
+  RunPreFreezeTasks();
+}
+
 // static
 void PreFreezeBackgroundMemoryTrimmer::UnregisterBackgroundTask(
     BackgroundTask* task) {
@@ -491,13 +770,13 @@
 
 void PreFreezeBackgroundMemoryTrimmer::UnregisterBackgroundTaskInternal(
     BackgroundTask* timer) {
-  base::AutoLock locker(lock_);
+  base::AutoLock locker(lock());
   std::erase_if(background_tasks_, [&](auto& t) { return t.get() == timer; });
 }
 
 // static
 void PreFreezeBackgroundMemoryTrimmer::RegisterPrivateMemoryFootprintMetric() {
-  base::AutoLock locker(Instance().lock_);
+  base::AutoLock locker(lock());
   static base::NoDestructor<PrivateMemoryFootprintMetric> pmf_metric;
   if (!PrivateMemoryFootprintMetric::did_register_) {
     PrivateMemoryFootprintMetric::did_register_ = true;
@@ -512,14 +791,12 @@
 
 // static
 bool PreFreezeBackgroundMemoryTrimmer::ShouldUseModernTrim() {
-  return SupportsModernTrim() &&
-         base::FeatureList::IsEnabled(kOnPreFreezeMemoryTrim);
+  return SupportsModernTrim();
 }
 
 // static
 bool PreFreezeBackgroundMemoryTrimmer::IsTrimMemoryBackgroundCritical() {
-  return SupportsModernTrim() &&
-         base::FeatureList::IsEnabled(kIsTrimMemoryBackgroundCritical);
+  return SupportsModernTrim();
 }
 
 // static
@@ -530,36 +807,43 @@
 
 // static
 void PreFreezeBackgroundMemoryTrimmer::ClearMetricsForTesting() {
-  base::AutoLock locker(Instance().lock_);
+  base::AutoLock locker(lock());
   Instance().metrics_.clear();
   PrivateMemoryFootprintMetric::did_register_ = false;
 }
 
 bool PreFreezeBackgroundMemoryTrimmer::DidRegisterTasksForTesting() const {
-  base::AutoLock locker(lock_);
+  base::AutoLock locker(lock());
   return metrics_.size() != 0;
 }
 
 size_t
 PreFreezeBackgroundMemoryTrimmer::GetNumberOfPendingBackgroundTasksForTesting()
     const {
-  base::AutoLock locker(lock_);
+  base::AutoLock locker(lock());
   return background_tasks_.size();
 }
 
 size_t PreFreezeBackgroundMemoryTrimmer::GetNumberOfKnownMetricsForTesting()
     const {
-  base::AutoLock locker(lock_);
+  base::AutoLock locker(lock());
   return metrics_.size();
 }
 
 size_t PreFreezeBackgroundMemoryTrimmer::GetNumberOfValuesBeforeForTesting()
     const {
-  base::AutoLock locker(lock_);
+  base::AutoLock locker(lock());
   return values_before_.size();
 }
 
 // static
+void PreFreezeBackgroundMemoryTrimmer::
+    ResetSelfCompactionLastCancelledForTesting() {
+  base::AutoLock locker(lock());
+  Instance().self_compaction_last_cancelled_ = base::TimeTicks::Min();
+}
+
+// static
 void PreFreezeBackgroundMemoryTrimmer::BackgroundTask::RunNow(
     std::unique_ptr<PreFreezeBackgroundMemoryTrimmer::BackgroundTask>
         background_task) {
@@ -635,4 +919,33 @@
 
 PreFreezeBackgroundMemoryTrimmer::PreFreezeMetric::~PreFreezeMetric() = default;
 
+PreFreezeBackgroundMemoryTrimmer::CompactionMetric::CompactionMetric(
+    base::TimeTicks triggered_at,
+    base::TimeTicks started_at)
+    : self_compaction_triggered_at_(triggered_at),
+      self_compaction_started_at_(started_at) {}
+PreFreezeBackgroundMemoryTrimmer::CompactionMetric::~CompactionMetric() =
+    default;
+
+void PreFreezeBackgroundMemoryTrimmer::CompactionMetric::RecordBeforeMetrics() {
+  RecordSmapsRollup(&smaps_before_);
+}
+
+void PreFreezeBackgroundMemoryTrimmer::CompactionMetric::
+    RecordDelayedMetrics() {
+  RecordSmapsRollup(&smaps_after_);
+  RecordSmapsRollupWithDelay(&smaps_after_1s_, base::Seconds(1));
+  RecordSmapsRollupWithDelay(&smaps_after_10s_, base::Seconds(10));
+  RecordSmapsRollupWithDelay(&smaps_after_60s_, base::Seconds(60));
+}
+
+void PreFreezeBackgroundMemoryTrimmer::CompactionMetric::RecordTimeMetrics(
+    base::TimeTicks self_compaction_last_cancelled) {
+  const auto now = base::TimeTicks::Now();
+  UmaHistogramMediumTimes("Memory.SelfCompact2.Renderer.SelfCompactionTime",
+                          now - self_compaction_started_at_);
+  UmaHistogramMediumTimes("Memory.SelfCompact2.Renderer.TimeSinceLastCancel",
+                          now - self_compaction_last_cancelled);
+}
+
 }  // namespace base::android
diff --git a/tot/base/android/pre_freeze_background_memory_trimmer.h b/tot/base/android/pre_freeze_background_memory_trimmer.h
index 832ee35..a7c6cd8 100644
--- a/tot/base/android/pre_freeze_background_memory_trimmer.h
+++ b/tot/base/android/pre_freeze_background_memory_trimmer.h
@@ -13,6 +13,7 @@
 #include "base/functional/callback.h"
 #include "base/memory/post_delayed_memory_reduction_task.h"
 #include "base/no_destructor.h"
+#include "base/profiler/sample_metadata.h"
 #include "base/task/delayed_task_handle.h"
 #include "base/task/sequenced_task_runner.h"
 #include "base/timer/timer.h"
@@ -20,7 +21,6 @@
 namespace base::android {
 class MemoryPurgeManagerAndroid;
 
-BASE_EXPORT BASE_DECLARE_FEATURE(kOnPreFreezeMemoryTrim);
 BASE_EXPORT BASE_DECLARE_FEATURE(kShouldFreezeSelf);
 
 // Starting from Android U, apps are frozen shortly after being backgrounded
@@ -35,6 +35,14 @@
 // be frozen.
 class BASE_EXPORT PreFreezeBackgroundMemoryTrimmer {
  public:
+  // These values are persisted to logs. Entries should not be renumbered and
+  // numeric values should never be reused.
+  enum class SelfCompactCancellationReason {
+    kAppFreezer,
+    kPageResumed,
+    kMaxValue = kPageResumed
+  };
+
   static PreFreezeBackgroundMemoryTrimmer& Instance();
   ~PreFreezeBackgroundMemoryTrimmer() = delete;
 
@@ -45,7 +53,7 @@
       scoped_refptr<base::SequencedTaskRunner> task_runner,
       const base::Location& from_here,
       OnceCallback<void(void)> task,
-      base::TimeDelta delay) LOCKS_EXCLUDED(lock_) {
+      base::TimeDelta delay) LOCKS_EXCLUDED(lock()) {
     PostDelayedBackgroundTask(
         task_runner, from_here,
         BindOnce(
@@ -60,7 +68,7 @@
       scoped_refptr<base::SequencedTaskRunner> task_runner,
       const base::Location& from_here,
       OnceCallback<void(MemoryReductionTaskContext)> task,
-      base::TimeDelta delay) LOCKS_EXCLUDED(lock_);
+      base::TimeDelta delay) LOCKS_EXCLUDED(lock());
 
   class PreFreezeMetric {
    public:
@@ -102,34 +110,47 @@
   // See "Memory.PreFreeze2.{process_type}.{name}.{suffix}" for details on the
   // exact metrics.
   static void RegisterMemoryMetric(const PreFreezeMetric* metric)
-      LOCKS_EXCLUDED(Instance().lock_);
+      LOCKS_EXCLUDED(lock());
 
   static void UnregisterMemoryMetric(const PreFreezeMetric* metric)
-      LOCKS_EXCLUDED(Instance().lock_);
+      LOCKS_EXCLUDED(lock());
+
+  // The callback runs in the thread pool. The caller cannot make any thread
+  // safety assumptions for the callback execution (e.g. it could run
+  // concurrently with the thread that registered it).
+  static void SetOnStartSelfCompactionCallback(base::RepeatingClosure callback)
+      LOCKS_EXCLUDED(lock());
 
   static bool SelfCompactionIsSupported();
 
-  // Compacts the memory for the process, and returns the number of bytes
-  // processed on success.
-  static std::optional<int64_t> CompactSelf();
+  // Compacts the memory for the process.
+  void CompactSelf(scoped_refptr<SequencedTaskRunner> task_runner,
+                   base::TimeTicks triggered_at);
+
+  // If we are currently running self compaction, cancel it. If it was running,
+  // record a metric with the reason for the cancellation.
+  static void MaybeCancelSelfCompaction(
+      SelfCompactCancellationReason cancellation_reason);
 
   static void SetSupportsModernTrimForTesting(bool is_supported);
-  static void ClearMetricsForTesting() LOCKS_EXCLUDED(lock_);
+  static void ClearMetricsForTesting() LOCKS_EXCLUDED(lock());
   size_t GetNumberOfPendingBackgroundTasksForTesting() const
-      LOCKS_EXCLUDED(lock_);
-  size_t GetNumberOfKnownMetricsForTesting() const LOCKS_EXCLUDED(lock_);
-  size_t GetNumberOfValuesBeforeForTesting() const LOCKS_EXCLUDED(lock_);
+      LOCKS_EXCLUDED(lock());
+  size_t GetNumberOfKnownMetricsForTesting() const LOCKS_EXCLUDED(lock());
+  size_t GetNumberOfValuesBeforeForTesting() const LOCKS_EXCLUDED(lock());
   bool DidRegisterTasksForTesting() const;
 
-  static void OnPreFreezeForTesting() LOCKS_EXCLUDED(lock_) { OnPreFreeze(); }
+  static void OnPreFreezeForTesting() LOCKS_EXCLUDED(lock()) { OnPreFreeze(); }
+  static void ResetSelfCompactionLastCancelledForTesting();
 
-  static std::optional<int64_t> CompactRegion(debug::MappedMemoryRegion region);
+  static std::optional<uint64_t> CompactRegion(
+      debug::MappedMemoryRegion region);
 
   // Called when Chrome is about to be frozen. Runs as many delayed tasks as
   // possible immediately, before we are frozen.
-  static void OnPreFreeze() LOCKS_EXCLUDED(lock_);
+  static void OnPreFreeze() LOCKS_EXCLUDED(lock());
 
-  static void OnSelfFreeze() LOCKS_EXCLUDED(lock_);
+  static void OnSelfFreeze() LOCKS_EXCLUDED(lock());
 
   static bool SupportsModernTrim();
   static bool ShouldUseModernTrim();
@@ -143,6 +164,9 @@
   friend class base::OneShotDelayedBackgroundTimer;
   friend class PreFreezeBackgroundMemoryTrimmerTest;
   friend class PreFreezeSelfCompactionTest;
+  FRIEND_TEST_ALL_PREFIXES(PreFreezeSelfCompactionTest, Cancel);
+  FRIEND_TEST_ALL_PREFIXES(PreFreezeSelfCompactionTest, NotCanceled);
+  FRIEND_TEST_ALL_PREFIXES(PreFreezeSelfCompactionTest, OnSelfFreezeCancel);
 
   // We use our own implementation here, based on |PostCancelableDelayedTask|,
   // rather than relying on something like |base::OneShotTimer|, since
@@ -181,54 +205,140 @@
     OnceCallback<void(MemoryReductionTaskContext)> task_;
   };
 
+ private:
+  class CompactionMetric : public RefCountedThreadSafe<CompactionMetric> {
+   public:
+    CompactionMetric(base::TimeTicks triggered_at, base::TimeTicks started_at);
+
+    void RecordDelayedMetrics();
+    void RecordTimeMetrics(base::TimeTicks self_compaction_last_cancelled);
+
+    void RecordBeforeMetrics();
+    void MaybeRecordCompactionMetrics() LOCKS_EXCLUDED(lock());
+
+   private:
+    friend class RefCountedThreadSafe<CompactionMetric>;
+    ~CompactionMetric();
+    void RecordSmapsRollup(std::optional<debug::SmapsRollup>* target)
+        LOCKS_EXCLUDED(lock());
+    void RecordSmapsRollupWithDelay(std::optional<debug::SmapsRollup>* target,
+                                    base::TimeDelta delay);
+    // When the self compaction was first triggered. There is a delay between
+    // this time and when we actually begin the compaction.
+    base::TimeTicks self_compaction_triggered_at_;
+    // When the self compaction first started. This should generally be
+    // |self_compaction_triggered_at_ +
+    // kShouldFreezeSelfDelayAfterPreFreezeTasks.Get()|, but may be longer if
+    // the task was delayed.
+    base::TimeTicks self_compaction_started_at_;
+    // We use std::optional here because:
+    // - We record these incrementally.
+    // - We may stop recording at some point.
+    // - We only want to emit histograms if all values were recorded.
+    std::optional<debug::SmapsRollup> smaps_before_;
+    std::optional<debug::SmapsRollup> smaps_after_;
+    std::optional<debug::SmapsRollup> smaps_after_1s_;
+    std::optional<debug::SmapsRollup> smaps_after_10s_;
+    std::optional<debug::SmapsRollup> smaps_after_60s_;
+  };
+
   PreFreezeBackgroundMemoryTrimmer();
 
-  static std::optional<int64_t> CompactMemory(
-      std::vector<debug::MappedMemoryRegion> regions);
+  static base::Lock& lock() { return Instance().lock_; }
+
+  void StartSelfCompaction(scoped_refptr<base::SequencedTaskRunner> task_runner,
+                           std::vector<debug::MappedMemoryRegion> regions,
+                           uint64_t max_size,
+                           base::TimeTicks triggered_at) LOCKS_EXCLUDED(lock());
+  static base::TimeDelta GetDelayBetweenSelfCompaction();
+  void MaybePostSelfCompactionTask(
+      scoped_refptr<base::SequencedTaskRunner> task_runner,
+      std::vector<debug::MappedMemoryRegion> regions,
+      scoped_refptr<CompactionMetric> metric,
+      uint64_t max_size,
+      base::TimeTicks triggered_at) LOCKS_EXCLUDED(lock());
+  void SelfCompactionTask(scoped_refptr<base::SequencedTaskRunner> task_runner,
+                          std::vector<debug::MappedMemoryRegion> regions,
+                          scoped_refptr<CompactionMetric> metric,
+                          uint64_t max_size,
+                          base::TimeTicks triggered_at) LOCKS_EXCLUDED(lock());
+  void FinishSelfCompaction(scoped_refptr<CompactionMetric> metric,
+                            base::TimeTicks triggered_at)
+      LOCKS_EXCLUDED(lock());
+
+  static bool ShouldContinueSelfCompaction(
+      base::TimeTicks self_compaction_triggered_at) LOCKS_EXCLUDED(lock());
+
+  static std::optional<uint64_t> CompactMemory(
+      std::vector<debug::MappedMemoryRegion>* regions,
+      const uint64_t max_bytes);
 
   void RegisterMemoryMetricInternal(const PreFreezeMetric* metric)
-      EXCLUSIVE_LOCKS_REQUIRED(lock_);
+      EXCLUSIVE_LOCKS_REQUIRED(lock());
 
   void UnregisterMemoryMetricInternal(const PreFreezeMetric* metric)
-      EXCLUSIVE_LOCKS_REQUIRED(lock_);
-  static void UnregisterBackgroundTask(BackgroundTask*) LOCKS_EXCLUDED(lock_);
+      EXCLUSIVE_LOCKS_REQUIRED(lock());
+  static void UnregisterBackgroundTask(BackgroundTask*) LOCKS_EXCLUDED(lock());
 
-  void UnregisterBackgroundTaskInternal(BackgroundTask*) LOCKS_EXCLUDED(lock_);
+  void UnregisterBackgroundTaskInternal(BackgroundTask*) LOCKS_EXCLUDED(lock());
 
-  static void RegisterPrivateMemoryFootprintMetric() LOCKS_EXCLUDED(lock_);
-  void RegisterPrivateMemoryFootprintMetricInternal() LOCKS_EXCLUDED(lock_);
+  static void RegisterPrivateMemoryFootprintMetric() LOCKS_EXCLUDED(lock());
+  void RegisterPrivateMemoryFootprintMetricInternal() LOCKS_EXCLUDED(lock());
 
   void PostDelayedBackgroundTaskInternal(
       scoped_refptr<base::SequencedTaskRunner> task_runner,
       const base::Location& from_here,
       OnceCallback<void(MemoryReductionTaskContext)> task,
-      base::TimeDelta delay) LOCKS_EXCLUDED(lock_);
+      base::TimeDelta delay) LOCKS_EXCLUDED(lock());
   void PostDelayedBackgroundTaskModern(
       scoped_refptr<base::SequencedTaskRunner> task_runner,
       const base::Location& from_here,
       OnceCallback<void(MemoryReductionTaskContext)> task,
-      base::TimeDelta delay) LOCKS_EXCLUDED(lock_);
+      base::TimeDelta delay) LOCKS_EXCLUDED(lock());
   BackgroundTask* PostDelayedBackgroundTaskModernHelper(
       scoped_refptr<base::SequencedTaskRunner> task_runner,
       const base::Location& from_here,
       OnceCallback<void(MemoryReductionTaskContext)> task,
-      base::TimeDelta delay) EXCLUSIVE_LOCKS_REQUIRED(lock_);
+      base::TimeDelta delay) EXCLUSIVE_LOCKS_REQUIRED(lock());
 
-  void OnPreFreezeInternal() LOCKS_EXCLUDED(lock_);
+  void OnPreFreezeInternal() LOCKS_EXCLUDED(lock());
+  void RunPreFreezeTasks() EXCLUSIVE_LOCKS_REQUIRED(lock());
 
-  void PostMetricsTasksIfModern() EXCLUSIVE_LOCKS_REQUIRED(lock_);
-  void PostMetricsTask() EXCLUSIVE_LOCKS_REQUIRED(lock_);
-  void RecordMetrics() LOCKS_EXCLUDED(lock_);
+  void OnSelfFreezeInternal(scoped_refptr<SequencedTaskRunner> task_runner);
+
+  void MaybeCancelSelfCompactionInternal(
+      SelfCompactCancellationReason cancellation_reason) LOCKS_EXCLUDED(lock());
+
+  void PostMetricsTasksIfModern() EXCLUSIVE_LOCKS_REQUIRED(lock());
+  void PostMetricsTask() EXCLUSIVE_LOCKS_REQUIRED(lock());
+  void RecordMetrics() LOCKS_EXCLUDED(lock());
 
   mutable base::Lock lock_;
   std::deque<std::unique_ptr<BackgroundTask>> background_tasks_
-      GUARDED_BY(lock_);
-  std::vector<const PreFreezeMetric*> metrics_ GUARDED_BY(lock_);
+      GUARDED_BY(lock());
+  std::vector<const PreFreezeMetric*> metrics_ GUARDED_BY(lock());
   // When a metrics task is posted (see |RecordMetrics|), the values of each
   // metric before any tasks are run are saved here. The "i"th entry corresponds
   // to the "i"th entry in |metrics_|. When there is no pending metrics task,
   // |values_before_| should be empty.
-  std::vector<std::optional<uint64_t>> values_before_ GUARDED_BY(lock_);
+  std::vector<std::optional<uint64_t>> values_before_ GUARDED_BY(lock());
+  // Whether or not we should continue self compaction. There are two reasons
+  // why we would cancel:
+  // (1) We have resumed, meaning we are likely to touch much of the process
+  //     memory soon, and we do not want to waste CPU time with compaction,
+  //     since it can block other work that needs to be done.
+  // (2) We are going to be frozen by App Freezer, which will do the compaction
+  //     work for us. This situation should be relatively rare, because we
+  //     attempt to not do self compaction if we know that we are going to
+  //     frozen by App Freezer.
+  base::TimeTicks self_compaction_last_cancelled_ GUARDED_BY(lock()) =
+      base::TimeTicks::Min();
+  // When we last triggered self compaction. Used to record metrics.
+  base::TimeTicks self_compaction_last_triggered_ GUARDED_BY(lock()) =
+      base::TimeTicks::Min();
+  std::optional<base::ScopedSampleMetadata> process_compacted_metadata_
+      GUARDED_BY(lock());
+  base::RepeatingClosure on_self_compact_callback_ GUARDED_BY(lock());
   bool supports_modern_trim_;
 };
 
diff --git a/tot/base/android/pre_freeze_background_memory_trimmer_unittest.cc b/tot/base/android/pre_freeze_background_memory_trimmer_unittest.cc
index 647da60..ae92bfe 100644
--- a/tot/base/android/pre_freeze_background_memory_trimmer_unittest.cc
+++ b/tot/base/android/pre_freeze_background_memory_trimmer_unittest.cc
@@ -14,6 +14,7 @@
 #include "base/files/scoped_temp_file.h"
 #include "base/memory/page_size.h"
 #include "base/task/thread_pool.h"
+#include "base/test/metrics/histogram_tester.h"
 #include "base/test/scoped_feature_list.h"
 #include "base/test/task_environment.h"
 #include "testing/gtest/include/gtest/gtest.h"
@@ -97,9 +98,6 @@
 
 class PreFreezeBackgroundMemoryTrimmerTest : public testing::Test {
  public:
-  PreFreezeBackgroundMemoryTrimmerTest() {
-    fl_.InitAndEnableFeature(kOnPreFreezeMemoryTrim);
-  }
   void SetUp() override {
     PreFreezeBackgroundMemoryTrimmer::SetSupportsModernTrimForTesting(true);
     PreFreezeBackgroundMemoryTrimmer::ClearMetricsForTesting();
@@ -129,8 +127,59 @@
 
   test::TaskEnvironment task_environment_{
       base::test::TaskEnvironment::TimeSource::MOCK_TIME};
+};
+
+class PreFreezeSelfCompactionTest : public testing::Test {
+ public:
+  void SetUp() override {
+    PreFreezeBackgroundMemoryTrimmer::
+        ResetSelfCompactionLastCancelledForTesting();
+  }
+
+  bool ShouldContinueSelfCompaction(base::TimeTicks compaction_started_at) {
+    return PreFreezeBackgroundMemoryTrimmer::Instance()
+        .ShouldContinueSelfCompaction(compaction_started_at);
+  }
+
+  // |size| is in bytes.
+  void* Map(size_t size) {
+    DCHECK_EQ(size % base::GetPageSize(), 0u);
+    void* addr = mmap(nullptr, size, PROT_WRITE | PROT_READ,
+                      MAP_PRIVATE | MAP_ANON, -1, 0);
+    debug::MappedMemoryRegion region;
+    region.permissions = debug::MappedMemoryRegion::WRITE |
+                         debug::MappedMemoryRegion::READ |
+                         debug::MappedMemoryRegion::PRIVATE;
+    region.inode = 0;
+    region.dev_major = 0;
+    region.dev_minor = 0;
+    region.start = reinterpret_cast<uintptr_t>(addr);
+    region.end = region.start + size;
+    mapped_regions_.push_back(region);
+    // We memset to guarantee that the memory we just allocated is resident.
+    memset(addr, 02, size);
+    return addr;
+  }
+
+  // |addr| must have been allocated using |Map|. |size| is in bytes.
+  void Unmap(void* addr, size_t size) {
+    munmap(addr, size);
+    std::erase_if(mapped_regions_,
+                  [&](const debug::MappedMemoryRegion& region) {
+                    return region.start == reinterpret_cast<uintptr_t>(addr);
+                  });
+  }
+
+  // Returns a copy of the regions that have been allocated via |Map|.
+  std::vector<debug::MappedMemoryRegion> GetMappedMemoryRegions() const {
+    return mapped_regions_;
+  }
+
+  test::TaskEnvironment task_environment_{
+      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
+
  private:
-  test::ScopedFeatureList fl_;
+  std::vector<debug::MappedMemoryRegion> mapped_regions_;
 };
 
 // We do not expect any tasks to be registered with
@@ -153,24 +202,6 @@
   EXPECT_EQ(s_counter, 1);
 }
 
-TEST_F(PreFreezeBackgroundMemoryTrimmerTest, PostTaskPreFreezeWithoutTrim) {
-  test::ScopedFeatureList fl;
-  fl.InitAndDisableFeature(kOnPreFreezeMemoryTrim);
-  ASSERT_FALSE(did_register_tasks());
-
-  PreFreezeBackgroundMemoryTrimmer::PostDelayedBackgroundTask(
-      SingleThreadTaskRunner::GetCurrentDefault(), FROM_HERE,
-      base::BindRepeating(&IncGlobalCounter), base::Seconds(30));
-
-  ASSERT_EQ(pending_task_count(), 0u);
-  ASSERT_TRUE(did_register_tasks());
-
-  task_environment_.FastForwardBy(base::Seconds(30));
-
-  ASSERT_EQ(pending_task_count(), 0u);
-  EXPECT_EQ(s_counter, 1);
-}
-
 // TODO(thiabaud): Test that the histograms are recorded too.
 TEST_F(PreFreezeBackgroundMemoryTrimmerTest, RegisterMetric) {
   ASSERT_EQ(measurements_count(), 0u);
@@ -648,7 +679,7 @@
   EXPECT_EQ(called_task_type.value(), MemoryReductionTaskContext::kProactive);
 }
 
-TEST(PreFreezeSelfCompactionTest, Simple) {
+TEST_F(PreFreezeSelfCompactionTest, Simple) {
   // MADV_PAGEOUT is only supported starting from Linux 5.4. So, on devices
   // don't support it, we bail out early. This is a known problem on some 32
   // bit devices.
@@ -682,7 +713,7 @@
   munmap(addr, size);
 }
 
-TEST(PreFreezeSelfCompactionTest, File) {
+TEST_F(PreFreezeSelfCompactionTest, File) {
   // MADV_PAGEOUT is only supported starting from Linux 5.4. So, on devices
   // don't support it, we bail out early. This is a known problem on some 32
   // bit devices.
@@ -724,7 +755,7 @@
   munmap(addr, size);
 }
 
-TEST(PreFreezeSelfCompactionTest, Locked) {
+TEST_F(PreFreezeSelfCompactionTest, Locked) {
   // MADV_PAGEOUT is only supported starting from Linux 5.4. So, on devices
   // don't support it, we bail out early. This is a known problem on some 32
   // bit devices.
@@ -763,4 +794,214 @@
   munmap(addr, size);
 }
 
+TEST_F(PreFreezeSelfCompactionTest, SimpleCancel) {
+  auto started_at = base::TimeTicks::Now();
+
+  EXPECT_TRUE(ShouldContinueSelfCompaction(started_at));
+
+  PreFreezeBackgroundMemoryTrimmer::MaybeCancelSelfCompaction(
+      PreFreezeBackgroundMemoryTrimmer::SelfCompactCancellationReason::
+          kPageResumed);
+
+  EXPECT_FALSE(ShouldContinueSelfCompaction(started_at));
+}
+
+TEST_F(PreFreezeSelfCompactionTest, Cancel) {
+  // MADV_PAGEOUT is only supported starting from Linux 5.4. So, on devices
+  // don't support it, we bail out early. This is a known problem on some 32
+  // bit devices.
+  if (!PreFreezeBackgroundMemoryTrimmer::SelfCompactionIsSupported()) {
+    GTEST_SKIP() << "No kernel support";
+  }
+
+  ASSERT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0u);
+
+  std::array<void*, 5> addrs;
+  for (size_t i = 1; i < 5; i++) {
+    addrs[i] = Map(i * base::GetPageSize());
+    ASSERT_NE(addrs[i], MAP_FAILED);
+  }
+
+  std::vector<debug::MappedMemoryRegion> regions = GetMappedMemoryRegions();
+  base::HistogramTester histograms;
+
+  ASSERT_EQ(regions.size(), 4u);
+
+  const auto started_at = base::TimeTicks::Now();
+  PreFreezeBackgroundMemoryTrimmer::Instance().StartSelfCompaction(
+      task_environment_.GetMainThreadTaskRunner(), std::move(regions), 1,
+      started_at);
+
+  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1u);
+
+  task_environment_.FastForwardBy(
+      task_environment_.NextMainThreadPendingTaskDelay());
+
+  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1u);
+
+  PreFreezeBackgroundMemoryTrimmer::MaybeCancelSelfCompaction(
+      PreFreezeBackgroundMemoryTrimmer::SelfCompactCancellationReason::
+          kPageResumed);
+
+  task_environment_.FastForwardBy(
+      task_environment_.NextMainThreadPendingTaskDelay());
+
+  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0u);
+
+  task_environment_.FastForwardBy(base::Seconds(60));
+
+  // No metrics should have been recorded, since we cancelled self compaction.
+  EXPECT_EQ(histograms.GetTotalCountsForPrefix("Memory.SelfCompact2").size(),
+            0);
+
+  for (size_t i = 1; i < 5; i++) {
+    Unmap(addrs[i], i * base::GetPageSize());
+  }
+}
+
+TEST_F(PreFreezeSelfCompactionTest, NotCanceled) {
+  // MADV_PAGEOUT is only supported starting from Linux 5.4. So, on devices
+  // don't support it, we bail out early. This is a known problem on some 32
+  // bit devices.
+  if (!PreFreezeBackgroundMemoryTrimmer::SelfCompactionIsSupported()) {
+    GTEST_SKIP() << "No kernel support";
+  }
+
+  base::HistogramTester histograms;
+
+  ASSERT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0u);
+
+  std::array<void*, 5> addrs;
+  for (size_t i = 1; i < 5; i++) {
+    addrs[i] = Map(i * base::GetPageSize());
+    ASSERT_NE(addrs[i], MAP_FAILED);
+  }
+
+  std::vector<debug::MappedMemoryRegion> regions = GetMappedMemoryRegions();
+
+  ASSERT_EQ(regions.size(), 4u);
+
+  const auto started_at = base::TimeTicks::Now();
+  PreFreezeBackgroundMemoryTrimmer::Instance().StartSelfCompaction(
+      task_environment_.GetMainThreadTaskRunner(), std::move(regions), 1,
+      started_at);
+
+  // We should have 4 sections here, based on the sizes mapped above.
+  // |StartSelfCompaction| doesn't run right away, but rather schedules a task.
+  // So, we expect to have 4 tasks to run here.
+  for (size_t i = 0; i < 4; i++) {
+    EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1u);
+    task_environment_.FastForwardBy(
+        task_environment_.NextMainThreadPendingTaskDelay());
+  }
+
+  // Fast forward to run the metrics tasks too.
+  task_environment_.FastForwardBy(base::Seconds(60));
+
+  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0u);
+
+  // We check here for the names of each metric we expect to be recorded. We
+  // can't easily check for the exact values of these metrics unfortunately,
+  // since they depend on reading /proc/self/smaps_rollup.
+  for (const auto& name : {"Rss", "Pss", "PssAnon", "PssFile", "SwapPss"}) {
+    for (const auto& timing :
+         {"Before", "After", "After1s", "After10s", "After60s"}) {
+      histograms.ExpectTotalCount(
+          StrCat({"Memory.SelfCompact2.Renderer.", name, ".", timing}), 1);
+    }
+    for (const auto& timing :
+         {"BeforeAfter", "After1s", "After10s", "After60s"}) {
+      const auto metric =
+          StrCat({"Memory.SelfCompact2.Renderer.", name, ".Diff.", timing});
+      base::HistogramTester::CountsMap diff_metrics;
+      diff_metrics[StrCat({metric, ".Increase"})] = 1;
+      diff_metrics[StrCat({metric, ".Decrease"})] = 1;
+      EXPECT_THAT(histograms.GetTotalCountsForPrefix(metric),
+                  testing::IsSubsetOf(diff_metrics));
+    }
+  }
+
+  // We also check that no other histograms (other than the ones expected above)
+  // were recorded.
+  EXPECT_EQ(histograms.GetTotalCountsForPrefix("Memory.SelfCompact2").size(),
+            47);
+
+  for (size_t i = 1; i < 5; i++) {
+    size_t len = i * base::GetPageSize();
+    EXPECT_EQ(CountResidentPagesInRange(addrs[i], len), 0);
+    Unmap(addrs[i], len);
+  }
+}
+
+// Test that we still record metrics even when the feature is disabled.
+TEST_F(PreFreezeSelfCompactionTest, Disabled) {
+  // Although we are not actually compacting anything, the self compaction
+  // code will exit out before metrics are recorded in the case where compaction
+  // is not supported.
+  if (!PreFreezeBackgroundMemoryTrimmer::SelfCompactionIsSupported()) {
+    GTEST_SKIP() << "No kernel support";
+  }
+
+  base::test::ScopedFeatureList feature_list_;
+  feature_list_.InitAndDisableFeature(kShouldFreezeSelf);
+
+  base::HistogramTester histograms;
+
+  PreFreezeBackgroundMemoryTrimmer::Instance().CompactSelf(
+      task_environment_.GetMainThreadTaskRunner(), base::TimeTicks::Now());
+
+  // Run metrics
+  task_environment_.FastForwardBy(base::Seconds(60));
+
+  // We check here for the names of each metric we expect to be recorded. We
+  // can't easily check for the exact values of these metrics unfortunately,
+  // since they depend on reading /proc/self/smaps_rollup.
+  for (const auto& name : {"Rss", "Pss", "PssAnon", "PssFile", "SwapPss"}) {
+    for (const auto& timing :
+         {"Before", "After", "After1s", "After10s", "After60s"}) {
+      histograms.ExpectTotalCount(
+          StrCat({"Memory.SelfCompact2.Renderer.", name, ".", timing}), 1);
+    }
+    for (const auto& timing :
+         {"BeforeAfter", "After1s", "After10s", "After60s"}) {
+      const auto metric =
+          StrCat({"Memory.SelfCompact2.Renderer.", name, ".Diff.", timing});
+      base::HistogramTester::CountsMap diff_metrics;
+      diff_metrics[StrCat({metric, ".Increase"})] = 1;
+      diff_metrics[StrCat({metric, ".Decrease"})] = 1;
+      EXPECT_THAT(histograms.GetTotalCountsForPrefix(metric),
+                  testing::IsSubsetOf(diff_metrics));
+    }
+  }
+
+  // We also check that no other histograms (other than the ones expected above)
+  // were recorded.
+  EXPECT_EQ(histograms.GetTotalCountsForPrefix("Memory.SelfCompact2").size(),
+            48);
+}
+
+TEST_F(PreFreezeSelfCompactionTest, OnSelfFreezeCancel) {
+  base::test::ScopedFeatureList feature_list_;
+  feature_list_.InitAndEnableFeature(kShouldFreezeSelf);
+
+  PreFreezeBackgroundMemoryTrimmer::Instance().OnSelfFreezeInternal(
+      task_environment_.GetMainThreadTaskRunner());
+  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1u);
+
+  // We advance here because |MaybeCancelSelfCompaction| relies on the current
+  // time to determine cancellation, which will not work correctly with mocked
+  // time otherwise.
+  task_environment_.FastForwardBy(base::Seconds(1));
+
+  PreFreezeBackgroundMemoryTrimmer::MaybeCancelSelfCompaction(
+      PreFreezeBackgroundMemoryTrimmer::SelfCompactCancellationReason::
+          kPageResumed);
+  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 1u);
+
+  task_environment_.FastForwardBy(
+      task_environment_.NextMainThreadPendingTaskDelay());
+
+  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0u);
+}
+
 }  // namespace base::android
diff --git a/tot/base/android/radio_utils.cc b/tot/base/android/radio_utils.cc
index e4b3513..8f1dee7 100644
--- a/tot/base/android/radio_utils.cc
+++ b/tot/base/android/radio_utils.cc
@@ -42,8 +42,9 @@
     // If GetConnectionType is being used in tests
     return g_overrider_for_tests->GetConnectionType();
   }
-  if (!IsSupported())
+  if (!IsSupported()) {
     return RadioConnectionType::kUnknown;
+  }
 
   JNIEnv* env = AttachCurrentThread();
   if (Java_RadioUtils_isWifiConnected(env)) {
@@ -54,8 +55,9 @@
 }
 
 std::optional<RadioSignalLevel> RadioUtils::GetCellSignalLevel() {
-  if (!IsSupported())
+  if (!IsSupported()) {
     return std::nullopt;
+  }
 
   JNIEnv* env = AttachCurrentThread();
   int signal_level = Java_RadioUtils_getCellSignalLevel(env);
@@ -67,8 +69,9 @@
 }
 
 std::optional<RadioDataActivity> RadioUtils::GetCellDataActivity() {
-  if (!IsSupported())
+  if (!IsSupported()) {
     return std::nullopt;
+  }
 
   JNIEnv* env = AttachCurrentThread();
   return static_cast<RadioDataActivity>(
diff --git a/tot/base/android/radio_utils_unittest.cc b/tot/base/android/radio_utils_unittest.cc
index e5dc3df..080c331 100644
--- a/tot/base/android/radio_utils_unittest.cc
+++ b/tot/base/android/radio_utils_unittest.cc
@@ -3,6 +3,7 @@
 // found in the LICENSE file.
 
 #include "base/android/radio_utils.h"
+
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace base {
@@ -23,4 +24,4 @@
 }
 
 }  // namespace android
-}  // namespace base
\ No newline at end of file
+}  // namespace base
diff --git a/tot/base/android/scoped_input_event.cc b/tot/base/android/scoped_input_event.cc
new file mode 100644
index 0000000..5ec8767
--- /dev/null
+++ b/tot/base/android/scoped_input_event.cc
@@ -0,0 +1,56 @@
+// Copyright 2024 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/android/scoped_input_event.h"
+
+#include "base/android/build_info.h"
+#include "base/check.h"
+#include "base/notreached.h"
+
+namespace base::android {
+
+// The class calls AInputEvent_release which was added only in Android S(31).
+#ifndef SCOPED_INPUT_EVENT_MIN_API
+#define SCOPED_INPUT_EVENT_MIN_API 31
+#endif
+
+ScopedInputEvent::ScopedInputEvent(const AInputEvent* event) {
+  CHECK(base::android::BuildInfo::GetInstance()->sdk_int() >=
+        SCOPED_INPUT_EVENT_MIN_API);
+  CHECK(event);
+  a_input_event_ = event;
+}
+
+ScopedInputEvent::~ScopedInputEvent() {
+  DestroyIfNeeded();
+}
+
+ScopedInputEvent::ScopedInputEvent(ScopedInputEvent&& other)
+    : a_input_event_(other.a_input_event_) {
+  other.a_input_event_ = nullptr;
+}
+
+ScopedInputEvent& ScopedInputEvent::operator=(ScopedInputEvent&& other) {
+  if (this != &other) {
+    DestroyIfNeeded();
+    a_input_event_ = other.a_input_event_;
+    other.a_input_event_ = nullptr;
+  }
+  return *this;
+}
+
+void ScopedInputEvent::DestroyIfNeeded() {
+  if (a_input_event_ == nullptr) {
+    return;
+  }
+  // If check to suppress the compiler warning.
+  if (__builtin_available(android SCOPED_INPUT_EVENT_MIN_API, *)) {
+    AInputEvent_release(a_input_event_);
+    a_input_event_ = nullptr;
+    return;
+  }
+  NOTREACHED();
+}
+
+}  // namespace base::android
diff --git a/tot/base/android/scoped_input_event.h b/tot/base/android/scoped_input_event.h
new file mode 100644
index 0000000..0efb4c0
--- /dev/null
+++ b/tot/base/android/scoped_input_event.h
@@ -0,0 +1,42 @@
+// Copyright 2024 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_ANDROID_SCOPED_INPUT_EVENT_H_
+#define BASE_ANDROID_SCOPED_INPUT_EVENT_H_
+
+#include <android/input.h>
+
+#include "base/base_export.h"
+#include "base/memory/raw_ptr.h"
+
+namespace base::android {
+
+// Class to manage lifecycle of AInputEvent.
+// The class should only be instantiated on Android S+, since
+// AInputEvent_release was added only in Android S(31).
+class BASE_EXPORT ScopedInputEvent {
+ public:
+  explicit ScopedInputEvent(const AInputEvent* event);
+  ~ScopedInputEvent();
+
+  ScopedInputEvent(ScopedInputEvent&& other);
+  ScopedInputEvent& operator=(ScopedInputEvent&& other);
+
+  // Move only type.
+  ScopedInputEvent(const ScopedInputEvent&) = delete;
+  ScopedInputEvent& operator=(const ScopedInputEvent&) = delete;
+
+  explicit operator bool() const { return !!a_input_event_; }
+
+  const AInputEvent* a_input_event() const { return a_input_event_.get(); }
+
+ private:
+  void DestroyIfNeeded();
+
+  raw_ptr<const AInputEvent> a_input_event_ = nullptr;
+};
+
+}  // namespace base::android
+
+#endif  // BASE_ANDROID_SCOPED_INPUT_EVENT_H_
diff --git a/tot/base/android/shared_preferences/shared_preferences_manager.cc b/tot/base/android/shared_preferences/shared_preferences_manager.cc
index 76c2a3b..7366cea 100644
--- a/tot/base/android/shared_preferences/shared_preferences_manager.cc
+++ b/tot/base/android/shared_preferences/shared_preferences_manager.cc
@@ -25,55 +25,41 @@
 
 void SharedPreferencesManager::RemoveKey(
     const std::string& shared_preference_key) {
-  ScopedJavaLocalRef<jstring> jkey =
-      ConvertUTF8ToJavaString(env_, shared_preference_key);
-  Java_SharedPreferencesManager_removeKey(env_, java_obj_, jkey);
+  Java_SharedPreferencesManager_removeKey(env_, java_obj_,
+                                          shared_preference_key);
 }
 
 bool SharedPreferencesManager::ContainsKey(
     const std::string& shared_preference_key) {
-  ScopedJavaLocalRef<jstring> jkey =
-      ConvertUTF8ToJavaString(env_, shared_preference_key);
-  return Java_SharedPreferencesManager_contains(env_, java_obj_, jkey);
+  return Java_SharedPreferencesManager_contains(env_, java_obj_,
+                                                shared_preference_key);
 }
 
 bool SharedPreferencesManager::ReadBoolean(
     const std::string& shared_preference_key,
     bool default_value) {
-  ScopedJavaLocalRef<jstring> jkey =
-      ConvertUTF8ToJavaString(env_, shared_preference_key);
-  return Java_SharedPreferencesManager_readBoolean(env_, java_obj_, jkey,
-                                                   default_value);
+  return Java_SharedPreferencesManager_readBoolean(
+      env_, java_obj_, shared_preference_key, default_value);
 }
 
 int SharedPreferencesManager::ReadInt(const std::string& shared_preference_key,
                                       int default_value) {
-  ScopedJavaLocalRef<jstring> jkey =
-      ConvertUTF8ToJavaString(env_, shared_preference_key);
-  return Java_SharedPreferencesManager_readInt(env_, java_obj_, jkey,
-                                               default_value);
+  return Java_SharedPreferencesManager_readInt(
+      env_, java_obj_, shared_preference_key, default_value);
 }
 
 std::string SharedPreferencesManager::ReadString(
     const std::string& shared_preference_key,
     const std::string& default_value) {
-  ScopedJavaLocalRef<jstring> jkey =
-      ConvertUTF8ToJavaString(env_, shared_preference_key);
-  ScopedJavaLocalRef<jstring> jdefault_value =
-      ConvertUTF8ToJavaString(env_, default_value);
-  ScopedJavaLocalRef<jstring> java_result =
-      Java_SharedPreferencesManager_readString(env_, java_obj_, jkey,
-                                               jdefault_value);
-  return ConvertJavaStringToUTF8(java_result);
+  return Java_SharedPreferencesManager_readString(
+      env_, java_obj_, shared_preference_key, default_value);
 }
 
 void SharedPreferencesManager::WriteString(
     const std::string& shared_preference_key,
     const std::string& value) {
-  ScopedJavaLocalRef<jstring> jkey =
-      ConvertUTF8ToJavaString(env_, shared_preference_key);
-  ScopedJavaLocalRef<jstring> jvalue = ConvertUTF8ToJavaString(env_, value);
-  Java_SharedPreferencesManager_writeString(env_, java_obj_, jkey, jvalue);
+  Java_SharedPreferencesManager_writeString(env_, java_obj_,
+                                            shared_preference_key, value);
 }
 
 }  // namespace base::android
diff --git a/tot/base/android/shared_preferences/shared_preferences_manager.h b/tot/base/android/shared_preferences/shared_preferences_manager.h
index 2c491cc..d4aad52 100644
--- a/tot/base/android/shared_preferences/shared_preferences_manager.h
+++ b/tot/base/android/shared_preferences/shared_preferences_manager.h
@@ -5,9 +5,8 @@
 #ifndef BASE_ANDROID_SHARED_PREFERENCES_SHARED_PREFERENCES_MANAGER_H_
 #define BASE_ANDROID_SHARED_PREFERENCES_SHARED_PREFERENCES_MANAGER_H_
 
-#include "base/base_export.h"
-
 #include "base/android/jni_android.h"
+#include "base/base_export.h"
 
 namespace base::android {
 
diff --git a/tot/base/android/sys_utils.cc b/tot/base/android/sys_utils.cc
index 4a3189d..ccf08bb 100644
--- a/tot/base/android/sys_utils.cc
+++ b/tot/base/android/sys_utils.cc
@@ -17,22 +17,11 @@
 namespace base {
 namespace android {
 
-bool SysUtils::IsLowEndDeviceFromJni() {
-  JNIEnv* env = AttachCurrentThread();
-  return Java_SysUtils_isLowEndDevice(env);
-}
-
 bool SysUtils::IsCurrentlyLowMemory() {
   JNIEnv* env = AttachCurrentThread();
   return Java_SysUtils_isCurrentlyLowMemory(env);
 }
 
-// static
-int SysUtils::AmountOfPhysicalMemoryKB() {
-  JNIEnv* env = AttachCurrentThread();
-  return Java_SysUtils_amountOfPhysicalMemoryKB(env);
-}
-
 // Logs the number of minor / major page faults to tracing (and also the time to
 // collect) the metrics. Does nothing if tracing is not enabled.
 static void JNI_SysUtils_LogPageFaultCountToTracing(JNIEnv* env) {
@@ -40,8 +29,9 @@
   // expensive (reading and parsing a file).
   bool enabled;
   TRACE_EVENT_CATEGORY_GROUP_ENABLED("startup", &enabled);
-  if (!enabled)
+  if (!enabled) {
     return;
+  }
   TRACE_EVENT_BEGIN2("memory", "CollectPageFaultCount", "minor", 0, "major", 0);
   std::unique_ptr<base::ProcessMetrics> process_metrics(
       base::ProcessMetrics::CreateProcessMetrics(
diff --git a/tot/base/android/sys_utils.h b/tot/base/android/sys_utils.h
index c4ddd21..4dee3a5 100644
--- a/tot/base/android/sys_utils.h
+++ b/tot/base/android/sys_utils.h
@@ -12,12 +12,8 @@
 
 class BASE_EXPORT SysUtils {
  public:
-  // Returns true iff this is a low-end device.
-  static bool IsLowEndDeviceFromJni();
   // Returns true if system has low available memory.
   static bool IsCurrentlyLowMemory();
-  // Returns amount of physical ram detected in KB, or 0 if detection failed.
-  static int AmountOfPhysicalMemoryKB();
 };
 
 }  // namespace android
diff --git a/tot/base/android/task_scheduler/task_runner_android.cc b/tot/base/android/task_scheduler/task_runner_android.cc
index 3df400d..0347d55 100644
--- a/tot/base/android/task_scheduler/task_runner_android.cc
+++ b/tot/base/android/task_scheduler/task_runner_android.cc
@@ -36,15 +36,8 @@
   return *callback;
 }
 
-void RunJavaTask(base::android::ScopedJavaGlobalRef<jobject> task,
-                 const std::string& runnable_class_name) {
-  TRACE_EVENT("toplevel", nullptr, [&](::perfetto::EventContext& ctx) {
-    std::string event_name =
-        base::StrCat({"JniPostTask: ", runnable_class_name});
-    ctx.event()->set_name(event_name.c_str());
-  });
-  JNIEnv* env = jni_zero::AttachCurrentThread();
-  JNI_Runnable::Java_Runnable_run(env, task);
+void RunJavaTask(jint task_index) {
+  Java_TaskRunnerImpl_runTask(jni_zero::AttachCurrentThread(), task_index);
 }
 
 }  // namespace
@@ -68,19 +61,13 @@
   delete this;
 }
 
-void TaskRunnerAndroid::PostDelayedTask(
-    JNIEnv* env,
-    const base::android::JavaRef<jobject>& task,
-    jlong delay,
-    std::string& runnable_class_name) {
+void TaskRunnerAndroid::PostDelayedTask(JNIEnv* env,
+                                        jlong delay,
+                                        jint task_index) {
   // This could be run on any java thread, so we can't cache |env| in the
   // BindOnce because JNIEnv is thread specific.
   task_runner_->PostDelayedTask(
-      FROM_HERE,
-      base::BindOnce(&RunJavaTask,
-                     base::android::ScopedJavaGlobalRef<jobject>(task),
-                     runnable_class_name),
-      Milliseconds(delay));
+      FROM_HERE, base::BindOnce(&RunJavaTask, task_index), Milliseconds(delay));
 }
 
 // static
diff --git a/tot/base/android/task_scheduler/task_runner_android.h b/tot/base/android/task_scheduler/task_runner_android.h
index 59c8351..e077cf3 100644
--- a/tot/base/android/task_scheduler/task_runner_android.h
+++ b/tot/base/android/task_scheduler/task_runner_android.h
@@ -32,10 +32,7 @@
 
   void Destroy(JNIEnv* env);
 
-  void PostDelayedTask(JNIEnv* env,
-                       const base::android::JavaRef<jobject>& task,
-                       jlong delay,
-                       std::string& runnable_class_name);
+  void PostDelayedTask(JNIEnv* env, jlong delay, jint taskIndex);
 
   bool BelongsToCurrentThread(JNIEnv* env);
 
diff --git a/tot/base/android/thread_instruction_count.cc b/tot/base/android/thread_instruction_count.cc
index b063430..0aaba17 100644
--- a/tot/base/android/thread_instruction_count.cc
+++ b/tot/base/android/thread_instruction_count.cc
@@ -4,16 +4,16 @@
 
 #include "base/android/thread_instruction_count.h"
 
+#include <linux/perf_event.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
 #include "base/check_op.h"
 #include "base/logging.h"
 #include "base/no_destructor.h"
 #include "base/numerics/safe_conversions.h"
 #include "base/threading/thread_local_storage.h"
 
-#include <linux/perf_event.h>
-#include <sys/syscall.h>
-#include <unistd.h>
-
 namespace base {
 namespace android {
 
@@ -24,8 +24,9 @@
 ThreadLocalStorage::Slot& InstructionCounterFdSlot() {
   static NoDestructor<ThreadLocalStorage::Slot> fd_slot([](void* fd_ptr) {
     int fd = checked_cast<int>(reinterpret_cast<intptr_t>(fd_ptr));
-    if (fd > 0)
+    if (fd > 0) {
       close(fd);
+    }
   });
   return *fd_slot;
 }
@@ -75,8 +76,9 @@
 ThreadInstructionCount ThreadInstructionCount::Now() {
   DCHECK(IsSupported());
   int fd = InstructionCounterFdForCurrentThread();
-  if (fd <= 0)
+  if (fd <= 0) {
     return ThreadInstructionCount();
+  }
 
   uint64_t instructions = 0;
   ssize_t bytes_read = read(fd, &instructions, sizeof(instructions));
diff --git a/tot/base/android/token_android.cc b/tot/base/android/token_android.cc
index d106204..eb86d72 100644
--- a/tot/base/android/token_android.cc
+++ b/tot/base/android/token_android.cc
@@ -4,15 +4,8 @@
 
 #include "base/android/token_android.h"
 
-#include "build/robolectric_buildflags.h"
-
-#if BUILDFLAG(IS_ROBOLECTRIC)
-#include "base/base_robolectric_jni/TokenBase_jni.h"  // nogncheck
-#include "base/base_robolectric_jni/Token_jni.h"      // nogncheck
-#else
-#include "base/base_jni/TokenBase_jni.h"
-#include "base/base_jni/Token_jni.h"
-#endif
+#include "base/base_minimal_jni/TokenBase_jni.h"
+#include "base/base_minimal_jni/Token_jni.h"
 
 namespace base::android {
 
@@ -36,3 +29,5 @@
 }
 
 }  // namespace base::android
+
+DEFINE_JNI_FOR_Token()
diff --git a/tot/base/android/trace_event_binding.cc b/tot/base/android/trace_event_binding.cc
index 6377036..7b34929 100644
--- a/tot/base/android/trace_event_binding.cc
+++ b/tot/base/android/trace_event_binding.cc
@@ -13,13 +13,6 @@
 #include "base/metrics/histogram_macros.h"
 #include "base/trace_event/base_tracing.h"
 #include "base/tracing_buildflags.h"
-#include "build/robolectric_buildflags.h"
-
-#if BUILDFLAG(IS_ROBOLECTRIC)
-#include "base/base_robolectric_jni/TraceEvent_jni.h"  // nogncheck
-#else
-#include "base/tasks_jni/TraceEvent_jni.h"
-#endif
 
 #if BUILDFLAG(ENABLE_BASE_TRACING)
 #include "base/trace_event/trace_event_impl.h"  // no-presubmit-check
@@ -27,6 +20,9 @@
 #include "third_party/perfetto/protos/perfetto/config/chrome/chrome_config.gen.h"  // nogncheck
 #endif  // BUILDFLAG(ENABLE_BASE_TRACING)
 
+// Must come after all headers that specialize FromJniType() / ToJniType().
+#include "base/tasks_minimal_jni/TraceEvent_jni.h"
+
 namespace base {
 namespace android {
 
@@ -90,7 +86,6 @@
   std::unordered_map<uint32_t, bool> event_name_filtering_per_session_;
 };
 
-
 }  // namespace
 
 static void JNI_TraceEvent_RegisterEnabledObserver(JNIEnv* env) {
@@ -311,21 +306,24 @@
 #endif  // BUILDFLAG(ENABLE_BASE_TRACING)
 }
 
-static void JNI_TraceEvent_WebViewStartupStage2(JNIEnv* env,
-                                                jlong start_time_ms,
-                                                jlong duration_ms,
-                                                jboolean is_cold_startup) {
+static void JNI_TraceEvent_WebViewStartupFirstInstance(
+    JNIEnv* env,
+    jlong start_time_ms,
+    jlong duration_ms,
+    jboolean included_global_startup) {
 #if BUILDFLAG(ENABLE_BASE_TRACING)
   auto t = perfetto::Track::ThreadScoped(
       reinterpret_cast<void*>(trace_event::GetNextGlobalTraceId()));
-  if (is_cold_startup) {
-    TRACE_EVENT_BEGIN("android_webview.timeline",
-                      "WebView.Startup.CreationTime.Stage2.ProviderInit.Cold",
-                      t, TimeTicks() + Milliseconds(start_time_ms));
+  if (included_global_startup) {
+    TRACE_EVENT_BEGIN(
+        "android_webview.timeline",
+        "WebView.Startup.CreationTime.FirstInstanceWithGlobalStartup", t,
+        TimeTicks() + Milliseconds(start_time_ms));
   } else {
-    TRACE_EVENT_BEGIN("android_webview.timeline",
-                      "WebView.Startup.CreationTime.Stage2.ProviderInit.Warm",
-                      t, TimeTicks() + Milliseconds(start_time_ms));
+    TRACE_EVENT_BEGIN(
+        "android_webview.timeline",
+        "WebView.Startup.CreationTime.FirstInstanceWithoutGlobalStartup", t,
+        TimeTicks() + Milliseconds(start_time_ms));
   }
 
   TRACE_EVENT_END("android_webview.timeline", t,
@@ -333,6 +331,20 @@
 #endif  // BUILDFLAG(ENABLE_BASE_TRACING)
 }
 
+static void JNI_TraceEvent_WebViewStartupNotFirstInstance(JNIEnv* env,
+                                                          jlong start_time_ms,
+                                                          jlong duration_ms) {
+#if BUILDFLAG(ENABLE_BASE_TRACING)
+  auto t = perfetto::Track::ThreadScoped(
+      reinterpret_cast<void*>(trace_event::GetNextGlobalTraceId()));
+  TRACE_EVENT_BEGIN("android_webview.timeline",
+                    "WebView.Startup.CreationTime.NotFirstInstance", t,
+                    TimeTicks() + Milliseconds(start_time_ms));
+  TRACE_EVENT_END("android_webview.timeline", t,
+                  TimeTicks() + Milliseconds(start_time_ms + duration_ms));
+#endif  // BUILDFLAG(ENABLE_BASE_TRACING)
+}
+
 static void JNI_TraceEvent_WebViewStartupStartChromiumLocked(
     JNIEnv* env,
     jlong start_time_ms,
@@ -549,8 +561,7 @@
       });
 }
 
-static void JNI_TraceEvent_FinishAsync(JNIEnv* env,
-                                       jlong jid) {
+static void JNI_TraceEvent_FinishAsync(JNIEnv* env, jlong jid) {
   TRACE_EVENT_END(internal::kJavaTraceCategory,
                   perfetto::Track(static_cast<uint64_t>(jid)));
 }
diff --git a/tot/base/android/unguessable_token_android.cc b/tot/base/android/unguessable_token_android.cc
index 9278a66..b76bd2a 100644
--- a/tot/base/android/unguessable_token_android.cc
+++ b/tot/base/android/unguessable_token_android.cc
@@ -4,17 +4,9 @@
 
 #include "base/android/unguessable_token_android.h"
 
-#include "build/robolectric_buildflags.h"
-
 // Must come after all headers that specialize FromJniType() / ToJniType().
-#if BUILDFLAG(IS_ROBOLECTRIC)
-#include "base/base_robolectric_jni/TokenBase_jni.h"  // nogncheck
-#include "base/base_robolectric_jni/UnguessableToken_jni.h"  // nogncheck
-#else
-#include "base/base_jni/TokenBase_jni.h"
-#include "base/base_jni/UnguessableToken_jni.h"
-#endif
-
+#include "base/base_minimal_jni/TokenBase_jni.h"
+#include "base/base_minimal_jni/UnguessableToken_jni.h"
 
 namespace base {
 namespace android {
@@ -51,3 +43,5 @@
 
 }  // namespace android
 }  // namespace base
+
+DEFINE_JNI_FOR_UnguessableToken()
diff --git a/tot/base/apple/dispatch_source.cc b/tot/base/apple/dispatch_source.cc
new file mode 100644
index 0000000..f542eaf
--- /dev/null
+++ b/tot/base/apple/dispatch_source.cc
@@ -0,0 +1,101 @@
+// Copyright 2014 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/apple/dispatch_source.h"
+
+#include "base/apple/scoped_dispatch_object.h"
+
+namespace base::apple {
+
+struct DispatchSource::Storage {
+  // The dispatch queue used to service the source_.
+  ScopedDispatchObject<dispatch_queue_t> queue;
+
+  // Dispatch source type, either DISPATCH_SOURCE_TYPE_MACH_RECV,
+  // DISPATCH_SOURCE_TYPE_READ or DISPATCH_SOURCE_TYPE_WRITE.
+  ScopedDispatchObject<dispatch_source_t> source;
+
+  // Semaphore used to wait on the |source_|'s cancellation in the destructor.
+  ScopedDispatchObject<dispatch_semaphore_t> source_canceled;
+};
+
+DispatchSource::DispatchSource(const char* name,
+                               mach_port_t port,
+                               void (^event_handler)())
+    : DispatchSource(dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL),
+                     port,
+                     event_handler) {
+  // Since the queue was created above in the delegated constructor, and it was
+  // subsequently retained, release it here.
+  dispatch_release(storage_->queue.get());
+}
+
+DispatchSource::DispatchSource(dispatch_queue_t queue,
+                               int fd,
+                               dispatch_source_type_t type,
+                               void (^event_handler)())
+    : storage_(std::make_unique<Storage>()) {
+  DCHECK(type == DISPATCH_SOURCE_TYPE_READ ||
+         type == DISPATCH_SOURCE_TYPE_WRITE);
+  storage_->queue.reset(queue, base::scoped_policy::RETAIN);
+  storage_->source.reset(dispatch_source_create(
+      type, static_cast<uintptr_t>(fd), 0, storage_->queue.get()));
+  storage_->source_canceled.reset(dispatch_semaphore_create(0));
+
+  dispatch_source_set_event_handler(storage_->source.get(), event_handler);
+  dispatch_source_set_cancel_handler(storage_->source.get(), ^{
+    dispatch_semaphore_signal(storage_->source_canceled.get());
+  });
+}
+
+DispatchSource::DispatchSource(dispatch_queue_t queue,
+                               mach_port_t port,
+                               void (^event_handler)())
+    : storage_(std::make_unique<Storage>()) {
+  storage_->queue.reset(queue, base::scoped_policy::RETAIN);
+  storage_->source.reset(dispatch_source_create(
+      DISPATCH_SOURCE_TYPE_MACH_RECV, port, 0, storage_->queue.get()));
+  storage_->source_canceled.reset(dispatch_semaphore_create(0));
+
+  dispatch_source_set_event_handler(storage_->source.get(), event_handler);
+  dispatch_source_set_cancel_handler(storage_->source.get(), ^{
+    dispatch_semaphore_signal(storage_->source_canceled.get());
+  });
+}
+
+DispatchSource::~DispatchSource() {
+  if (suspended_) {
+    Resume();
+  }
+  // Cancel the source and wait for the semaphore to be signaled. This will
+  // ensure the source managed by this class is not used after it is freed.
+  dispatch_source_cancel(storage_->source.get());
+  storage_->source.reset();
+
+  dispatch_semaphore_wait(storage_->source_canceled.get(),
+                          DISPATCH_TIME_FOREVER);
+}
+
+void DispatchSource::Resume() {
+  if (!suspended_) {
+    return;
+  }
+  suspended_ = false;
+  dispatch_resume(storage_->source.get());
+}
+
+void DispatchSource::Suspend() {
+  if (suspended_) {
+    return;
+  }
+
+  suspended_ = true;
+  dispatch_suspend(storage_->source.get());
+}
+
+dispatch_queue_t DispatchSource::Queue() const {
+  return storage_->queue.get();
+}
+
+}  // namespace base::apple
diff --git a/tot/base/apple/dispatch_source.h b/tot/base/apple/dispatch_source.h
new file mode 100644
index 0000000..0e7e28b
--- /dev/null
+++ b/tot/base/apple/dispatch_source.h
@@ -0,0 +1,63 @@
+// Copyright 2014 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_APPLE_DISPATCH_SOURCE_H_
+#define BASE_APPLE_DISPATCH_SOURCE_H_
+
+#include <dispatch/dispatch.h>
+
+#include <memory>
+
+#include "base/base_export.h"
+
+namespace base::apple {
+
+// This class encapsulates a dispatch source of type dispatch_source_type_t.
+// When this object is destroyed, the source will be cancelled and it will wait
+// for the source to stop executing work. The source can run on either a
+// user-supplied queue, or it can create its own for the source.
+class BASE_EXPORT DispatchSource {
+ public:
+  // Creates a new dispatch source for the |port| and schedules it on a new
+  // queue that will be created with |name|. When a Mach message is received,
+  // the |event_handler| will be called.
+  DispatchSource(const char* name, mach_port_t port, void (^event_handler)());
+
+  // Creates a new dispatch source with the same semantics as above, but rather
+  // than creating a new queue, it schedules the source on |queue|.
+  DispatchSource(dispatch_queue_t queue,
+                 mach_port_t port,
+                 void (^event_handler)());
+
+  // Create a dispatch source for a file descriptor.
+  // `type` should either be DISPATCH_SOURCE_TYPE_READ or
+  // DISPATCH_SOURCE_TYPE_WRITE.
+  DispatchSource(dispatch_queue_t queue,
+                 int fd,
+                 dispatch_source_type_t type,
+                 void (^event_handler)());
+
+  DispatchSource(const DispatchSource&) = delete;
+  DispatchSource& operator=(const DispatchSource&) = delete;
+
+  // Cancels the source and waits for it to become fully cancelled before
+  // releasing the source.
+  ~DispatchSource();
+
+  // Resumes the source. This must be called before any Mach messages will
+  // be received.
+  void Resume();
+  void Suspend();
+
+  dispatch_queue_t Queue() const;
+
+ private:
+  bool suspended_ = true;
+  struct Storage;
+  std::unique_ptr<Storage> storage_;
+};
+
+}  // namespace base::apple
+
+#endif  // BASE_APPLE_DISPATCH_SOURCE_H_
diff --git a/tot/base/apple/dispatch_source_mach.cc b/tot/base/apple/dispatch_source_mach.cc
deleted file mode 100644
index e155bee..0000000
--- a/tot/base/apple/dispatch_source_mach.cc
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright 2014 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/apple/dispatch_source_mach.h"
-
-#include "base/apple/scoped_dispatch_object.h"
-
-namespace base::apple {
-
-struct DispatchSourceMach::Storage {
-  // The dispatch queue used to service the source_.
-  ScopedDispatchObject<dispatch_queue_t> queue;
-
-  // A MACH_RECV dispatch source.
-  ScopedDispatchObject<dispatch_source_t> source;
-
-  // Semaphore used to wait on the |source_|'s cancellation in the destructor.
-  ScopedDispatchObject<dispatch_semaphore_t> source_canceled;
-};
-
-DispatchSourceMach::DispatchSourceMach(const char* name,
-                                       mach_port_t port,
-                                       void (^event_handler)())
-    : DispatchSourceMach(dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL),
-                         port,
-                         event_handler) {
-  // Since the queue was created above in the delegated constructor, and it was
-  // subsequently retained, release it here.
-  dispatch_release(storage_->queue.get());
-}
-
-DispatchSourceMach::DispatchSourceMach(dispatch_queue_t queue,
-                                       mach_port_t port,
-                                       void (^event_handler)())
-    : storage_(std::make_unique<Storage>()) {
-  storage_->queue.reset(queue, base::scoped_policy::RETAIN);
-  storage_->source.reset(dispatch_source_create(
-      DISPATCH_SOURCE_TYPE_MACH_RECV, port, 0, storage_->queue.get()));
-  storage_->source_canceled.reset(dispatch_semaphore_create(0));
-
-  dispatch_source_set_event_handler(storage_->source.get(), event_handler);
-  dispatch_source_set_cancel_handler(storage_->source.get(), ^{
-    dispatch_semaphore_signal(storage_->source_canceled.get());
-  });
-}
-
-DispatchSourceMach::~DispatchSourceMach() {
-  // Cancel the source and wait for the semaphore to be signaled. This will
-  // ensure the source managed by this class is not used after it is freed.
-  dispatch_source_cancel(storage_->source.get());
-  storage_->source.reset();
-
-  dispatch_semaphore_wait(storage_->source_canceled.get(),
-                          DISPATCH_TIME_FOREVER);
-}
-
-void DispatchSourceMach::Resume() {
-  dispatch_resume(storage_->source.get());
-}
-
-dispatch_queue_t DispatchSourceMach::Queue() const {
-  return storage_->queue.get();
-}
-
-}  // namespace base::apple
diff --git a/tot/base/apple/dispatch_source_mach.h b/tot/base/apple/dispatch_source_mach.h
deleted file mode 100644
index e6289ba..0000000
--- a/tot/base/apple/dispatch_source_mach.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2014 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_APPLE_DISPATCH_SOURCE_MACH_H_
-#define BASE_APPLE_DISPATCH_SOURCE_MACH_H_
-
-#include <dispatch/dispatch.h>
-
-#include <memory>
-
-#include "base/base_export.h"
-
-namespace base::apple {
-
-// This class encapsulates a MACH_RECV dispatch source. When this object is
-// destroyed, the source will be cancelled and it will wait for the source
-// to stop executing work. The source can run on either a user-supplied queue,
-// or it can create its own for the source.
-class BASE_EXPORT DispatchSourceMach {
- public:
-  // Creates a new dispatch source for the |port| and schedules it on a new
-  // queue that will be created with |name|. When a Mach message is received,
-  // the |event_handler| will be called.
-  DispatchSourceMach(const char* name,
-                     mach_port_t port,
-                     void (^event_handler)());
-
-  // Creates a new dispatch source with the same semantics as above, but rather
-  // than creating a new queue, it schedules the source on |queue|.
-  DispatchSourceMach(dispatch_queue_t queue,
-                     mach_port_t port,
-                     void (^event_handler)());
-
-  DispatchSourceMach(const DispatchSourceMach&) = delete;
-  DispatchSourceMach& operator=(const DispatchSourceMach&) = delete;
-
-  // Cancels the source and waits for it to become fully cancelled before
-  // releasing the source.
-  ~DispatchSourceMach();
-
-  // Resumes the source. This must be called before any Mach messages will
-  // be received.
-  void Resume();
-
-  dispatch_queue_t Queue() const;
-
- private:
-  struct Storage;
-  std::unique_ptr<Storage> storage_;
-};
-
-}  // namespace base::apple
-
-#endif  // BASE_APPLE_DISPATCH_SOURCE_MACH_H_
diff --git a/tot/base/apple/dispatch_source_mach_unittest.cc b/tot/base/apple/dispatch_source_mach_unittest.cc
deleted file mode 100644
index 9fd7e21..0000000
--- a/tot/base/apple/dispatch_source_mach_unittest.cc
+++ /dev/null
@@ -1,125 +0,0 @@
-// Copyright 2014 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/apple/dispatch_source_mach.h"
-
-#include <mach/mach.h>
-
-#include <memory>
-
-#include "base/apple/scoped_mach_port.h"
-#include "base/logging.h"
-#include "base/test/test_timeouts.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace base::apple {
-
-class DispatchSourceMachTest : public testing::Test {
- public:
-  void SetUp() override {
-    mach_port_t port = MACH_PORT_NULL;
-    ASSERT_EQ(KERN_SUCCESS, mach_port_allocate(mach_task_self(),
-                                               MACH_PORT_RIGHT_RECEIVE, &port));
-    receive_right_.reset(port);
-
-    ASSERT_EQ(KERN_SUCCESS, mach_port_insert_right(mach_task_self(), port, port,
-                                                   MACH_MSG_TYPE_MAKE_SEND));
-    send_right_.reset(port);
-  }
-
-  mach_port_t GetPort() { return receive_right_.get(); }
-
-  void WaitForSemaphore(dispatch_semaphore_t semaphore) {
-    dispatch_semaphore_wait(
-        semaphore, dispatch_time(DISPATCH_TIME_NOW,
-                                 TestTimeouts::action_timeout().InSeconds() *
-                                     NSEC_PER_SEC));
-  }
-
- private:
-  base::apple::ScopedMachReceiveRight receive_right_;
-  base::apple::ScopedMachSendRight send_right_;
-};
-
-TEST_F(DispatchSourceMachTest, ReceiveAfterResume) {
-  dispatch_semaphore_t signal = dispatch_semaphore_create(0);
-  mach_port_t port = GetPort();
-
-  bool __block did_receive = false;
-  DispatchSourceMach source("org.chromium.base.test.ReceiveAfterResume", port,
-                            ^{
-                              mach_msg_empty_rcv_t msg = {{0}};
-                              msg.header.msgh_size = sizeof(msg);
-                              msg.header.msgh_local_port = port;
-                              mach_msg_receive(&msg.header);
-                              did_receive = true;
-
-                              dispatch_semaphore_signal(signal);
-                            });
-
-  mach_msg_empty_send_t msg = {{0}};
-  msg.header.msgh_size = sizeof(msg);
-  msg.header.msgh_remote_port = port;
-  msg.header.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_COPY_SEND);
-  ASSERT_EQ(KERN_SUCCESS, mach_msg_send(&msg.header));
-
-  EXPECT_FALSE(did_receive);
-
-  source.Resume();
-
-  WaitForSemaphore(signal);
-  dispatch_release(signal);
-
-  EXPECT_TRUE(did_receive);
-}
-
-TEST_F(DispatchSourceMachTest, NoMessagesAfterDestruction) {
-  mach_port_t port = GetPort();
-
-  std::unique_ptr<int> count(new int(0));
-  int* __block count_ptr = count.get();
-
-  std::unique_ptr<DispatchSourceMach> source(new DispatchSourceMach(
-      "org.chromium.base.test.NoMessagesAfterDestruction", port, ^{
-        mach_msg_empty_rcv_t msg = {{0}};
-        msg.header.msgh_size = sizeof(msg);
-        msg.header.msgh_local_port = port;
-        mach_msg_receive(&msg.header);
-        LOG(INFO) << "Receive " << *count_ptr;
-        ++(*count_ptr);
-      }));
-  source->Resume();
-
-  dispatch_queue_t queue =
-      dispatch_queue_create("org.chromium.base.test.MessageSend", NULL);
-  dispatch_semaphore_t signal = dispatch_semaphore_create(0);
-  for (int i = 0; i < 30; ++i) {
-    dispatch_async(queue, ^{
-      mach_msg_empty_send_t msg = {{0}};
-      msg.header.msgh_size = sizeof(msg);
-      msg.header.msgh_remote_port = port;
-      msg.header.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_COPY_SEND);
-      mach_msg_send(&msg.header);
-    });
-
-    // After sending five messages, shut down the source and taint the
-    // pointer the handler dereferences. The test will crash if |count_ptr|
-    // is being used after "free".
-    if (i == 5) {
-      std::unique_ptr<DispatchSourceMach>* source_ptr = &source;
-      dispatch_async(queue, ^{
-        source_ptr->reset();
-        count_ptr = reinterpret_cast<int*>(0xdeaddead);
-        dispatch_semaphore_signal(signal);
-      });
-    }
-  }
-
-  WaitForSemaphore(signal);
-  dispatch_release(signal);
-
-  dispatch_release(queue);
-}
-
-}  // namespace base::apple
diff --git a/tot/base/apple/dispatch_source_unittest.cc b/tot/base/apple/dispatch_source_unittest.cc
new file mode 100644
index 0000000..c4af9a4
--- /dev/null
+++ b/tot/base/apple/dispatch_source_unittest.cc
@@ -0,0 +1,182 @@
+// Copyright 2014 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/apple/dispatch_source.h"
+
+#include <mach/mach.h>
+
+#include <memory>
+
+#include "base/apple/scoped_mach_port.h"
+#include "base/logging.h"
+#include "base/test/test_timeouts.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace base::apple {
+
+class DispatchSourceTest : public testing::Test {
+ public:
+  void SetUp() override {
+    mach_port_t port = MACH_PORT_NULL;
+    ASSERT_EQ(KERN_SUCCESS, mach_port_allocate(mach_task_self(),
+                                               MACH_PORT_RIGHT_RECEIVE, &port));
+    receive_right_.reset(port);
+
+    ASSERT_EQ(KERN_SUCCESS, mach_port_insert_right(mach_task_self(), port, port,
+                                                   MACH_MSG_TYPE_MAKE_SEND));
+    send_right_.reset(port);
+  }
+
+  mach_port_t GetPort() { return receive_right_.get(); }
+
+  void WaitForSemaphore(dispatch_semaphore_t semaphore) {
+    dispatch_semaphore_wait(
+        semaphore, dispatch_time(DISPATCH_TIME_NOW,
+                                 TestTimeouts::action_timeout().InSeconds() *
+                                     NSEC_PER_SEC));
+  }
+
+ private:
+  base::apple::ScopedMachReceiveRight receive_right_;
+  base::apple::ScopedMachSendRight send_right_;
+};
+
+TEST_F(DispatchSourceTest, ReceiveAfterResume) {
+  dispatch_semaphore_t signal = dispatch_semaphore_create(0);
+  mach_port_t port = GetPort();
+
+  bool __block did_receive = false;
+  DispatchSource source("org.chromium.base.test.ReceiveAfterResume", port, ^{
+    mach_msg_empty_rcv_t msg = {{0}};
+    msg.header.msgh_size = sizeof(msg);
+    msg.header.msgh_local_port = port;
+    mach_msg_receive(&msg.header);
+    did_receive = true;
+
+    dispatch_semaphore_signal(signal);
+  });
+
+  mach_msg_empty_send_t msg = {{0}};
+  msg.header.msgh_size = sizeof(msg);
+  msg.header.msgh_remote_port = port;
+  msg.header.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_COPY_SEND);
+  ASSERT_EQ(KERN_SUCCESS, mach_msg_send(&msg.header));
+
+  EXPECT_FALSE(did_receive);
+
+  source.Resume();
+
+  WaitForSemaphore(signal);
+  dispatch_release(signal);
+
+  EXPECT_TRUE(did_receive);
+}
+
+TEST_F(DispatchSourceTest, NoMessagesAfterDestruction) {
+  mach_port_t port = GetPort();
+
+  std::unique_ptr<int> count(new int(0));
+  int* __block count_ptr = count.get();
+
+  std::unique_ptr<DispatchSource> source(new DispatchSource(
+      "org.chromium.base.test.NoMessagesAfterDestruction", port, ^{
+        mach_msg_empty_rcv_t msg = {{0}};
+        msg.header.msgh_size = sizeof(msg);
+        msg.header.msgh_local_port = port;
+        mach_msg_receive(&msg.header);
+        LOG(INFO) << "Receive " << *count_ptr;
+        ++(*count_ptr);
+      }));
+  source->Resume();
+
+  dispatch_queue_t queue =
+      dispatch_queue_create("org.chromium.base.test.MessageSend", NULL);
+  dispatch_semaphore_t signal = dispatch_semaphore_create(0);
+  for (int i = 0; i < 30; ++i) {
+    dispatch_async(queue, ^{
+      mach_msg_empty_send_t msg = {{0}};
+      msg.header.msgh_size = sizeof(msg);
+      msg.header.msgh_remote_port = port;
+      msg.header.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_COPY_SEND);
+      mach_msg_send(&msg.header);
+    });
+
+    // After sending five messages, shut down the source and taint the
+    // pointer the handler dereferences. The test will crash if |count_ptr|
+    // is being used after "free".
+    if (i == 5) {
+      std::unique_ptr<DispatchSource>* source_ptr = &source;
+      dispatch_async(queue, ^{
+        source_ptr->reset();
+        count_ptr = reinterpret_cast<int*>(0xdeaddead);
+        dispatch_semaphore_signal(signal);
+      });
+    }
+  }
+
+  WaitForSemaphore(signal);
+  dispatch_release(signal);
+
+  dispatch_release(queue);
+}
+
+class DispatchSourceFdTest : public testing::Test {
+ public:
+  void SetUp() override {
+    /* Create the pipe. */
+    ASSERT_EQ(KERN_SUCCESS, pipe(pipe_fds_));
+  }
+
+  int GetWrite() { return pipe_fds_[1]; }
+  int GetRead() { return pipe_fds_[0]; }
+
+  void WaitForSemaphore(dispatch_semaphore_t semaphore) {
+    dispatch_semaphore_wait(
+        semaphore, dispatch_time(DISPATCH_TIME_NOW,
+                                 TestTimeouts::action_timeout().InSeconds() *
+                                     NSEC_PER_SEC));
+  }
+
+ private:
+  int pipe_fds_[2];
+};
+
+TEST_F(DispatchSourceFdTest, ReceiveAfterResume) {
+  dispatch_semaphore_t signal = dispatch_semaphore_create(0);
+  dispatch_queue_t queue = dispatch_queue_create(
+      "org.chromium.base.test.ReceiveAfterResume", DISPATCH_QUEUE_SERIAL);
+  int read_fd = GetRead();
+
+  bool __block did_receive = false;
+  DispatchSource source(queue, read_fd, DISPATCH_SOURCE_TYPE_READ, ^{
+    char buf[1];
+    ASSERT_EQ(read(read_fd, &buf, 1), 1);
+    did_receive = true;
+
+    dispatch_semaphore_signal(signal);
+  });
+
+  int write_fd = GetWrite();
+  ASSERT_EQ(write(write_fd, "1", 1), 1);
+
+  EXPECT_FALSE(did_receive);
+
+  source.Resume();
+
+  WaitForSemaphore(signal);
+
+  EXPECT_TRUE(did_receive);
+
+  source.Suspend();
+  did_receive = false;
+  ASSERT_EQ(write(write_fd, "2", 1), 1);
+  EXPECT_FALSE(did_receive);
+
+  source.Resume();
+
+  WaitForSemaphore(signal);
+  dispatch_release(signal);
+}
+
+}  // namespace base::apple
diff --git a/tot/base/apple/foundation_util.mm b/tot/base/apple/foundation_util.mm
index fa3ff7f..5c9a383 100644
--- a/tot/base/apple/foundation_util.mm
+++ b/tot/base/apple/foundation_util.mm
@@ -10,6 +10,7 @@
 #include <stdlib.h>
 #include <string.h>
 
+#include <algorithm>
 #include <vector>
 
 #include "base/apple/bridging.h"
@@ -22,7 +23,6 @@
 #include "base/logging.h"
 #include "base/numerics/checked_math.h"
 #include "base/numerics/safe_conversions.h"
-#include "base/ranges/algorithm.h"
 #include "base/strings/string_util.h"
 #include "base/strings/sys_string_conversions.h"
 #include "build/branding_buildflags.h"
@@ -234,7 +234,7 @@
     return FilePath();
   }
 
-  auto app = ranges::find_if(
+  auto app = std::ranges::find_if(
       Reversed(components), [](const std::string& component) -> bool {
         return component.size() > kExtLength && EndsWith(component, kExt);
       });
diff --git a/tot/base/apple/foundation_util_unittest.mm b/tot/base/apple/foundation_util_unittest.mm
index 08ea54e..7508290 100644
--- a/tot/base/apple/foundation_util_unittest.mm
+++ b/tot/base/apple/foundation_util_unittest.mm
@@ -430,13 +430,13 @@
     const char* expected_hex;
   } nsinteger_cases[] = {
 #if !defined(ARCH_CPU_64_BITS)
-    {12345678, "12345678", "bc614e"},
-    {-12345678, "-12345678", "ff439eb2"},
+      {12345678, "12345678", "bc614e"},
+      {-12345678, "-12345678", "ff439eb2"},
 #else
-    {12345678, "12345678", "bc614e"},
-    {-12345678, "-12345678", "ffffffffff439eb2"},
-    {137451299150l, "137451299150", "2000bc614e"},
-    {-137451299150l, "-137451299150", "ffffffdfff439eb2"},
+      {12345678, "12345678", "bc614e"},
+      {-12345678, "-12345678", "ffffffffff439eb2"},
+      {137451299150l, "137451299150", "2000bc614e"},
+      {-137451299150l, "-137451299150", "ffffffdfff439eb2"},
 #endif  // !defined(ARCH_CPU_64_BITS)
   };
 
@@ -454,13 +454,13 @@
     const char* expected_hex;
   } nsuinteger_cases[] = {
 #if !defined(ARCH_CPU_64_BITS)
-    {12345678u, "12345678", "bc614e"},
-    {4282621618u, "4282621618", "ff439eb2"},
+      {12345678u, "12345678", "bc614e"},
+      {4282621618u, "4282621618", "ff439eb2"},
 #else
-    {12345678u, "12345678", "bc614e"},
-    {4282621618u, "4282621618", "ff439eb2"},
-    {137451299150ul, "137451299150", "2000bc614e"},
-    {18446743936258252466ul, "18446743936258252466", "ffffffdfff439eb2"},
+      {12345678u, "12345678", "bc614e"},
+      {4282621618u, "4282621618", "ff439eb2"},
+      {137451299150ul, "137451299150", "2000bc614e"},
+      {18446743936258252466ul, "18446743936258252466", "ffffffdfff439eb2"},
 #endif  // !defined(ARCH_CPU_64_BITS)
   };
 
diff --git a/tot/base/apple/mach_logging.h b/tot/base/apple/mach_logging.h
index 24d609e..46ea5e3 100644
--- a/tot/base/apple/mach_logging.h
+++ b/tot/base/apple/mach_logging.h
@@ -67,40 +67,39 @@
 #endif
 
 #define MACH_LOG_STREAM(severity, mach_err) \
-    COMPACT_GOOGLE_LOG_EX_ ## severity(MachLogMessage, mach_err).stream()
+  COMPACT_GOOGLE_LOG_EX_##severity(MachLogMessage, mach_err).stream()
 #define MACH_VLOG_STREAM(verbose_level, mach_err) \
-    logging::MachLogMessage(__FILE__, __LINE__, \
-                            -verbose_level, mach_err).stream()
+  logging::MachLogMessage(__FILE__, __LINE__, -verbose_level, mach_err).stream()
 
 #define MACH_LOG(severity, mach_err) \
-    LAZY_STREAM(MACH_LOG_STREAM(severity, mach_err), LOG_IS_ON(severity))
+  LAZY_STREAM(MACH_LOG_STREAM(severity, mach_err), LOG_IS_ON(severity))
 #define MACH_LOG_IF(severity, condition, mach_err) \
-    LAZY_STREAM(MACH_LOG_STREAM(severity, mach_err), \
-                LOG_IS_ON(severity) && (condition))
+  LAZY_STREAM(MACH_LOG_STREAM(severity, mach_err), \
+              LOG_IS_ON(severity) && (condition))
 
-#define MACH_VLOG(verbose_level, mach_err) \
-    LAZY_STREAM(MACH_VLOG_STREAM(verbose_level, mach_err), \
-                VLOG_IS_ON(verbose_level))
+#define MACH_VLOG(verbose_level, mach_err)               \
+  LAZY_STREAM(MACH_VLOG_STREAM(verbose_level, mach_err), \
+              VLOG_IS_ON(verbose_level))
 #define MACH_VLOG_IF(verbose_level, condition, mach_err) \
-    LAZY_STREAM(MACH_VLOG_STREAM(verbose_level, mach_err), \
-                VLOG_IS_ON(verbose_level) && (condition))
+  LAZY_STREAM(MACH_VLOG_STREAM(verbose_level, mach_err), \
+              VLOG_IS_ON(verbose_level) && (condition))
 
-#define MACH_CHECK(condition, mach_err) \
-    LAZY_STREAM(MACH_LOG_STREAM(FATAL, mach_err), !(condition)) \
-    << "Check failed: " # condition << ". "
+#define MACH_CHECK(condition, mach_err)                       \
+  LAZY_STREAM(MACH_LOG_STREAM(FATAL, mach_err), !(condition)) \
+      << "Check failed: " #condition << ". "
 
 #define MACH_DLOG(severity, mach_err) \
-    LAZY_STREAM(MACH_LOG_STREAM(severity, mach_err), DLOG_IS_ON(severity))
+  LAZY_STREAM(MACH_LOG_STREAM(severity, mach_err), DLOG_IS_ON(severity))
 #define MACH_DLOG_IF(severity, condition, mach_err) \
-    LAZY_STREAM(MACH_LOG_STREAM(severity, mach_err), \
-                DLOG_IS_ON(severity) && (condition))
+  LAZY_STREAM(MACH_LOG_STREAM(severity, mach_err),  \
+              DLOG_IS_ON(severity) && (condition))
 
-#define MACH_DVLOG(verbose_level, mach_err) \
-    LAZY_STREAM(MACH_VLOG_STREAM(verbose_level, mach_err), \
-                MACH_DVLOG_IS_ON(verbose_level))
+#define MACH_DVLOG(verbose_level, mach_err)              \
+  LAZY_STREAM(MACH_VLOG_STREAM(verbose_level, mach_err), \
+              MACH_DVLOG_IS_ON(verbose_level))
 #define MACH_DVLOG_IF(verbose_level, condition, mach_err) \
-    LAZY_STREAM(MACH_VLOG_STREAM(verbose_level, mach_err), \
-                MACH_DVLOG_IS_ON(verbose_level) && (condition))
+  LAZY_STREAM(MACH_VLOG_STREAM(verbose_level, mach_err),  \
+              MACH_DVLOG_IS_ON(verbose_level) && (condition))
 
 #define MACH_DCHECK(condition, mach_err)        \
   LAZY_STREAM(MACH_LOG_STREAM(FATAL, mach_err), \
@@ -141,43 +140,43 @@
 #define BOOTSTRAP_DVLOG_IS_ON MACH_DVLOG_IS_ON
 
 #define BOOTSTRAP_LOG_STREAM(severity, bootstrap_err) \
-    COMPACT_GOOGLE_LOG_EX_ ## severity(BootstrapLogMessage, \
-                                       bootstrap_err).stream()
-#define BOOTSTRAP_VLOG_STREAM(verbose_level, bootstrap_err) \
-    logging::BootstrapLogMessage(__FILE__, __LINE__, \
-                                 -verbose_level, bootstrap_err).stream()
+  COMPACT_GOOGLE_LOG_EX_##severity(BootstrapLogMessage, bootstrap_err).stream()
+#define BOOTSTRAP_VLOG_STREAM(verbose_level, bootstrap_err)        \
+  logging::BootstrapLogMessage(__FILE__, __LINE__, -verbose_level, \
+                               bootstrap_err)                      \
+      .stream()
 
-#define BOOTSTRAP_LOG(severity, bootstrap_err) \
-    LAZY_STREAM(BOOTSTRAP_LOG_STREAM(severity, \
-                                     bootstrap_err), LOG_IS_ON(severity))
+#define BOOTSTRAP_LOG(severity, bootstrap_err)               \
+  LAZY_STREAM(BOOTSTRAP_LOG_STREAM(severity, bootstrap_err), \
+              LOG_IS_ON(severity))
 #define BOOTSTRAP_LOG_IF(severity, condition, bootstrap_err) \
-    LAZY_STREAM(BOOTSTRAP_LOG_STREAM(severity, bootstrap_err), \
-                LOG_IS_ON(severity) && (condition))
+  LAZY_STREAM(BOOTSTRAP_LOG_STREAM(severity, bootstrap_err), \
+              LOG_IS_ON(severity) && (condition))
 
-#define BOOTSTRAP_VLOG(verbose_level, bootstrap_err) \
-    LAZY_STREAM(BOOTSTRAP_VLOG_STREAM(verbose_level, bootstrap_err), \
-                VLOG_IS_ON(verbose_level))
+#define BOOTSTRAP_VLOG(verbose_level, bootstrap_err)               \
+  LAZY_STREAM(BOOTSTRAP_VLOG_STREAM(verbose_level, bootstrap_err), \
+              VLOG_IS_ON(verbose_level))
 #define BOOTSTRAP_VLOG_IF(verbose_level, condition, bootstrap_err) \
-    LAZY_STREAM(BOOTSTRAP_VLOG_STREAM(verbose_level, bootstrap_err), \
-                VLOG_IS_ON(verbose_level) && (condition))
+  LAZY_STREAM(BOOTSTRAP_VLOG_STREAM(verbose_level, bootstrap_err), \
+              VLOG_IS_ON(verbose_level) && (condition))
 
-#define BOOTSTRAP_CHECK(condition, bootstrap_err) \
-    LAZY_STREAM(BOOTSTRAP_LOG_STREAM(FATAL, bootstrap_err), !(condition)) \
-    << "Check failed: " # condition << ". "
+#define BOOTSTRAP_CHECK(condition, bootstrap_err)                       \
+  LAZY_STREAM(BOOTSTRAP_LOG_STREAM(FATAL, bootstrap_err), !(condition)) \
+      << "Check failed: " #condition << ". "
 
-#define BOOTSTRAP_DLOG(severity, bootstrap_err) \
-    LAZY_STREAM(BOOTSTRAP_LOG_STREAM(severity, bootstrap_err), \
-                DLOG_IS_ON(severity))
+#define BOOTSTRAP_DLOG(severity, bootstrap_err)              \
+  LAZY_STREAM(BOOTSTRAP_LOG_STREAM(severity, bootstrap_err), \
+              DLOG_IS_ON(severity))
 #define BOOTSTRAP_DLOG_IF(severity, condition, bootstrap_err) \
-    LAZY_STREAM(BOOTSTRAP_LOG_STREAM(severity, bootstrap_err), \
-                DLOG_IS_ON(severity) && (condition))
+  LAZY_STREAM(BOOTSTRAP_LOG_STREAM(severity, bootstrap_err),  \
+              DLOG_IS_ON(severity) && (condition))
 
-#define BOOTSTRAP_DVLOG(verbose_level, bootstrap_err) \
-    LAZY_STREAM(BOOTSTRAP_VLOG_STREAM(verbose_level, bootstrap_err), \
-                BOOTSTRAP_DVLOG_IS_ON(verbose_level))
+#define BOOTSTRAP_DVLOG(verbose_level, bootstrap_err)              \
+  LAZY_STREAM(BOOTSTRAP_VLOG_STREAM(verbose_level, bootstrap_err), \
+              BOOTSTRAP_DVLOG_IS_ON(verbose_level))
 #define BOOTSTRAP_DVLOG_IF(verbose_level, condition, bootstrap_err) \
-    LAZY_STREAM(BOOTSTRAP_VLOG_STREAM(verbose_level, bootstrap_err), \
-                BOOTSTRAP_DVLOG_IS_ON(verbose_level) && (condition))
+  LAZY_STREAM(BOOTSTRAP_VLOG_STREAM(verbose_level, bootstrap_err),  \
+              BOOTSTRAP_DVLOG_IS_ON(verbose_level) && (condition))
 
 #define BOOTSTRAP_DCHECK(condition, bootstrap_err)        \
   LAZY_STREAM(BOOTSTRAP_LOG_STREAM(FATAL, bootstrap_err), \
diff --git a/tot/base/apple/mach_port_rendezvous.cc b/tot/base/apple/mach_port_rendezvous.cc
index c510f27..23c03b4 100644
--- a/tot/base/apple/mach_port_rendezvous.cc
+++ b/tot/base/apple/mach_port_rendezvous.cc
@@ -2,11 +2,6 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifdef UNSAFE_BUFFERS_BUILD
-// TODO(crbug.com/341324165): Fix and remove.
-#pragma allow_unsafe_buffers
-#endif
-
 #include "base/apple/mach_port_rendezvous.h"
 
 #include <mach/mig.h>
@@ -17,6 +12,7 @@
 #include "base/apple/foundation_util.h"
 #include "base/apple/mach_logging.h"
 #include "base/bits.h"
+#include "base/compiler_specific.h"
 #include "base/containers/buffer_iterator.h"
 #include "base/feature_list.h"
 #include "base/logging.h"
@@ -35,6 +31,7 @@
 #include <bsm/libbsm.h>
 #include <servers/bootstrap.h>
 
+#include "base/apple/scoped_dispatch_object.h"
 #include "base/environment.h"
 #include "base/mac/info_plist_data.h"
 #include "base/strings/string_number_conversions.h"
@@ -72,7 +69,7 @@
 #endif
 
 // This limit is arbitrary and can be safely increased in the future.
-constexpr size_t kMaximumRendezvousPorts = 5;
+constexpr size_t kMaximumRendezvousPorts = 6;
 
 enum MachRendezvousMsgId : mach_msg_id_t {
   kMachRendezvousMsgIdRequest = 'mrzv',
@@ -248,7 +245,8 @@
   const size_t buffer_size =
       CalculateResponseSize(port_count, additional_data.size());
   auto buffer = std::make_unique<uint8_t[]>(buffer_size);
-  BufferIterator<uint8_t> iterator(buffer.get(), buffer_size);
+  auto iterator =
+      UNSAFE_TODO(BufferIterator<uint8_t>(buffer.get(), buffer_size));
 
   auto* message = iterator.MutableObject<mach_msg_base_t>();
   message->header.msgh_bits =
@@ -297,7 +295,7 @@
   DCHECK_LT(ports_.size(), kMaximumRendezvousPorts);
   bool res = apple::CreateMachPort(&server_port_, &send_right_);
   CHECK(res) << "Failed to create mach server port";
-  dispatch_source_ = std::make_unique<apple::DispatchSourceMach>(
+  dispatch_source_ = std::make_unique<apple::DispatchSource>(
       "MachPortRendezvousServer", server_port_.get(), ^{
         HandleRequest();
       });
@@ -325,6 +323,19 @@
 
 #if BUILDFLAG(IS_MAC)
 
+struct MachPortRendezvousServerMac::ClientData {
+  ClientData();
+  ClientData(ClientData&&);
+  ~ClientData();
+
+  // A DISPATCH_SOURCE_TYPE_PROC / DISPATCH_PROC_EXIT dispatch source. When
+  // the source is triggered, it calls OnClientExited().
+  apple::ScopedDispatchObject<dispatch_source_t> exit_watcher;
+
+  MachPortsForRendezvous ports;
+  std::optional<mac::ProcessRequirement> requirement;
+};
+
 // static
 MachPortRendezvousServerMac* MachPortRendezvousServerMac::GetInstance() {
   static auto* instance = new MachPortRendezvousServerMac();
@@ -398,7 +409,7 @@
       apple::ScopedMachReceiveRight::Receiver(server_port_).get());
   BOOTSTRAP_CHECK(kr == KERN_SUCCESS, kr)
       << "bootstrap_check_in " << bootstrap_name;
-  dispatch_source_ = std::make_unique<apple::DispatchSourceMach>(
+  dispatch_source_ = std::make_unique<apple::DispatchSource>(
       bootstrap_name.c_str(), server_port_.get(), ^{
         HandleRequest();
       });
@@ -407,6 +418,10 @@
 
 MachPortRendezvousServerMac::~MachPortRendezvousServerMac() = default;
 
+void MachPortRendezvousServerMac::ClearClientDataForTesting() {
+  client_data_.clear();
+}
+
 std::optional<MachPortsForRendezvous>
 MachPortRendezvousServerMac::PortsForClient(audit_token_t audit_token) {
   pid_t pid = audit_token_to_pid(audit_token);
@@ -494,7 +509,8 @@
                             additional_response_data_size) +
       sizeof(mach_msg_audit_trailer_t);
   auto buffer = std::make_unique<uint8_t[]>(buffer_size);
-  BufferIterator<uint8_t> iterator(buffer.get(), buffer_size);
+  auto iterator =
+      UNSAFE_TODO(BufferIterator<uint8_t>(buffer.get(), buffer_size));
 
   // Perform a send and receive mach_msg.
   auto* message = iterator.MutableObject<mach_msg_base_t>();
diff --git a/tot/base/apple/mach_port_rendezvous.h b/tot/base/apple/mach_port_rendezvous.h
index 00d4504..40a0e4b 100644
--- a/tot/base/apple/mach_port_rendezvous.h
+++ b/tot/base/apple/mach_port_rendezvous.h
@@ -15,7 +15,7 @@
 #include <string>
 #include <vector>
 
-#include "base/apple/dispatch_source_mach.h"
+#include "base/apple/dispatch_source.h"
 #include "base/apple/scoped_mach_port.h"
 #include "base/base_export.h"
 #include "base/containers/buffer_iterator.h"
@@ -25,7 +25,6 @@
 #include "build/ios_buildflags.h"
 
 #if BUILDFLAG(IS_MAC)
-#include "base/apple/scoped_dispatch_object.h"
 #include "base/environment.h"
 #include "base/mac/process_requirement.h"
 #endif
@@ -100,7 +99,7 @@
   apple::ScopedMachReceiveRight server_port_;
 
   // Mach message dispatch source for |server_port_|.
-  std::unique_ptr<apple::DispatchSourceMach> dispatch_source_;
+  std::unique_ptr<apple::DispatchSource> dispatch_source_;
 
   // Ask for the associated ports associated with `audit_token`.
   // Return `std::nullopt` if the client is not authorized to
@@ -206,6 +205,8 @@
   // registered.
   Lock& GetLock() LOCK_RETURNED(lock_) { return lock_; }
 
+  void ClearClientDataForTesting() EXCLUSIVE_LOCKS_REQUIRED(GetLock());
+
  protected:
   // Returns the registered collection of ports for the specified `audit_token`.
   // `std::nullopt` indicates that the client is not authorized to retrieve the
@@ -225,18 +226,7 @@
   MachPortRendezvousServerMac();
   ~MachPortRendezvousServerMac() override;
 
-  struct ClientData {
-    ClientData();
-    ClientData(ClientData&&);
-    ~ClientData();
-
-    // A DISPATCH_SOURCE_TYPE_PROC / DISPATCH_PROC_EXIT dispatch source. When
-    // the source is triggered, it calls OnClientExited().
-    apple::ScopedDispatchObject<dispatch_source_t> exit_watcher;
-
-    MachPortsForRendezvous ports;
-    std::optional<mac::ProcessRequirement> requirement;
-  };
+  struct ClientData;
 
   // Returns the `ClientData` for `pid`, creating it if necessary.
   // It will be cleaned up automatically when `pid` exits.
diff --git a/tot/base/apple/mach_port_rendezvous_fuzzer.cc b/tot/base/apple/mach_port_rendezvous_fuzzer.cc
index 53cb23b..6d06bd0 100644
--- a/tot/base/apple/mach_port_rendezvous_fuzzer.cc
+++ b/tot/base/apple/mach_port_rendezvous_fuzzer.cc
@@ -27,7 +27,8 @@
 
   void ClearClientData() EXCLUSIVE_LOCKS_REQUIRED(
       base::MachPortRendezvousServerMac::GetInstance()->GetLock()) {
-    base::MachPortRendezvousServerMac::GetInstance()->client_data_.clear();
+    base::MachPortRendezvousServerMac::GetInstance()
+        ->ClearClientDataForTesting();
   }
 
   base::apple::ScopedMachSendRight server_send_right;
diff --git a/tot/base/apple/scoped_mach_port.h b/tot/base/apple/scoped_mach_port.h
index 99706b0..da32367 100644
--- a/tot/base/apple/scoped_mach_port.h
+++ b/tot/base/apple/scoped_mach_port.h
@@ -17,25 +17,19 @@
 namespace internal {
 
 struct BASE_EXPORT SendRightTraits {
-  static mach_port_t InvalidValue() {
-    return MACH_PORT_NULL;
-  }
+  static mach_port_t InvalidValue() { return MACH_PORT_NULL; }
 
   BASE_EXPORT static void Free(mach_port_t port);
 };
 
 struct BASE_EXPORT ReceiveRightTraits {
-  static mach_port_t InvalidValue() {
-    return MACH_PORT_NULL;
-  }
+  static mach_port_t InvalidValue() { return MACH_PORT_NULL; }
 
   BASE_EXPORT static void Free(mach_port_t port);
 };
 
 struct PortSetTraits {
-  static mach_port_t InvalidValue() {
-    return MACH_PORT_NULL;
-  }
+  static mach_port_t InvalidValue() { return MACH_PORT_NULL; }
 
   BASE_EXPORT static void Free(mach_port_t port);
 };
diff --git a/tot/base/apple/scoped_mach_vm.h b/tot/base/apple/scoped_mach_vm.h
index cb9765d..7c2ae37 100644
--- a/tot/base/apple/scoped_mach_vm.h
+++ b/tot/base/apple/scoped_mach_vm.h
@@ -72,13 +72,9 @@
   // aligned.
   void reset_unaligned(vm_address_t address, vm_size_t size);
 
-  vm_address_t address() const {
-    return address_;
-  }
+  vm_address_t address() const { return address_; }
 
-  vm_size_t size() const {
-    return size_;
-  }
+  vm_size_t size() const { return size_; }
 
   void swap(ScopedMachVM& that) {
     std::swap(address_, that.address_);
diff --git a/tot/base/apple/scoped_nsobject_unittest.mm b/tot/base/apple/scoped_nsobject_unittest.mm
index 97291a6..2ba24d6 100644
--- a/tot/base/apple/scoped_nsobject_unittest.mm
+++ b/tot/base/apple/scoped_nsobject_unittest.mm
@@ -2,9 +2,10 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "base/apple/scoped_nsobject.h"
+
 #include <vector>
 
-#include "base/apple/scoped_nsobject.h"
 #include "base/compiler_specific.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
diff --git a/tot/base/apple/scoped_objc_class_swizzler.mm b/tot/base/apple/scoped_objc_class_swizzler.mm
index d06b43a..fb9d706 100644
--- a/tot/base/apple/scoped_objc_class_swizzler.mm
+++ b/tot/base/apple/scoped_objc_class_swizzler.mm
@@ -7,6 +7,7 @@
 #include <string.h>
 
 #include "base/check_op.h"
+#include "base/compiler_specific.h"
 
 namespace base::apple {
 
@@ -59,8 +60,8 @@
   const char* new_types = method_getTypeEncoding(new_selector_impl_);
   DCHECK(old_types);
   DCHECK(new_types);
-  DCHECK_EQ(0, strcmp(old_types, new_types));
-  if (!old_types || !new_types || strcmp(old_types, new_types)) {
+  DCHECK_EQ(0, UNSAFE_TODO(strcmp(old_types, new_types)));
+  if (!old_types || !new_types || UNSAFE_TODO(strcmp(old_types, new_types))) {
     old_selector_impl_ = new_selector_impl_ = nullptr;
     return;
   }
diff --git a/tot/base/at_exit.cc b/tot/base/at_exit.cc
index 4c35da4..0d41961 100644
--- a/tot/base/at_exit.cc
+++ b/tot/base/at_exit.cc
@@ -5,6 +5,7 @@
 #include "base/at_exit.h"
 
 #include <stddef.h>
+
 #include <ostream>
 #include <utility>
 
@@ -40,8 +41,9 @@
   }
   DCHECK_EQ(this, g_top_manager);
 
-  if (!g_disable_managers)
+  if (!g_disable_managers) {
     ProcessCallbacksNow();
+  }
   g_top_manager = next_manager_;
 }
 
diff --git a/tot/base/at_exit_unittest.cc b/tot/base/at_exit_unittest.cc
index 3363cb0..fdeea43 100644
--- a/tot/base/at_exit_unittest.cc
+++ b/tot/base/at_exit_unittest.cc
@@ -3,8 +3,8 @@
 // found in the LICENSE file.
 
 #include "base/at_exit.h"
-#include "base/functional/bind.h"
 
+#include "base/functional/bind.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace {
diff --git a/tot/base/atomicops.cc b/tot/base/atomicops.cc
new file mode 100644
index 0000000..7b6aca4
--- /dev/null
+++ b/tot/base/atomicops.cc
@@ -0,0 +1,65 @@
+// Copyright 2024 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/atomicops.h"
+
+#include <atomic>
+
+#include "base/memory/aligned_memory.h"
+
+namespace base::subtle {
+
+void RelaxedAtomicWriteMemcpy(base::span<uint8_t> dst,
+                              base::span<const uint8_t> src) {
+  CHECK_EQ(dst.size(), src.size());
+  size_t bytes = dst.size();
+  uint8_t* dst_byte_ptr = dst.data();
+  const uint8_t* src_byte_ptr = src.data();
+  // Make sure that we can at least copy byte by byte with atomics.
+  static_assert(std::atomic_ref<uint8_t>::required_alignment == 1);
+
+  // Alignment for uintmax_t atomics that we use in the happy case.
+  constexpr size_t kDesiredAlignment =
+      std::atomic_ref<uintmax_t>::required_alignment;
+
+  // Copy byte-by-byte until `dst_byte_ptr` is not properly aligned for
+  // the happy case.
+  while (bytes > 0 && !IsAligned(dst_byte_ptr, kDesiredAlignment)) {
+    std::atomic_ref<uint8_t>(*dst_byte_ptr)
+        .store(*src_byte_ptr, std::memory_order_relaxed);
+    // SAFETY: We check above that `dst_byte_ptr` and `src_byte_ptr` point
+    // to spans of sufficient size.
+    UNSAFE_BUFFERS(++dst_byte_ptr);
+    UNSAFE_BUFFERS(++src_byte_ptr);
+    --bytes;
+  }
+
+  // Happy case where both `src_byte_ptr` and `dst_byte_ptr` are both properly
+  // aligned and the largest possible atomic is used for copying.
+  if (IsAligned(src_byte_ptr, kDesiredAlignment)) {
+    while (bytes >= sizeof(uintmax_t)) {
+      std::atomic_ref<uintmax_t>(*reinterpret_cast<uintmax_t*>(dst_byte_ptr))
+          .store(*reinterpret_cast<const uintmax_t*>(src_byte_ptr),
+                 std::memory_order_relaxed);
+      // SAFETY: We check above that `dst_byte_ptr` and `src_byte_ptr` point
+      // to spans of sufficient size.
+      UNSAFE_BUFFERS(dst_byte_ptr += sizeof(uintmax_t));
+      UNSAFE_BUFFERS(src_byte_ptr += sizeof(uintmax_t));
+      bytes -= sizeof(uintmax_t);
+    }
+  }
+
+  // Copy what's left after the happy-case byte-by-byte.
+  while (bytes > 0) {
+    std::atomic_ref<uint8_t>(*dst_byte_ptr)
+        .store(*src_byte_ptr, std::memory_order_relaxed);
+    // SAFETY: We check above that `dst_byte_ptr` and `src_byte_ptr` point
+    // to spans of sufficient size.
+    UNSAFE_BUFFERS(++dst_byte_ptr);
+    UNSAFE_BUFFERS(++src_byte_ptr);
+    --bytes;
+  }
+}
+
+}  // namespace base::subtle
diff --git a/tot/base/atomicops.h b/tot/base/atomicops.h
index 47a10e6..7b7efaa 100644
--- a/tot/base/atomicops.h
+++ b/tot/base/atomicops.h
@@ -51,6 +51,9 @@
 // - libstdc++: captures bits/c++config.h for __GLIBCXX__
 #include <cstddef>
 
+#include "base/base_export.h"
+#include "base/compiler_specific.h"
+#include "base/containers/span.h"
 #include "build/build_config.h"
 
 namespace base {
@@ -95,8 +98,7 @@
 // *ptr with the increment applied.  This routine implies no memory barriers.
 Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment);
 
-Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
-                                 Atomic32 increment);
+Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment);
 
 // These following lower-level operations are typically useful only to people
 // implementing higher-level synchronization operations like spinlocks,
@@ -139,6 +141,28 @@
 Atomic64 Acquire_Load(volatile const Atomic64* ptr);
 #endif  // ARCH_CPU_64_BITS
 
+// Copies non-overlapping spans of the same size. Writes are done using C++
+// atomics with `std::memory_order_relaxed`.
+//
+// This is an analogue of `WTF::AtomicWriteMemcpy` and it should be used
+// for copying data into buffers that are accessible from another
+// thread while the copy is being done. The buffer will appear inconsistent,
+// but it won't trigger C++ UB and won't upset TSAN. The end of copy needs to
+// be signaled through a synchronization mechanism like fence, after
+// which the `dst` buffer will be observed as consistent.
+//
+// Notable example is a buffer owned by `SharedArrayBuffer`.
+// While the copy is being done, JS and WASM code can access the `dst` buffer
+// on a different thread. The data observed by JS may not be consistent
+// from application point of view (which is always the case with
+// `SharedArrayBuffer`).
+//
+// Reads from the `src` buffer are not atomic and `src` access
+// should be synchronized via other means.
+// More info: crbug.com/340606792
+BASE_EXPORT void RelaxedAtomicWriteMemcpy(base::span<uint8_t> dst,
+                                          base::span<const uint8_t> src);
+
 }  // namespace subtle
 }  // namespace base
 
diff --git a/tot/base/atomicops_internals_atomicword_compat.h b/tot/base/atomicops_internals_atomicword_compat.h
index 4097c8c..a45e002 100644
--- a/tot/base/atomicops_internals_atomicword_compat.h
+++ b/tot/base/atomicops_internals_atomicword_compat.h
@@ -30,26 +30,26 @@
 inline AtomicWord NoBarrier_CompareAndSwap(volatile AtomicWord* ptr,
                                            AtomicWord old_value,
                                            AtomicWord new_value) {
-  return NoBarrier_CompareAndSwap(
-      reinterpret_cast<volatile Atomic32*>(ptr), old_value, new_value);
+  return NoBarrier_CompareAndSwap(reinterpret_cast<volatile Atomic32*>(ptr),
+                                  old_value, new_value);
 }
 
 inline AtomicWord NoBarrier_AtomicExchange(volatile AtomicWord* ptr,
                                            AtomicWord new_value) {
-  return NoBarrier_AtomicExchange(
-      reinterpret_cast<volatile Atomic32*>(ptr), new_value);
+  return NoBarrier_AtomicExchange(reinterpret_cast<volatile Atomic32*>(ptr),
+                                  new_value);
 }
 
 inline AtomicWord NoBarrier_AtomicIncrement(volatile AtomicWord* ptr,
                                             AtomicWord increment) {
-  return NoBarrier_AtomicIncrement(
-      reinterpret_cast<volatile Atomic32*>(ptr), increment);
+  return NoBarrier_AtomicIncrement(reinterpret_cast<volatile Atomic32*>(ptr),
+                                   increment);
 }
 
 inline AtomicWord Barrier_AtomicIncrement(volatile AtomicWord* ptr,
                                           AtomicWord increment) {
-  return Barrier_AtomicIncrement(
-      reinterpret_cast<volatile Atomic32*>(ptr), increment);
+  return Barrier_AtomicIncrement(reinterpret_cast<volatile Atomic32*>(ptr),
+                                 increment);
 }
 
 inline AtomicWord Acquire_CompareAndSwap(volatile AtomicWord* ptr,
@@ -66,19 +66,17 @@
       reinterpret_cast<volatile Atomic32*>(ptr), old_value, new_value);
 }
 
-inline void NoBarrier_Store(volatile AtomicWord *ptr, AtomicWord value) {
-  NoBarrier_Store(
-      reinterpret_cast<volatile Atomic32*>(ptr), value);
+inline void NoBarrier_Store(volatile AtomicWord* ptr, AtomicWord value) {
+  NoBarrier_Store(reinterpret_cast<volatile Atomic32*>(ptr), value);
 }
 
 inline void Release_Store(volatile AtomicWord* ptr, AtomicWord value) {
-  return base::subtle::Release_Store(
-      reinterpret_cast<volatile Atomic32*>(ptr), value);
+  return base::subtle::Release_Store(reinterpret_cast<volatile Atomic32*>(ptr),
+                                     value);
 }
 
-inline AtomicWord NoBarrier_Load(volatile const AtomicWord *ptr) {
-  return NoBarrier_Load(
-      reinterpret_cast<volatile const Atomic32*>(ptr));
+inline AtomicWord NoBarrier_Load(volatile const AtomicWord* ptr) {
+  return NoBarrier_Load(reinterpret_cast<volatile const Atomic32*>(ptr));
 }
 
 inline AtomicWord Acquire_Load(volatile const AtomicWord* ptr) {
diff --git a/tot/base/atomicops_internals_portable.h b/tot/base/atomicops_internals_portable.h
index 5239062..f9180ac 100644
--- a/tot/base/atomicops_internals_portable.h
+++ b/tot/base/atomicops_internals_portable.h
@@ -52,9 +52,7 @@
                                          Atomic32 old_value,
                                          Atomic32 new_value) {
   ((AtomicLocation32)ptr)
-      ->compare_exchange_strong(old_value,
-                                new_value,
-                                std::memory_order_relaxed,
+      ->compare_exchange_strong(old_value, new_value, std::memory_order_relaxed,
                                 std::memory_order_relaxed);
   return old_value;
 }
@@ -82,9 +80,7 @@
                                        Atomic32 old_value,
                                        Atomic32 new_value) {
   ((AtomicLocation32)ptr)
-      ->compare_exchange_strong(old_value,
-                                new_value,
-                                std::memory_order_acquire,
+      ->compare_exchange_strong(old_value, new_value, std::memory_order_acquire,
                                 std::memory_order_acquire);
   return old_value;
 }
@@ -93,9 +89,7 @@
                                        Atomic32 old_value,
                                        Atomic32 new_value) {
   ((AtomicLocation32)ptr)
-      ->compare_exchange_strong(old_value,
-                                new_value,
-                                std::memory_order_release,
+      ->compare_exchange_strong(old_value, new_value, std::memory_order_release,
                                 std::memory_order_relaxed);
   return old_value;
 }
@@ -128,9 +122,7 @@
                                          Atomic64 old_value,
                                          Atomic64 new_value) {
   ((AtomicLocation64)ptr)
-      ->compare_exchange_strong(old_value,
-                                new_value,
-                                std::memory_order_relaxed,
+      ->compare_exchange_strong(old_value, new_value, std::memory_order_relaxed,
                                 std::memory_order_relaxed);
   return old_value;
 }
@@ -158,9 +150,7 @@
                                        Atomic64 old_value,
                                        Atomic64 new_value) {
   ((AtomicLocation64)ptr)
-      ->compare_exchange_strong(old_value,
-                                new_value,
-                                std::memory_order_acquire,
+      ->compare_exchange_strong(old_value, new_value, std::memory_order_acquire,
                                 std::memory_order_acquire);
   return old_value;
 }
@@ -169,9 +159,7 @@
                                        Atomic64 old_value,
                                        Atomic64 new_value) {
   ((AtomicLocation64)ptr)
-      ->compare_exchange_strong(old_value,
-                                new_value,
-                                std::memory_order_release,
+      ->compare_exchange_strong(old_value, new_value, std::memory_order_release,
                                 std::memory_order_relaxed);
   return old_value;
 }
diff --git a/tot/base/atomicops_unittest.cc b/tot/base/atomicops_unittest.cc
index b494bd1..463777d 100644
--- a/tot/base/atomicops_unittest.cc
+++ b/tot/base/atomicops_unittest.cc
@@ -2,11 +2,18 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#ifdef UNSAFE_BUFFERS_BUILD
+// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
+#pragma allow_unsafe_libc_calls
+#endif
+
 #include "base/atomicops.h"
 
 #include <stdint.h>
 #include <string.h>
+
 #include <type_traits>
+#include <vector>
 
 #include "testing/gtest/include/gtest/gtest.h"
 
@@ -79,10 +86,8 @@
   EXPECT_EQ(s.next_word, next_word_value);
 }
 
-
 #define NUM_BITS(T) (sizeof(T) * 8)
 
-
 template <class AtomicType>
 static void TestCompareAndSwap() {
   AtomicType value = 0;
@@ -99,8 +104,8 @@
 
   // Use test value that has non-zero bits in both halves, more for testing
   // 64-bit implementation on 32-bit platforms.
-  const AtomicType k_test_val = (static_cast<uint64_t>(1) <<
-                                 (NUM_BITS(AtomicType) - 2)) + 11;
+  const AtomicType k_test_val =
+      (static_cast<uint64_t>(1) << (NUM_BITS(AtomicType) - 2)) + 11;
   value = k_test_val;
   prev = base::subtle::NoBarrier_CompareAndSwap(&value, 0, 5);
   EXPECT_EQ(k_test_val, value);
@@ -112,7 +117,6 @@
   EXPECT_EQ(k_test_val, prev);
 }
 
-
 template <class AtomicType>
 static void TestAtomicExchange() {
   AtomicType value = 0;
@@ -122,8 +126,8 @@
 
   // Use test value that has non-zero bits in both halves, more for testing
   // 64-bit implementation on 32-bit platforms.
-  const AtomicType k_test_val = (static_cast<uint64_t>(1) <<
-                                 (NUM_BITS(AtomicType) - 2)) + 11;
+  const AtomicType k_test_val =
+      (static_cast<uint64_t>(1) << (NUM_BITS(AtomicType) - 2)) + 11;
   value = k_test_val;
   new_value = base::subtle::NoBarrier_AtomicExchange(&value, k_test_val);
   EXPECT_EQ(k_test_val, value);
@@ -135,12 +139,11 @@
   EXPECT_EQ(k_test_val, new_value);
 }
 
-
 template <class AtomicType>
 static void TestAtomicIncrementBounds() {
   // Test at rollover boundary between int_max and int_min
-  AtomicType test_val = (static_cast<uint64_t>(1) <<
-                         (NUM_BITS(AtomicType) - 1));
+  AtomicType test_val =
+      (static_cast<uint64_t>(1) << (NUM_BITS(AtomicType) - 1));
   AtomicType value = -1 ^ test_val;
   AtomicType new_value = base::subtle::NoBarrier_AtomicIncrement(&value, 1);
   EXPECT_EQ(test_val, value);
@@ -239,3 +242,24 @@
   TestLoad<base::subtle::Atomic32>();
   TestLoad<base::subtle::AtomicWord>();
 }
+
+TEST(AtomicOpsTest, RelaxedAtomicWriteMemcpy) {
+  std::vector<uint8_t> src(17);
+  for (size_t i = 0; i < src.size(); i++) {
+    src[i] = i + 1;
+  }
+
+  for (size_t i = 0; i < src.size(); i++) {
+    std::vector<uint8_t> dst(src.size());
+    size_t bytes_to_copy = src.size() - i;
+    base::subtle::RelaxedAtomicWriteMemcpy(
+        base::span(dst).first(bytes_to_copy),
+        base::span(src).subspan(i, bytes_to_copy));
+    for (size_t j = 0; j < bytes_to_copy; j++) {
+      EXPECT_EQ(src[i + j], dst[j]);
+    }
+    for (size_t j = bytes_to_copy; j < dst.size(); j++) {
+      EXPECT_EQ(0, dst[j]);
+    }
+  }
+}
diff --git a/tot/base/auto_reset.h b/tot/base/auto_reset.h
index 092d529..cfd803b 100644
--- a/tot/base/auto_reset.h
+++ b/tot/base/auto_reset.h
@@ -51,8 +51,9 @@
   }
 
   ~AutoReset() {
-    if (scoped_variable_)
+    if (scoped_variable_) {
       *scoped_variable_ = std::move(original_value_);
+    }
   }
 
  private:
diff --git a/tot/base/barrier_closure.cc b/tot/base/barrier_closure.cc
index 2597bdc..43f0f9e 100644
--- a/tot/base/barrier_closure.cc
+++ b/tot/base/barrier_closure.cc
@@ -34,8 +34,9 @@
 
 void BarrierInfo::Run() {
   DCHECK(!num_callbacks_left_.IsZero());
-  if (!num_callbacks_left_.Decrement())
+  if (!num_callbacks_left_.Decrement()) {
     std::move(done_closure_).Run();
+  }
 }
 
 void ShouldNeverRun() {
diff --git a/tot/base/barrier_closure_unittest.cc b/tot/base/barrier_closure_unittest.cc
index 29e672e..3c21338 100644
--- a/tot/base/barrier_closure_unittest.cc
+++ b/tot/base/barrier_closure_unittest.cc
@@ -45,7 +45,7 @@
 class DestructionIndicator {
  public:
   // Sets |*destructed| to true in destructor.
-  DestructionIndicator(bool* destructed) : destructed_(destructed) {
+  explicit DestructionIndicator(bool* destructed) : destructed_(destructed) {
     *destructed_ = false;
   }
 
diff --git a/tot/base/base64.cc b/tot/base/base64.cc
index b665b4c..380e528 100644
--- a/tot/base/base64.cc
+++ b/tot/base/base64.cc
@@ -81,7 +81,10 @@
     // in-place, but it violates the API contract that `output` is only modified
     // on success.
     std::string input_without_whitespace;
-    RemoveChars(input, kInfraAsciiWhitespace, &input_without_whitespace);
+    RemoveChars(input,
+                std::string_view(std::begin(kInfraAsciiWhitespace),
+                                 std::end(kInfraAsciiWhitespace)),
+                &input_without_whitespace);
     // This means that the required size to decode is at most what was needed
     // above, which means `decode_buf` will fit the decoded bytes at its current
     // size and we don't need to call `modp_b64_decode_len()` again.
diff --git a/tot/base/base64url.cc b/tot/base/base64url.cc
index 1b86d64..0926076 100644
--- a/tot/base/base64url.cc
+++ b/tot/base/base64url.cc
@@ -47,8 +47,9 @@
     Base64UrlDecodePolicy policy) {
   // Characters outside of the base64url alphabet are disallowed, which includes
   // the {+, /} characters found in the conventional base64 alphabet.
-  if (input.find_first_of(kBase64Chars) != std::string::npos)
+  if (input.find_first_of(kBase64Chars) != std::string::npos) {
     return std::nullopt;
+  }
 
   const size_t required_padding_characters = input.size() % 4;
   const bool needs_replacement =
@@ -57,16 +58,18 @@
   switch (policy) {
     case Base64UrlDecodePolicy::REQUIRE_PADDING:
       // Fail if the required padding is not included in |input|.
-      if (required_padding_characters > 0)
+      if (required_padding_characters > 0) {
         return std::nullopt;
+      }
       break;
     case Base64UrlDecodePolicy::IGNORE_PADDING:
       // Missing padding will be silently appended.
       break;
     case Base64UrlDecodePolicy::DISALLOW_PADDING:
       // Fail if padding characters are included in |input|.
-      if (input.find_first_of(kPaddingChar) != std::string::npos)
+      if (input.find_first_of(kPaddingChar) != std::string::npos) {
         return std::nullopt;
+      }
       break;
   }
 
diff --git a/tot/base/base64url_fuzzer.cc b/tot/base/base64url_fuzzer.cc
index cb65bb4..64ca03b 100644
--- a/tot/base/base64url_fuzzer.cc
+++ b/tot/base/base64url_fuzzer.cc
@@ -2,13 +2,14 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "base/base64url.h"
+
 #include <fuzzer/FuzzedDataProvider.h>
 #include <stdint.h>
 
 #include <string>
 #include <tuple>
 
-#include "base/base64url.h"
 #include "base/check.h"
 #include "base/check_op.h"
 
diff --git a/tot/base/base64url_unittest.cc b/tot/base/base64url_unittest.cc
index 0a9b12a..c2e7bc9 100644
--- a/tot/base/base64url_unittest.cc
+++ b/tot/base/base64url_unittest.cc
@@ -4,9 +4,9 @@
 
 #include "base/base64url.h"
 
+#include <algorithm>
 #include <string_view>
 
-#include "base/ranges/algorithm.h"
 #include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
@@ -120,8 +120,8 @@
 
 TEST(Base64UrlTest, DecodeRequirePaddingPolicy) {
   std::string output;
-  ASSERT_TRUE(Base64UrlDecode("aGVsbG8_d29ybGQ=",
-                              Base64UrlDecodePolicy::REQUIRE_PADDING, &output));
+  ASSERT_TRUE(Base64UrlDecode(
+      "aGVsbG8_d29ybGQ=", Base64UrlDecodePolicy::REQUIRE_PADDING, &output));
 
   EXPECT_EQ("hello?world", output);
 
@@ -146,8 +146,8 @@
   EXPECT_EQ("hello?world", output);
 
   // Including the padding is accepted as well.
-  ASSERT_TRUE(Base64UrlDecode("aGVsbG8_d29ybGQ=",
-                              Base64UrlDecodePolicy::IGNORE_PADDING, &output));
+  ASSERT_TRUE(Base64UrlDecode(
+      "aGVsbG8_d29ybGQ=", Base64UrlDecodePolicy::IGNORE_PADDING, &output));
 
   EXPECT_EQ("hello?world", output);
 }
@@ -159,7 +159,7 @@
   static constexpr uint8_t kExpected[] = {'1', '2', '3', '4'};
   std::optional<std::vector<uint8_t>> result =
       Base64UrlDecode("MTIzNA", Base64UrlDecodePolicy::DISALLOW_PADDING);
-  ASSERT_TRUE(ranges::equal(*result, kExpected));
+  ASSERT_TRUE(std::ranges::equal(*result, kExpected));
 }
 
 TEST(Base64UrlTest, DecodeDisallowPaddingPolicy) {
@@ -186,14 +186,14 @@
 TEST(Base64UrlTest, DecodeDisallowsPaddingOnly) {
   std::string output;
 
-  ASSERT_FALSE(Base64UrlDecode(
-      "=", Base64UrlDecodePolicy::IGNORE_PADDING, &output));
-  ASSERT_FALSE(Base64UrlDecode(
-      "==", Base64UrlDecodePolicy::IGNORE_PADDING, &output));
-  ASSERT_FALSE(Base64UrlDecode(
-      "===", Base64UrlDecodePolicy::IGNORE_PADDING, &output));
-  ASSERT_FALSE(Base64UrlDecode(
-      "====", Base64UrlDecodePolicy::IGNORE_PADDING, &output));
+  ASSERT_FALSE(
+      Base64UrlDecode("=", Base64UrlDecodePolicy::IGNORE_PADDING, &output));
+  ASSERT_FALSE(
+      Base64UrlDecode("==", Base64UrlDecodePolicy::IGNORE_PADDING, &output));
+  ASSERT_FALSE(
+      Base64UrlDecode("===", Base64UrlDecodePolicy::IGNORE_PADDING, &output));
+  ASSERT_FALSE(
+      Base64UrlDecode("====", Base64UrlDecodePolicy::IGNORE_PADDING, &output));
 }
 
 }  // namespace
diff --git a/tot/base/base_paths.cc b/tot/base/base_paths.cc
index 297486b..59ffbd2 100644
--- a/tot/base/base_paths.cc
+++ b/tot/base/base_paths.cc
@@ -59,14 +59,16 @@
 
   switch (key) {
     case DIR_EXE:
-      if (!PathService::Get(FILE_EXE, result))
+      if (!PathService::Get(FILE_EXE, result)) {
         return false;
+      }
       *result = result->DirName();
       return true;
 #if !BUILDFLAG(IS_FUCHSIA) && !BUILDFLAG(IS_IOS)
     case DIR_MODULE:
-      if (!PathService::Get(FILE_MODULE, result))
+      if (!PathService::Get(FILE_MODULE, result)) {
         return false;
+      }
       *result = result->DirName();
       return true;
     case DIR_ASSETS:
@@ -100,8 +102,9 @@
       test_data_path = test_data_path.Append(FILE_PATH_LITERAL("base"));
       test_data_path = test_data_path.Append(FILE_PATH_LITERAL("test"));
       test_data_path = test_data_path.Append(FILE_PATH_LITERAL("data"));
-      if (!PathExists(test_data_path))  // We don't want to create this.
+      if (!PathExists(test_data_path)) {  // We don't want to create this.
         return false;
+      }
       *result = test_data_path;
       return true;
     }
diff --git a/tot/base/base_paths_android.cc b/tot/base/base_paths_android.cc
index 482b5ba..a90f3a4 100644
--- a/tot/base/base_paths_android.cc
+++ b/tot/base/base_paths_android.cc
@@ -5,6 +5,8 @@
 // Defines base::PathProviderAndroid which replaces base::PathProviderPosix for
 // Android in base/path_service.cc.
 
+#include "base/base_paths.h"
+
 #include <limits.h>
 #include <unistd.h>
 
@@ -12,7 +14,6 @@
 
 #include "base/android/jni_android.h"
 #include "base/android/path_utils.h"
-#include "base/base_paths.h"
 #include "base/files/file_path.h"
 #include "base/files/file_util.h"
 #include "base/logging.h"
diff --git a/tot/base/base_paths_android.h b/tot/base/base_paths_android.h
index c4d293b..213c815 100644
--- a/tot/base/base_paths_android.h
+++ b/tot/base/base_paths_android.h
@@ -14,7 +14,7 @@
 enum {
   PATH_ANDROID_START = 300,
 
-  DIR_ANDROID_APP_DATA,  // Directory where to put Android app's data.
+  DIR_ANDROID_APP_DATA,          // Directory where to put Android app's data.
   DIR_ANDROID_EXTERNAL_STORAGE,  // Android external storage directory.
 
   PATH_ANDROID_END
diff --git a/tot/base/base_paths_ios.mm b/tot/base/base_paths_ios.mm
index 6ddcd38..0c4167e 100644
--- a/tot/base/base_paths_ios.mm
+++ b/tot/base/base_paths_ios.mm
@@ -5,11 +5,12 @@
 // Defines base::PathProviderIOS which replaces base::PathProviderPosix for iOS
 // in base/path_service.cc.
 
+#include "base/base_paths.h"
+
 #import <Foundation/Foundation.h>
 
 #include "base/apple/bundle_locations.h"
 #include "base/apple/foundation_util.h"
-#include "base/base_paths.h"
 #include "base/base_paths_apple.h"
 #include "base/files/file_path.h"
 #include "base/files/file_util.h"
diff --git a/tot/base/base_paths_mac.mm b/tot/base/base_paths_mac.mm
index 8f5c8bd..1dde038 100644
--- a/tot/base/base_paths_mac.mm
+++ b/tot/base/base_paths_mac.mm
@@ -5,11 +5,12 @@
 // Defines base::PathProviderMac which replaces base::PathProviderPosix for Mac
 // in base/path_service.cc.
 
+#include "base/base_paths.h"
+
 #import <Foundation/Foundation.h>
 
 #include "base/apple/bundle_locations.h"
 #include "base/apple/foundation_util.h"
-#include "base/base_paths.h"
 #include "base/base_paths_apple.h"
 #include "base/files/file_path.h"
 #include "base/files/file_util.h"
diff --git a/tot/base/base_paths_posix.cc b/tot/base/base_paths_posix.cc
index 8dadc5f..284e538 100644
--- a/tot/base/base_paths_posix.cc
+++ b/tot/base/base_paths_posix.cc
@@ -47,7 +47,7 @@
       *result = bin_dir;
       return true;
 #elif BUILDFLAG(IS_FREEBSD)
-      int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
+      int name[] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
       std::optional<std::string> bin_dir = StringSysctl(name, std::size(name));
       if (!bin_dir.has_value() || bin_dir.value().length() <= 1) {
         NOTREACHED() << "Unable to resolve path.";
@@ -64,10 +64,11 @@
 #elif BUILDFLAG(IS_OPENBSD) || BUILDFLAG(IS_AIX)
       // There is currently no way to get the executable path on OpenBSD
       char* cpath;
-      if ((cpath = getenv("CHROME_EXE_PATH")) != NULL)
+      if ((cpath = getenv("CHROME_EXE_PATH")) != NULL) {
         *result = FilePath(cpath);
-      else
+      } else {
         *result = FilePath("/usr/local/chrome/chrome");
+      }
       return true;
 #endif
     }
diff --git a/tot/base/base_paths_win.cc b/tot/base/base_paths_win.cc
index 197986a..8cb854a 100644
--- a/tot/base/base_paths_win.cc
+++ b/tot/base/base_paths_win.cc
@@ -35,15 +35,17 @@
   FilePath cur;
   switch (key) {
     case base::FILE_EXE:
-      if (GetModuleFileName(NULL, system_buffer, MAX_PATH) == 0)
+      if (GetModuleFileName(NULL, system_buffer, MAX_PATH) == 0) {
         return false;
+      }
       cur = FilePath(system_buffer);
       break;
     case base::FILE_MODULE: {
       // the resource containing module is assumed to be the one that
       // this code lives in, whether that's a dll or exe
-      if (GetModuleFileName(CURRENT_MODULE(), system_buffer, MAX_PATH) == 0)
+      if (GetModuleFileName(CURRENT_MODULE(), system_buffer, MAX_PATH) == 0) {
         return false;
+      }
       cur = FilePath(system_buffer);
       break;
     }
@@ -58,8 +60,9 @@
     case base::DIR_PROGRAM_FILESX86:
       if (win::OSInfo::GetArchitecture() != win::OSInfo::X86_ARCHITECTURE) {
         if (FAILED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILESX86, NULL,
-                                   SHGFP_TYPE_CURRENT, system_buffer)))
+                                   SHGFP_TYPE_CURRENT, system_buffer))) {
           return false;
+        }
         cur = FilePath(system_buffer);
         break;
       }
@@ -67,8 +70,9 @@
       [[fallthrough]];
     case base::DIR_PROGRAM_FILES:
       if (FAILED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL,
-                                 SHGFP_TYPE_CURRENT, system_buffer)))
+                                 SHGFP_TYPE_CURRENT, system_buffer))) {
         return false;
+      }
       cur = FilePath(system_buffer);
       break;
     case base::DIR_PROGRAM_FILES6432:
@@ -80,64 +84,74 @@
         // 32-bit process running in WOW64 sets ProgramW6432 environment
         // variable. See
         // https://msdn.microsoft.com/library/windows/desktop/aa384274.aspx.
-        if (!env->GetVar("ProgramW6432", &programfiles_w6432))
+        if (!env->GetVar("ProgramW6432", &programfiles_w6432)) {
           return false;
+        }
         // GetVar returns UTF8 - convert back to Wide.
         cur = FilePath(UTF8ToWide(programfiles_w6432));
         break;
       }
 #endif
       if (FAILED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL,
-                                 SHGFP_TYPE_CURRENT, system_buffer)))
+                                 SHGFP_TYPE_CURRENT, system_buffer))) {
         return false;
+      }
       cur = FilePath(system_buffer);
       break;
     case base::DIR_IE_INTERNET_CACHE:
       if (FAILED(SHGetFolderPath(NULL, CSIDL_INTERNET_CACHE, NULL,
-                                 SHGFP_TYPE_CURRENT, system_buffer)))
+                                 SHGFP_TYPE_CURRENT, system_buffer))) {
         return false;
+      }
       cur = FilePath(system_buffer);
       break;
     case base::DIR_COMMON_START_MENU:
       if (FAILED(SHGetFolderPath(NULL, CSIDL_COMMON_PROGRAMS, NULL,
-                                 SHGFP_TYPE_CURRENT, system_buffer)))
+                                 SHGFP_TYPE_CURRENT, system_buffer))) {
         return false;
+      }
       cur = FilePath(system_buffer);
       break;
     case base::DIR_START_MENU:
       if (FAILED(SHGetFolderPath(NULL, CSIDL_PROGRAMS, NULL, SHGFP_TYPE_CURRENT,
-                                 system_buffer)))
+                                 system_buffer))) {
         return false;
+      }
       cur = FilePath(system_buffer);
       break;
     case base::DIR_COMMON_STARTUP:
       if (FAILED(SHGetFolderPath(nullptr, CSIDL_COMMON_STARTUP, nullptr,
-                                 SHGFP_TYPE_CURRENT, system_buffer)))
+                                 SHGFP_TYPE_CURRENT, system_buffer))) {
         return false;
+      }
       cur = FilePath(system_buffer);
       break;
     case base::DIR_USER_STARTUP:
       if (FAILED(SHGetFolderPath(nullptr, CSIDL_STARTUP, nullptr,
-                                 SHGFP_TYPE_CURRENT, system_buffer)))
+                                 SHGFP_TYPE_CURRENT, system_buffer))) {
         return false;
+      }
       cur = FilePath(system_buffer);
       break;
     case base::DIR_ROAMING_APP_DATA:
       if (FAILED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT,
-                                 system_buffer)))
+                                 system_buffer))) {
         return false;
+      }
       cur = FilePath(system_buffer);
       break;
     case base::DIR_COMMON_APP_DATA:
       if (FAILED(SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL,
-                                 SHGFP_TYPE_CURRENT, system_buffer)))
+                                 SHGFP_TYPE_CURRENT, system_buffer))) {
         return false;
+      }
       cur = FilePath(system_buffer);
       break;
     case base::DIR_LOCAL_APP_DATA:
       if (FAILED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL,
-                                 SHGFP_TYPE_CURRENT, system_buffer)))
+                                 SHGFP_TYPE_CURRENT, system_buffer))) {
         return false;
+      }
       cur = FilePath(system_buffer);
       break;
     case base::DIR_SRC_TEST_DATA_ROOT: {
@@ -151,8 +165,9 @@
     case base::DIR_APP_SHORTCUTS: {
       base::win::ScopedCoMem<wchar_t> path_buf;
       if (FAILED(SHGetKnownFolderPath(FOLDERID_ApplicationShortcuts, 0, NULL,
-                                      &path_buf)))
+                                      &path_buf))) {
         return false;
+      }
 
       cur = FilePath(path_buf.get());
       break;
@@ -172,8 +187,9 @@
       cur = FilePath(system_buffer);
       break;
     case base::DIR_USER_QUICK_LAUNCH:
-      if (!PathService::Get(base::DIR_ROAMING_APP_DATA, &cur))
+      if (!PathService::Get(base::DIR_ROAMING_APP_DATA, &cur)) {
         return false;
+      }
       // According to various sources, appending
       // "Microsoft\Internet Explorer\Quick Launch" to %appdata% is the only
       // reliable way to get the quick launch folder across all versions of
@@ -185,15 +201,17 @@
                 .Append(FILE_PATH_LITERAL("Quick Launch"));
       break;
     case base::DIR_TASKBAR_PINS: {
-      if (!PathService::Get(base::DIR_USER_QUICK_LAUNCH, &cur))
+      if (!PathService::Get(base::DIR_USER_QUICK_LAUNCH, &cur)) {
         return false;
+      }
       cur = cur.Append(FILE_PATH_LITERAL("User Pinned"))
                 .Append(FILE_PATH_LITERAL("TaskBar"));
       break;
     }
     case base::DIR_IMPLICIT_APP_SHORTCUTS:
-      if (!PathService::Get(base::DIR_USER_QUICK_LAUNCH, &cur))
+      if (!PathService::Get(base::DIR_USER_QUICK_LAUNCH, &cur)) {
         return false;
+      }
       cur = cur.Append(FILE_PATH_LITERAL("User Pinned"))
                 .Append(FILE_PATH_LITERAL("ImplicitAppShortcuts"));
       break;
@@ -220,6 +238,17 @@
         return false;
       }
       break;
+    case base::DIR_ONE_DRIVE: {
+      base::win::ScopedCoMem<wchar_t> path_buf;
+      // FOLDERID_OneDrive points on the user OneDrive folder. The default path
+      // is %USERPROFILE%\OneDrive. It is formerly known as FOLDERID_SkyDrive.
+      if (FAILED(SHGetKnownFolderPath(FOLDERID_OneDrive, 0, NULL, &path_buf))) {
+        return false;
+      }
+
+      cur = FilePath(path_buf.get());
+      break;
+    }
     default:
       return false;
   }
diff --git a/tot/base/base_paths_win.h b/tot/base/base_paths_win.h
index 521424d..413105f 100644
--- a/tot/base/base_paths_win.h
+++ b/tot/base/base_paths_win.h
@@ -57,6 +57,7 @@
   DIR_WINDOWS_FONTS,           // Usually C:\Windows\Fonts.
   DIR_SYSTEM_TEMP,             // %SystemRoot%\SystemTemp or %ProgramFiles%;
                                // only for admin processes.
+  DIR_ONE_DRIVE,               // The synced personal OneDrive directory.
   PATH_WIN_END
 };
 
diff --git a/tot/base/base_switches.cc b/tot/base/base_switches.cc
index 37a846d..2c26484 100644
--- a/tot/base/base_switches.cc
+++ b/tot/base/base_switches.cc
@@ -3,8 +3,8 @@
 // found in the LICENSE file.
 
 #include "base/base_switches.h"
+
 #include "build/build_config.h"
-#include "build/chromeos_buildflags.h"
 
 namespace switches {
 
@@ -12,7 +12,7 @@
 const char kDisableBestEffortTasks[] = "disable-best-effort-tasks";
 
 // Disables the crash reporting.
-const char kDisableBreakpad[]               = "disable-breakpad";
+const char kDisableBreakpad[] = "disable-breakpad";
 
 // Comma-separated list of feature names to disable. See also kEnableFeatures.
 const char kDisableFeatures[] = "disable-features";
@@ -23,13 +23,13 @@
 // Indicates that crash reporting should be enabled. On platforms where helper
 // processes cannot access to files needed to make this decision, this flag is
 // generated internally.
-const char kEnableCrashReporter[]           = "enable-crash-reporter";
+const char kEnableCrashReporter[] = "enable-crash-reporter";
 
 // Comma-separated list of feature names to enable. See also kDisableFeatures.
 const char kEnableFeatures[] = "enable-features";
 
 // Force low-end device mode when set.
-const char kEnableLowEndDeviceMode[]        = "enable-low-end-device-mode";
+const char kEnableLowEndDeviceMode[] = "enable-low-end-device-mode";
 
 // Enable the use of background thread priorities for background tasks in the
 // ThreadPool even on systems where it is disabled by default, e.g. due to
@@ -54,7 +54,7 @@
 // also be used by the browser process to send the list of trials to a
 // non-browser process, using the same format. See
 // FieldTrialList::CreateTrialsFromString() in field_trial.h for details.
-const char kForceFieldTrials[]              = "force-fieldtrials";
+const char kForceFieldTrials[] = "force-fieldtrials";
 
 // Generates full memory crash dump.
 const char kFullMemoryCrashReport[] = "full-memory-crash-report";
@@ -71,7 +71,7 @@
 const char kMetricsSharedMemoryHandle[] = "metrics-shmem-handle";
 
 // Suppresses all error dialogs when present.
-const char kNoErrorDialogs[]                = "noerrdialogs";
+const char kNoErrorDialogs[] = "noerrdialogs";
 
 // Starts the sampling based profiler for the browser process at startup. This
 // will only work if chrome has been built with the gn arg enable_profiling =
@@ -129,7 +129,7 @@
 const char kDisableHighResTimer[] = "disable-highres-timer";
 
 // Disables the USB keyboard detection for blocking the OSK on Windows.
-const char kDisableUsbKeyboardDetect[]      = "disable-usb-keyboard-detect";
+const char kDisableUsbKeyboardDetect[] = "disable-usb-keyboard-detect";
 #endif
 
 #if BUILDFLAG(IS_LINUX)
@@ -148,6 +148,11 @@
 #endif
 
 #if BUILDFLAG(IS_ANDROID)
+// For testing, do not initialize child service process but also do not exit
+// (until requested by browser).
+const char kAndroidSkipChildServiceInitForTesting[] =
+    "android-skip-child-service-init-for-testing";
+
 // Default country code to be used for search engine localization.
 const char kDefaultCountryCodeAtInstall[] = "default-country-code";
 
diff --git a/tot/base/base_switches.h b/tot/base/base_switches.h
index a233ef2..0ceba5f 100644
--- a/tot/base/base_switches.h
+++ b/tot/base/base_switches.h
@@ -8,7 +8,6 @@
 #define BASE_BASE_SWITCHES_H_
 
 #include "build/build_config.h"
-#include "build/chromeos_buildflags.h"
 
 namespace switches {
 
@@ -50,6 +49,7 @@
 #endif
 
 #if BUILDFLAG(IS_ANDROID)
+extern const char kAndroidSkipChildServiceInitForTesting[];
 extern const char kDefaultCountryCodeAtInstall[];
 extern const char kEnableIdleTracing[];
 extern const char kHostPackageName[];
diff --git a/tot/base/big_endian_perftest.cc b/tot/base/big_endian_perftest.cc
index 2272366..8c68c03 100644
--- a/tot/base/big_endian_perftest.cc
+++ b/tot/base/big_endian_perftest.cc
@@ -41,17 +41,14 @@
   auto value = T{0};
   for (auto _ : state) {
     if constexpr (sizeof(T) == 1) {
-      buffer.subspan(offset).first<sizeof(T)>().copy_from(U8ToBigEndian(value));
+      buffer.subspan(offset).copy_prefix_from(U8ToBigEndian(value));
     } else if constexpr (sizeof(T) == 2) {
-      buffer.subspan(offset).first<sizeof(T)>().copy_from(
-          U16ToBigEndian(value));
+      buffer.subspan(offset).copy_prefix_from(U16ToBigEndian(value));
     } else if constexpr (sizeof(T) == 4) {
-      buffer.subspan(offset).first<sizeof(T)>().copy_from(
-          U32ToBigEndian(value));
+      buffer.subspan(offset).copy_prefix_from(U32ToBigEndian(value));
     } else {
       static_assert(sizeof(T) == 8);
-      buffer.subspan(offset).first<sizeof(T)>().copy_from(
-          U64ToBigEndian(value));
+      buffer.subspan(offset).copy_prefix_from(U64ToBigEndian(value));
     }
     offset += sizeof(T);
     static_assert(kSize % sizeof(T) == 0u);
diff --git a/tot/base/bit_cast_unittest.cc b/tot/base/bit_cast_unittest.cc
index 28cbd48..9805fcc 100644
--- a/tot/base/bit_cast_unittest.cc
+++ b/tot/base/bit_cast_unittest.cc
@@ -2,7 +2,6 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-
 #include "base/bit_cast.h"
 
 #include "testing/gtest/include/gtest/gtest.h"
@@ -22,7 +21,7 @@
 };
 
 TEST(BitCastTest, StructureInt) {
-  A a = { 1 };
+  A a = {1};
   int b = bit_cast<int>(a);
   EXPECT_EQ(1, b);
 }
diff --git a/tot/base/bits.h b/tot/base/bits.h
index f7d496d..5f93183 100644
--- a/tot/base/bits.h
+++ b/tot/base/bits.h
@@ -12,6 +12,7 @@
 
 #include <bit>
 #include <concepts>
+#include <type_traits>
 
 #include "base/check.h"
 
@@ -38,22 +39,6 @@
 concept SignedIntegerDeprecatedDoNotUse =
     std::integral<T> && !UnsignedInteger<T>;
 
-// Returns true iff |value| is a power of 2. DEPRECATED; use
-// std::has_single_bit() instead.
-//
-// TODO(crbug.com/40256225): Switch uses and remove.
-template <typename T>
-  requires SignedIntegerDeprecatedDoNotUse<T>
-constexpr bool IsPowerOfTwoDeprecatedDoNotUse(T value) {
-  // From "Hacker's Delight": Section 2.1 Manipulating Rightmost Bits.
-  //
-  // Only positive integers with a single bit set are powers of two. If only one
-  // bit is set in x (e.g. 0b00000100000000) then |x-1| will have that bit set
-  // to zero and all bits to its right set to 1 (e.g. 0b00000011111111). Hence
-  // |x & (x-1)| is 0 iff x is a power of two.
-  return value > 0 && (value & (value - 1)) == 0;
-}
-
 // Round down |size| to a multiple of alignment, which must be a power of two.
 template <typename T>
   requires UnsignedInteger<T>
@@ -67,10 +52,10 @@
 //
 // TODO(crbug.com/40256225): Switch uses and remove.
 template <typename T>
-  requires SignedIntegerDeprecatedDoNotUse<T>
-inline constexpr T AlignDownDeprecatedDoNotUse(T size, T alignment) {
-  DCHECK(IsPowerOfTwoDeprecatedDoNotUse(alignment));
-  return size & ~(alignment - 1);
+inline constexpr auto AlignDownDeprecatedDoNotUse(T size, T alignment) {
+  using U = std::make_unsigned_t<T>;
+  DCHECK(std::has_single_bit(static_cast<U>(alignment)));
+  return static_cast<U>(size) & ~static_cast<U>(alignment - 1);
 }
 
 // Move |ptr| back to the previous multiple of alignment, which must be a power
@@ -97,8 +82,9 @@
 template <typename T>
   requires SignedIntegerDeprecatedDoNotUse<T>
 inline constexpr T AlignUpDeprecatedDoNotUse(T size, T alignment) {
-  DCHECK(IsPowerOfTwoDeprecatedDoNotUse(alignment));
-  return (size + alignment - 1) & ~(alignment - 1);
+  using U = std::make_unsigned_t<T>;
+  DCHECK(std::has_single_bit(static_cast<U>(alignment)));
+  return static_cast<U>(size + alignment - 1) & ~static_cast<U>(alignment - 1);
 }
 
 // Advance |ptr| to the next multiple of alignment, which must be a power of
diff --git a/tot/base/bits_unittest.cc b/tot/base/bits_unittest.cc
index 47ba93c..6464844 100644
--- a/tot/base/bits_unittest.cc
+++ b/tot/base/bits_unittest.cc
@@ -117,19 +117,6 @@
             AlignDown(reinterpret_cast<uint8_t*>(1), kUintPtrTMax / 2 + 1));
 }
 
-TEST(BitsTest, PowerOfTwoDeprecatedDoNotUse) {
-  EXPECT_FALSE(IsPowerOfTwoDeprecatedDoNotUse(-1));
-  // Signed 64 bit cases.
-  for (uint32_t i = 2; i < 63; i++) {
-    const int64_t val = int64_t{1} << i;
-    EXPECT_FALSE(IsPowerOfTwoDeprecatedDoNotUse(val - 1));
-    EXPECT_TRUE(IsPowerOfTwoDeprecatedDoNotUse(val));
-    EXPECT_FALSE(IsPowerOfTwoDeprecatedDoNotUse(val + 1));
-  }
-  // Signed integers with only the last bit set are negative, not powers of two.
-  EXPECT_FALSE(IsPowerOfTwoDeprecatedDoNotUse(int64_t{1} << 63));
-}
-
 TEST(BitsTest, LeftMostBit) {
   // Construction of a signed type from an unsigned one of the same width
   // preserves all bits. Explicitly confirming this behavior here to illustrate
diff --git a/tot/base/callback_list.cc b/tot/base/callback_list.cc
index a50252e..4eae2ca 100644
--- a/tot/base/callback_list.cc
+++ b/tot/base/callback_list.cc
@@ -32,8 +32,9 @@
 }
 
 void CallbackListSubscription::Run() {
-  if (closure_)
+  if (closure_) {
     std::move(closure_).Run();
+  }
 }
 
 }  // namespace base
diff --git a/tot/base/callback_list.h b/tot/base/callback_list.h
index 33ceb44..b1204f0 100644
--- a/tot/base/callback_list.h
+++ b/tot/base/callback_list.h
@@ -5,6 +5,7 @@
 #ifndef BASE_CALLBACK_LIST_H_
 #define BASE_CALLBACK_LIST_H_
 
+#include <algorithm>
 #include <list>
 #include <memory>
 #include <utility>
@@ -15,7 +16,6 @@
 #include "base/functional/bind.h"
 #include "base/functional/callback.h"
 #include "base/memory/weak_ptr.h"
-#include "base/ranges/algorithm.h"
 #include "base/types/is_instantiation.h"
 
 // OVERVIEW:
@@ -174,7 +174,7 @@
   // Returns whether the list of registered callbacks is empty (from an external
   // perspective -- meaning no remaining callbacks are live).
   bool empty() const {
-    return ranges::all_of(
+    return std::ranges::all_of(
         callbacks_, [](const auto& callback) { return callback.is_null(); });
   }
 
@@ -196,8 +196,9 @@
   // the reentrant Notify() call.
   template <typename... RunArgs>
   void Notify(RunArgs&&... args) {
-    if (empty())
+    if (empty()) {
       return;  // Nothing to do.
+    }
 
     {
       AutoReset<bool> iterating(&iterating_, true);
@@ -211,18 +212,20 @@
         });
       };
       for (auto it = next_valid(callbacks_.begin()); it != callbacks_.end();
-           it = next_valid(it))
+           it = next_valid(it)) {
         // NOTE: Intentionally does not call std::forward<RunArgs>(args)...,
         // since that would allow move-only arguments.
         static_cast<CallbackListImpl*>(this)->RunCallback(it++, args...);
+      }
     }
 
     // Re-entrant invocations shouldn't prune anything from the list. This can
     // invalidate iterators from underneath higher call frames. It's safe to
     // simply do nothing, since the outermost frame will continue through here
     // and prune all null callbacks below.
-    if (iterating_)
+    if (iterating_) {
       return;
+    }
 
     // Any null callbacks remaining in the list were canceled due to
     // Subscription destruction during iteration, and can safely be erased now.
@@ -250,8 +253,9 @@
  private:
   // Cancels the callback pointed to by |it|, which is guaranteed to be valid.
   void CancelCallback(const typename Callbacks::iterator& it) {
-    if (static_cast<CallbackListImpl*>(this)->CancelNullCallback(it))
+    if (static_cast<CallbackListImpl*>(this)->CancelNullCallback(it)) {
       return;
+    }
 
     if (iterating_) {
       // Calling erase() here is unsafe, since the loop in Notify() may be
@@ -261,8 +265,9 @@
       it->Reset();
     } else {
       callbacks_.erase(it);
-      if (removal_callback_)
+      if (removal_callback_) {
         removal_callback_.Run();  // May delete |this|!
+      }
     }
   }
 
diff --git a/tot/base/callback_list_unittest.cc b/tot/base/callback_list_unittest.cc
index 52fffc5..ffc08d2 100644
--- a/tot/base/callback_list_unittest.cc
+++ b/tot/base/callback_list_unittest.cc
@@ -98,7 +98,7 @@
   void AddFiveParam(int a, int b, int c, int d, int e) {
     value_ = a + b + c + d + e;
   }
-  void AddSixParam(int a, int b, int c, int d, int e , int f) {
+  void AddSixParam(int a, int b, int c, int d, int e, int f) {
     value_ = a + b + c + d + e + f;
   }
 
diff --git a/tot/base/cancelable_callback.h b/tot/base/cancelable_callback.h
index 6a4235f..4b3818e 100644
--- a/tot/base/cancelable_callback.h
+++ b/tot/base/cancelable_callback.h
@@ -81,9 +81,7 @@
   }
 
   // Returns true if the wrapped callback has been cancelled.
-  bool IsCancelled() const {
-    return callback_.is_null();
-  }
+  bool IsCancelled() const { return callback_.is_null(); }
 
   // Sets |callback| as the closure that may be cancelled. |callback| may not
   // be null. Outstanding and any previously wrapped callbacks are cancelled.
@@ -101,8 +99,9 @@
   // e.g. via PostTaskAndReply[WithResult](), to post tasks back on the original
   // bound sequence.
   CallbackType callback() const {
-    if (!callback_)
+    if (!callback_) {
       return CallbackType();
+    }
     CallbackType forwarder;
     MakeForwarder(&forwarder);
     return forwarder;
diff --git a/tot/base/cancelable_callback_unittest.cc b/tot/base/cancelable_callback_unittest.cc
index 6b91035..9b92d9a 100644
--- a/tot/base/cancelable_callback_unittest.cc
+++ b/tot/base/cancelable_callback_unittest.cc
@@ -25,8 +25,12 @@
   ~TestRefCounted() = default;
 };
 
-void Increment(int* count) { (*count)++; }
-void IncrementBy(int* count, int n) { (*count) += n; }
+void Increment(int* count) {
+  (*count)++;
+}
+void IncrementBy(int* count, int n) {
+  (*count) += n;
+}
 void RefCountedParam(const scoped_refptr<TestRefCounted>& ref_counted) {}
 
 void OnMoveOnlyReceived(int* value, std::unique_ptr<int> result) {
diff --git a/tot/base/check.cc b/tot/base/check.cc
index 4c30de5..49e97f1 100644
--- a/tot/base/check.cc
+++ b/tot/base/check.cc
@@ -2,6 +2,11 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#ifdef UNSAFE_BUFFERS_BUILD
+// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
+#pragma allow_unsafe_libc_calls
+#endif
+
 #include "base/check.h"
 
 #include <optional>
@@ -164,7 +169,7 @@
 
 class DCheckLogMessage : public LogMessage {
  public:
-  DCheckLogMessage(const base::Location& location)
+  explicit DCheckLogMessage(const base::Location& location)
       : LogMessage(location.file_name(),
                    location.line_number(),
                    LOGGING_DCHECK),
@@ -238,38 +243,42 @@
 
 }  // namespace
 
+CheckError::CheckError(LogMessage* log_message) : log_message_(log_message) {}
+
 CheckError CheckError::Check(const char* condition,
                              base::NotFatalUntil fatal_milestone,
                              const base::Location& location) {
   auto* const log_message = new CheckLogMessage(
       location, GetCheckSeverity(fatal_milestone), fatal_milestone);
+  // TODO(pbos): Make this output CHECK instead of Check.
   log_message->stream() << "Check failed: " << condition << ". ";
   return CheckError(log_message);
 }
 
-CheckError CheckError::CheckOp(char* log_message_str,
-                               base::NotFatalUntil fatal_milestone,
-                               const base::Location& location) {
+LogMessage* CheckError::CheckOp(char* log_message_str,
+                                base::NotFatalUntil fatal_milestone,
+                                const base::Location& location) {
   auto* const log_message = new CheckLogMessage(
       location, GetCheckSeverity(fatal_milestone), fatal_milestone);
-  log_message->stream() << log_message_str;
+  // TODO(pbos): Make this output CHECK instead of Check.
+  log_message->stream() << "Check failed: " << log_message_str;
   free(log_message_str);
-  return CheckError(log_message);
+  return log_message;
 }
 
 CheckError CheckError::DCheck(const char* condition,
                               const base::Location& location) {
   auto* const log_message = new DCheckLogMessage(location);
-  log_message->stream() << "Check failed: " << condition << ". ";
+  log_message->stream() << "DCHECK failed: " << condition << ". ";
   return CheckError(log_message);
 }
 
-CheckError CheckError::DCheckOp(char* log_message_str,
-                                const base::Location& location) {
+LogMessage* CheckError::DCheckOp(char* log_message_str,
+                                 const base::Location& location) {
   auto* const log_message = new DCheckLogMessage(location);
-  log_message->stream() << log_message_str;
+  log_message->stream() << "DCHECK failed: " << log_message_str;
   free(log_message_str);
-  return CheckError(log_message);
+  return log_message;
 }
 
 CheckError CheckError::DumpWillBeCheck(const char* condition,
@@ -277,18 +286,20 @@
   auto* const log_message =
       new CheckLogMessage(location, GetDumpSeverity(),
                           base::NotFatalUntil::NoSpecifiedMilestoneInternal);
+  // TODO(pbos): Make this output CHECK instead of Check.
   log_message->stream() << "Check failed: " << condition << ". ";
   return CheckError(log_message);
 }
 
-CheckError CheckError::DumpWillBeCheckOp(char* log_message_str,
-                                         const base::Location& location) {
+LogMessage* CheckError::DumpWillBeCheckOp(char* log_message_str,
+                                          const base::Location& location) {
   auto* const log_message =
       new CheckLogMessage(location, GetDumpSeverity(),
                           base::NotFatalUntil::NoSpecifiedMilestoneInternal);
-  log_message->stream() << log_message_str;
+  // TODO(pbos): Make this output CHECK instead of Check.
+  log_message->stream() << "Check failed: " << log_message_str;
   free(log_message_str);
-  return CheckError(log_message);
+  return log_message;
 }
 
 CheckError CheckError::DPCheck(const char* condition,
@@ -299,7 +310,7 @@
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
   auto* const log_message = new DCheckErrnoLogMessage(location, err_code);
 #endif
-  log_message->stream() << "Check failed: " << condition << ". ";
+  log_message->stream() << "DCHECK failed: " << condition << ". ";
   return CheckError(log_message);
 }
 
@@ -307,6 +318,7 @@
                                       const base::Location& location) {
   auto* const log_message = new LogMessage(
       location.file_name(), location.line_number(), LOGGING_ERROR);
+  // TODO(pbos): Make this output NOTIMPLEMENTED instead of Not implemented.
   log_message->stream() << "Not implemented reached in " << function;
   return CheckError(log_message);
 }
@@ -335,8 +347,6 @@
   }
 }
 
-CheckError::CheckError(LogMessage* log_message) : log_message_(log_message) {}
-
 // Note: This function ends up in crash stack traces. If its full name changes,
 // the crash server's magic signature logic needs to be updated. See
 // cl/306632920.
@@ -355,18 +365,20 @@
   auto* const log_message =
       new CheckLogMessage(location, LOGGING_FATAL,
                           base::NotFatalUntil::NoSpecifiedMilestoneInternal);
+  // TODO(pbos): Make this output CHECK instead of Check.
   log_message->stream() << "Check failed: " << condition << ". ";
   return CheckNoreturnError(log_message);
 }
 
-CheckNoreturnError CheckNoreturnError::CheckOp(char* log_message_str,
-                                               const base::Location& location) {
+LogMessage* CheckNoreturnError::CheckOp(char* log_message_str,
+                                        const base::Location& location) {
   auto* const log_message =
       new CheckLogMessage(location, LOGGING_FATAL,
                           base::NotFatalUntil::NoSpecifiedMilestoneInternal);
-  log_message->stream() << log_message_str;
+  // TODO(pbos): Make this output CHECK instead of Check.
+  log_message->stream() << "Check failed: " << log_message_str;
   free(log_message_str);
-  return CheckNoreturnError(log_message);
+  return log_message;
 }
 
 CheckNoreturnError CheckNoreturnError::PCheck(const char* condition,
@@ -379,6 +391,7 @@
   auto* const log_message = new ErrnoLogMessage(
       location.file_name(), location.line_number(), LOGGING_FATAL, err_code);
 #endif
+  // TODO(pbos): Make this output CHECK instead of Check.
   log_message->stream() << "Check failed: " << condition << ". ";
   return CheckNoreturnError(log_message);
 }
@@ -392,8 +405,7 @@
   auto* const log_message = new NotReachedLogMessage(
       location, GetCheckSeverity(fatal_milestone), fatal_milestone);
 
-  // TODO(pbos): Consider a better message for NotReached(), this is here to
-  // match existing behavior + test expectations.
+  // TODO(pbos): Make this output "NOTREACHED hit." like the other NOTREACHEDs.
   log_message->stream() << "Check failed: false. ";
   return NotReachedError(log_message);
 }
diff --git a/tot/base/check.h b/tot/base/check.h
index aaf8662..96f17b9 100644
--- a/tot/base/check.h
+++ b/tot/base/check.h
@@ -75,42 +75,59 @@
 // Class used for raising a check error upon destruction.
 class BASE_EXPORT CheckError {
  public:
-  static CheckError Check(
-      const char* condition,
-      base::NotFatalUntil fatal_milestone,
-      const base::Location& location = base::Location::Current());
+  // Takes ownership of `log_message`.
+  explicit CheckError(LogMessage* log_message);
+
+  // All instances that take a base::Location should use
+  // base::Location::CurrentWithoutFunctionName() by default since we
+  // immediately pass file_name() and line_number() to LogMessage's constructor
+  // and discard the function_name() anyways. This saves ~23k on the Android
+  // size bots (as of 2024-12-17) but that's the official build that barely uses
+  // these for CHECKs. The size gains are believed to be significantly larger on
+  // developer builds and official+DCHECK where all CHECK failures generate
+  // logs.
+
+  // TODO(pbos): Make all static methods that currently return some version of
+  // CheckError return LogMessage*.
+  static CheckError Check(const char* condition,
+                          base::NotFatalUntil fatal_milestone,
+                          const base::Location& location =
+                              base::Location::CurrentWithoutFunctionName());
   // Takes ownership over (free()s after using) `log_message_str`, for use with
   // CHECK_op macros.
-  static CheckError CheckOp(
-      char* log_message_str,
-      base::NotFatalUntil fatal_milestone,
-      const base::Location& location = base::Location::Current());
+  static LogMessage* CheckOp(char* log_message_str,
+                             base::NotFatalUntil fatal_milestone,
+                             const base::Location& location =
+                                 base::Location::CurrentWithoutFunctionName());
 
-  static CheckError DCheck(
-      const char* condition,
-      const base::Location& location = base::Location::Current());
+  static CheckError DCheck(const char* condition,
+                           const base::Location& location =
+                               base::Location::CurrentWithoutFunctionName());
   // Takes ownership over (free()s after using) `log_message_str`, for use with
   // DCHECK_op macros.
-  static CheckError DCheckOp(
-      char* log_message_str,
-      const base::Location& location = base::Location::Current());
+  static LogMessage* DCheckOp(char* log_message_str,
+                              const base::Location& location =
+                                  base::Location::CurrentWithoutFunctionName());
 
   static CheckError DumpWillBeCheck(
       const char* condition,
-      const base::Location& location = base::Location::Current());
+      const base::Location& location =
+          base::Location::CurrentWithoutFunctionName());
   // Takes ownership over (free()s after using) `log_message_str`, for use with
   // DUMP_WILL_BE_CHECK_op macros.
-  static CheckError DumpWillBeCheckOp(
+  static LogMessage* DumpWillBeCheckOp(
       char* log_message_str,
-      const base::Location& location = base::Location::Current());
+      const base::Location& location =
+          base::Location::CurrentWithoutFunctionName());
 
-  static CheckError DPCheck(
-      const char* condition,
-      const base::Location& location = base::Location::Current());
+  static CheckError DPCheck(const char* condition,
+                            const base::Location& location =
+                                base::Location::CurrentWithoutFunctionName());
 
   static CheckError NotImplemented(
       const char* function,
-      const base::Location& location = base::Location::Current());
+      const base::Location& location =
+          base::Location::CurrentWithoutFunctionName());
 
   // Stream for adding optional details to the error message.
   std::ostream& stream();
@@ -123,14 +140,12 @@
   CheckError& operator=(const CheckError&) = delete;
 
   template <typename T>
-  std::ostream& operator<<(T&& streamed_type) {
-    return stream() << streamed_type;
+  CheckError& operator<<(T&& streamed_type) {
+    stream() << streamed_type;
+    return *this;
   }
 
  protected:
-  // Takes ownership of `log_message`.
-  explicit CheckError(LogMessage* log_message);
-
   std::unique_ptr<LogMessage> log_message_;
 };
 
@@ -141,18 +156,21 @@
 
   static CheckNoreturnError Check(
       const char* condition,
-      const base::Location& location = base::Location::Current());
+      const base::Location& location =
+          base::Location::CurrentWithoutFunctionName());
   // Takes ownership over (free()s after using) `log_message_str`, for use with
   // CHECK_op macros.
-  static CheckNoreturnError CheckOp(
-      char* log_message_str,
-      const base::Location& location = base::Location::Current());
+  static LogMessage* CheckOp(char* log_message_str,
+                             const base::Location& location =
+                                 base::Location::CurrentWithoutFunctionName());
 
   static CheckNoreturnError PCheck(
       const char* condition,
-      const base::Location& location = base::Location::Current());
+      const base::Location& location =
+          base::Location::CurrentWithoutFunctionName());
   static CheckNoreturnError PCheck(
-      const base::Location& location = base::Location::Current());
+      const base::Location& location =
+          base::Location::CurrentWithoutFunctionName());
 
  private:
   using CheckError::CheckError;
@@ -163,10 +181,12 @@
  public:
   static NotReachedError NotReached(
       base::NotFatalUntil fatal_milestone,
-      const base::Location& location = base::Location::Current());
+      const base::Location& location =
+          base::Location::CurrentWithoutFunctionName());
 
   static NotReachedError DumpWillBeNotReached(
-      const base::Location& location = base::Location::Current());
+      const base::Location& location =
+          base::Location::CurrentWithoutFunctionName());
 
   NOMERGE NOINLINE NOT_TAIL_CALLED ~NotReachedError();
 
@@ -178,7 +198,8 @@
 class BASE_EXPORT NotReachedNoreturnError : public CheckError {
  public:
   explicit NotReachedNoreturnError(
-      const base::Location& location = base::Location::Current());
+      const base::Location& location =
+          base::Location::CurrentWithoutFunctionName());
 
   [[noreturn]] NOMERGE NOINLINE NOT_TAIL_CALLED ~NotReachedNoreturnError();
 };
@@ -197,6 +218,9 @@
 // The weird ternary is to still generate an "is not contextually convertible to
 // 'bool' when provided weird parameters (regardless of ANALYZER_ASSUME_TRUE's
 // implementation). See base/check_nocompile.nc.
+//
+// The lambda is here to here permit the compiler to out-of-line much of the
+// CHECK-failure path and optimize better for the fast path.
 #define LOGGING_CHECK_FUNCTION_IMPL(check_stream, condition) \
   switch (0)                                                 \
   case 0:                                                    \
@@ -204,7 +228,7 @@
     if (ANALYZER_ASSUME_TRUE((condition) ? true : false))    \
       [[likely]];                                            \
     else                                                     \
-      (check_stream)
+      [&]() { return (check_stream); }()
 
 // A helper macro like LOGGING_CHECK_FUNCTION_IMPL above but discarding any
 // log-stream parameters rather than evaluate them on failure.
diff --git a/tot/base/check_deref.h b/tot/base/check_deref.h
index a545ce8..fe881b2 100644
--- a/tot/base/check_deref.h
+++ b/tot/base/check_deref.h
@@ -28,23 +28,22 @@
 //
 //   MyType& type_ref = CHECK_DEREF(your_wrapped_pointer.get());
 //
-#define CHECK_DEREF(ptr) \
-  ::logging::CheckDeref(ptr, #ptr " != nullptr", __FILE__, __LINE__)
+#define CHECK_DEREF(ptr) ::logging::CheckDeref(ptr, #ptr " != nullptr")
 
 template <typename T>
-[[nodiscard]] T& CheckDeref(T* ptr,
-                            const char* message,
-                            const char* file,
-                            int line) {
+[[nodiscard]] T& CheckDeref(
+    T* ptr,
+    const char* message,
+    const base::Location& location = base::Location::Current()) {
   // Note: we can't just call `CHECK_NE(ptr, nullptr)` here, as that would
   // cause the error to be reported from this header, and we want the error
   // to be reported at the file and line of the caller.
   if (ptr == nullptr) [[unlikely]] {
-#if !CHECK_WILL_STREAM()
-    CheckFailure();
+#if CHECK_WILL_STREAM()
+    // `CheckNoreturnError` will die with a fatal error in its destructor.
+    CheckNoreturnError::Check(message, location);
 #else
-    // `LogMessage` will die with a fatal error in its destructor.
-    LogMessage(file, line, message);
+    CheckFailure();
 #endif  // !CHECK_WILL_STREAM()
   }
   return *ptr;
diff --git a/tot/base/check_op.cc b/tot/base/check_op.cc
index 1fb12c7..c7fbcc2 100644
--- a/tot/base/check_op.cc
+++ b/tot/base/check_op.cc
@@ -2,6 +2,11 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#ifdef UNSAFE_BUFFERS_BUILD
+// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
+#pragma allow_unsafe_libc_calls
+#endif
+
 #include "base/check_op.h"
 
 #include <string.h>
@@ -101,8 +106,7 @@
                                     char* v1_str,
                                     char* v2_str) {
   std::stringstream ss;
-  ss << "Check failed: " << expr_str << " (" << v1_str << " vs. " << v2_str
-     << ")";
+  ss << expr_str << " (" << v1_str << " vs. " << v2_str << ")";
   free(v1_str);
   free(v2_str);
   return strdup(ss.str().c_str());
diff --git a/tot/base/check_op.h b/tot/base/check_op.h
index 76c3d7f..f49470a 100644
--- a/tot/base/check_op.h
+++ b/tot/base/check_op.h
@@ -12,11 +12,12 @@
 
 #include "base/base_export.h"
 #include "base/check.h"
+#include "base/compiler_specific.h"
 #include "base/dcheck_is_on.h"
 #include "base/memory/raw_ptr_exclusion.h"
-#include "base/strings/to_string.h"
 #include "base/types/is_arc_pointer.h"
 #include "base/types/supports_ostream_operator.h"
+#include "base/types/supports_to_string.h"
 
 // This header defines the (DP)CHECK_EQ etc. macros.
 //
@@ -155,7 +156,6 @@
 // use with CheckOpValueStr() which allocates these strings using strdup().
 // Returns allocated string (with strdup) for passing into
 // ::logging::CheckError::(D)CheckOp methods.
-// TODO(pbos): Annotate this RETURNS_NONNULL after solving compile failure.
 BASE_EXPORT char* CreateCheckOpLogMessageString(const char* expr_str,
                                                 char* v1_str,
                                                 char* v2_str);
@@ -165,17 +165,24 @@
 // macro is used in an 'if' clause such as:
 // if (a == 1)
 //   CHECK_EQ(2, a);
-#define CHECK_OP_FUNCTION_IMPL(check_failure_function, name, op, val1, val2, \
-                               ...)                                          \
-  switch (0)                                                                 \
-  case 0:                                                                    \
-  default:                                                                   \
-    if (char* const message_on_fail = ::logging::Check##name##Impl(          \
-            (val1), (val2), #val1 " " #op " " #val2);                        \
-        !message_on_fail)                                                    \
-      ;                                                                      \
-    else                                                                     \
-      check_failure_function(message_on_fail __VA_OPT__(, ) __VA_ARGS__)
+#define CHECK_OP_FUNCTION_IMPL(check_failure_type, check_log_message_function, \
+                               name, op, val1, val2, ...)                      \
+  switch (0)                                                                   \
+  case 0:                                                                      \
+  default:                                                                     \
+    if (::logging::LogMessage *const message_on_fail =                         \
+            ::logging::Check##name##Impl(                                      \
+                (val1), (val2),                                                \
+                [](char* str1, char* str2) {                                   \
+                  return check_log_message_function(                           \
+                      ::logging::CreateCheckOpLogMessageString(                \
+                          #val1 " " #op " " #val2, str1, str2) __VA_OPT__(, )  \
+                          __VA_ARGS__);                                        \
+                });                                                            \
+        !message_on_fail)                                                      \
+      ;                                                                        \
+    else                                                                       \
+      (check_failure_type)(message_on_fail)
 
 #if !CHECK_WILL_STREAM()
 
@@ -185,7 +192,8 @@
 #else
 
 #define CHECK_OP_INTERNAL_IMPL(name, op, val1, val2)                       \
-  CHECK_OP_FUNCTION_IMPL(::logging::CheckNoreturnError::CheckOp, name, op, \
+  CHECK_OP_FUNCTION_IMPL(::logging::CheckNoreturnError,                    \
+                         ::logging::CheckNoreturnError::CheckOp, name, op, \
                          val1, val2)
 
 #endif
@@ -193,28 +201,28 @@
 #define CHECK_OP(name, op, val1, val2, ...)                                \
   BASE_IF(BASE_IS_EMPTY(__VA_ARGS__),                                      \
           CHECK_OP_INTERNAL_IMPL(name, op, val1, val2),                    \
-          CHECK_OP_FUNCTION_IMPL(::logging::CheckError::CheckOp, name, op, \
+          CHECK_OP_FUNCTION_IMPL(::logging::CheckError,                    \
+                                 ::logging::CheckError::CheckOp, name, op, \
                                  val1, val2, __VA_ARGS__))
 
 // The second overload avoids address-taking of static members for
 // fundamental types.
-#define DEFINE_CHECK_OP_IMPL(name, op)                                  \
-  template <typename T, typename U>                                     \
-    requires(!std::is_fundamental_v<T> || !std::is_fundamental_v<U>)    \
-  constexpr char* Check##name##Impl(const T& v1, const U& v2,           \
-                                    const char* expr_str) {             \
-    if (ANALYZER_ASSUME_TRUE(v1 op v2)) [[likely]]                      \
-      return nullptr;                                                   \
-    return CreateCheckOpLogMessageString(expr_str, CheckOpValueStr(v1), \
-                                         CheckOpValueStr(v2));          \
-  }                                                                     \
-  template <typename T, typename U>                                     \
-    requires(std::is_fundamental_v<T> && std::is_fundamental_v<U>)      \
-  constexpr char* Check##name##Impl(T v1, U v2, const char* expr_str) { \
-    if (ANALYZER_ASSUME_TRUE(v1 op v2)) [[likely]]                      \
-      return nullptr;                                                   \
-    return CreateCheckOpLogMessageString(expr_str, CheckOpValueStr(v1), \
-                                         CheckOpValueStr(v2));          \
+#define DEFINE_CHECK_OP_IMPL(name, op)                                         \
+  template <typename T, typename U, typename F>                                \
+    requires(!std::is_fundamental_v<T> || !std::is_fundamental_v<U>)           \
+  constexpr ::logging::LogMessage* Check##name##Impl(const T& v1, const U& v2, \
+                                                     F on_failure) {           \
+    if (ANALYZER_ASSUME_TRUE(v1 op v2)) [[likely]]                             \
+      return nullptr;                                                          \
+    return on_failure(CheckOpValueStr(v1), CheckOpValueStr(v2));               \
+  }                                                                            \
+  template <typename T, typename U, typename F>                                \
+    requires(std::is_fundamental_v<T> && std::is_fundamental_v<U>)             \
+  constexpr ::logging::LogMessage* Check##name##Impl(T v1, U v2,               \
+                                                     F on_failure) {           \
+    if (ANALYZER_ASSUME_TRUE(v1 op v2)) [[likely]]                             \
+      return nullptr;                                                          \
+    return on_failure(CheckOpValueStr(v1), CheckOpValueStr(v2));               \
   }
 
 // clang-format off
@@ -241,8 +249,10 @@
 
 #if DCHECK_IS_ON()
 
-#define DCHECK_OP(name, op, val1, val2) \
-  CHECK_OP_FUNCTION_IMPL(::logging::CheckError::DCheckOp, name, op, val1, val2)
+#define DCHECK_OP(name, op, val1, val2)                                   \
+  CHECK_OP_FUNCTION_IMPL(::logging::CheckError,                           \
+                         ::logging::CheckError::DCheckOp, name, op, val1, \
+                         val2)
 
 #else
 
@@ -263,7 +273,8 @@
 // clang-format on
 
 #define DUMP_WILL_BE_CHECK_OP(name, op, val1, val2)                          \
-  CHECK_OP_FUNCTION_IMPL(::logging::CheckError::DumpWillBeCheckOp, name, op, \
+  CHECK_OP_FUNCTION_IMPL(::logging::CheckError,                              \
+                         ::logging::CheckError::DumpWillBeCheckOp, name, op, \
                          val1, val2)
 
 #define DUMP_WILL_BE_CHECK_EQ(val1, val2) \
diff --git a/tot/base/check_unittest.cc b/tot/base/check_unittest.cc
index ed8d730..d6f0e42 100644
--- a/tot/base/check_unittest.cc
+++ b/tot/base/check_unittest.cc
@@ -2,6 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include <array>
 #include <string>
 #include <string_view>
 #include <tuple>
@@ -59,8 +60,9 @@
 };
 
 MATCHER_P2(LogErrorMatches, line, expected_msg, "") {
-  EXPECT_THAT(arg, testing::HasSubstr(
-                       base::StringPrintf("check_unittest.cc(%d)] ", line)));
+  EXPECT_THAT(arg,
+              testing::HasSubstr(base::StringPrintf(
+                  "%s:%d] ", base::Location::Current().file_name(), line)));
   if (std::string(expected_msg).find("=~") == 0) {
     EXPECT_THAT(std::string(arg),
                 testing::ContainsRegex(std::string(expected_msg).substr(2)));
@@ -198,13 +200,13 @@
       PCHECK(fopen(file, "r") != nullptr) << "foo");
 
   EXPECT_DCHECK(
-      "Check failed: fopen(file, \"r\") != nullptr."
+      "DCHECK failed: fopen(file, \"r\") != nullptr."
       " : " +
           err,
       DPCHECK(fopen(file, "r") != nullptr));
 
   EXPECT_DCHECK(
-      "Check failed: fopen(file, \"r\") != nullptr."
+      "DCHECK failed: fopen(file, \"r\") != nullptr."
       " foo: " +
           err,
       DPCHECK(fopen(file, "r") != nullptr) << "foo");
@@ -220,12 +222,12 @@
   EXPECT_CHECK("Check failed: a >= b (1 vs. 2)", CHECK_GE(a, b));
   EXPECT_CHECK("Check failed: a > b (1 vs. 2)",  CHECK_GT(a, b));
 
-  EXPECT_DCHECK("Check failed: a == b (1 vs. 2)", DCHECK_EQ(a, b));
-  EXPECT_DCHECK("Check failed: a != a (1 vs. 1)", DCHECK_NE(a, a));
-  EXPECT_DCHECK("Check failed: b <= a (2 vs. 1)", DCHECK_LE(b, a));
-  EXPECT_DCHECK("Check failed: b < a (2 vs. 1)",  DCHECK_LT(b, a));
-  EXPECT_DCHECK("Check failed: a >= b (1 vs. 2)", DCHECK_GE(a, b));
-  EXPECT_DCHECK("Check failed: a > b (1 vs. 2)",  DCHECK_GT(a, b));
+  EXPECT_DCHECK("DCHECK failed: a == b (1 vs. 2)", DCHECK_EQ(a, b));
+  EXPECT_DCHECK("DCHECK failed: a != a (1 vs. 1)", DCHECK_NE(a, a));
+  EXPECT_DCHECK("DCHECK failed: b <= a (2 vs. 1)", DCHECK_LE(b, a));
+  EXPECT_DCHECK("DCHECK failed: b < a (2 vs. 1)",  DCHECK_LT(b, a));
+  EXPECT_DCHECK("DCHECK failed: a >= b (1 vs. 2)", DCHECK_GE(a, b));
+  EXPECT_DCHECK("DCHECK failed: a > b (1 vs. 2)",  DCHECK_GT(a, b));
   // clang-format on
 
   EXPECT_DUMP_WILL_BE_CHECK("Check failed: a == b (1 vs. 2)",
@@ -251,13 +253,13 @@
   EXPECT_CHECK("Check failed: csv == s (2 vs. 3)", CHECK_EQ(csv, s));
   EXPECT_CHECK("Check failed: sv == s (1 vs. 3)", CHECK_EQ(sv, s));
 
-  EXPECT_DCHECK("Check failed: sv == csv (1 vs. 2)", DCHECK_EQ(sv, csv));
-  EXPECT_DCHECK("Check failed: csv == s (2 vs. 3)", DCHECK_EQ(csv, s));
-  EXPECT_DCHECK("Check failed: sv == s (1 vs. 3)", DCHECK_EQ(sv, s));
+  EXPECT_DCHECK("DCHECK failed: sv == csv (1 vs. 2)", DCHECK_EQ(sv, csv));
+  EXPECT_DCHECK("DCHECK failed: csv == s (2 vs. 3)", DCHECK_EQ(csv, s));
+  EXPECT_DCHECK("DCHECK failed: sv == s (1 vs. 3)", DCHECK_EQ(sv, s));
 }
 
 TEST(CheckDeathTest, CheckOpPointers) {
-  uint8_t arr[] = {3, 2, 1, 0};
+  auto arr = std::to_array<uint8_t>({3, 2, 1, 0});
   uint8_t* arr_start = &arr[0];
   // Print pointers and not the binary data in `arr`.
 #if BUILDFLAG(IS_WIN)
@@ -346,7 +348,7 @@
   EXPECT_TRUE(DCHECK_IS_ON());
 #endif
 
-  EXPECT_DCHECK("Check failed: false. ", DCHECK(false));
+  EXPECT_DCHECK("DCHECK failed: false. ", DCHECK(false));
 
   // Produce a consistent error code so that both the main instance of this test
   // and the EXPECT_DEATH invocation below get the same error codes for DPCHECK.
@@ -354,8 +356,8 @@
   std::ignore = fopen(file, "r");
   std::string err =
       logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
-  EXPECT_DCHECK("Check failed: false. : " + err, DPCHECK(false));
-  EXPECT_DCHECK("Check failed: 0 == 1 (0 vs. 1)", DCHECK_EQ(0, 1));
+  EXPECT_DCHECK("DCHECK failed: false. : " + err, DPCHECK(false));
+  EXPECT_DCHECK("DCHECK failed: 0 == 1 (0 vs. 1)", DCHECK_EQ(0, 1));
 
   // Test DCHECK on std::nullptr_t
   const void* p_null = nullptr;
@@ -368,7 +370,7 @@
   // Test DCHECK on a scoped enum.
   enum class Animal { DOG, CAT };
   DCHECK_EQ(Animal::DOG, Animal::DOG);
-  EXPECT_DCHECK("Check failed: Animal::DOG == Animal::CAT (0 vs. 1)",
+  EXPECT_DCHECK("DCHECK failed: Animal::DOG == Animal::CAT (0 vs. 1)",
                 DCHECK_EQ(Animal::DOG, Animal::CAT));
 
   // Test DCHECK on functions and function pointers.
@@ -387,10 +389,10 @@
   DCHECK_EQ(fp1, fp3);
   DCHECK_EQ(mp1, &MemberFunctions::MemberFunction1);
   DCHECK_EQ(mp2, &MemberFunctions::MemberFunction2);
-  EXPECT_DCHECK("=~Check failed: fp1 == fp2 \\(\\w+ vs. \\w+\\)",
+  EXPECT_DCHECK("=~DCHECK failed: fp1 == fp2 \\(\\w+ vs. \\w+\\)",
                 DCHECK_EQ(fp1, fp2));
   EXPECT_DCHECK(
-      "Check failed: mp2 == &MemberFunctions::MemberFunction1 (1 vs. 1)",
+      "DCHECK failed: mp2 == &MemberFunctions::MemberFunction1 (1 vs. 1)",
       DCHECK_EQ(mp2, &MemberFunctions::MemberFunction1));
 }
 
@@ -409,26 +411,30 @@
 
 TEST(CheckTest, DCheckEqStatements) {
   bool reached = false;
-  if (false)
+  if (false) {
     DCHECK_EQ(false, true);  // Unreached.
-  else
+  } else {
     DCHECK_EQ(true, reached = true);  // Reached, passed.
+  }
   ASSERT_EQ(DCHECK_IS_ON() ? true : false, reached);
 
-  if (false)
+  if (false) {
     DCHECK_EQ(false, true);  // Unreached.
+  }
 }
 
 TEST(CheckTest, CheckEqStatements) {
   bool reached = false;
-  if (false)
+  if (false) {
     CHECK_EQ(false, true);  // Unreached.
-  else
+  } else {
     CHECK_EQ(true, reached = true);  // Reached, passed.
+  }
   ASSERT_TRUE(reached);
 
-  if (false)
+  if (false) {
     CHECK_EQ(false, true);  // Unreached.
+  }
 }
 
 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
@@ -786,9 +792,14 @@
   const logging::SystemErrorCode kTestError = 28;
   const std::string kExpectedCheckMessageRegex = base::StrCat(
       {" Check failed: false. ", base::NumberToString(kTestError)});
+  const std::string kExpectedDCheckMessageRegex = base::StrCat(
+      {" DCHECK failed: false. ", base::NumberToString(kTestError)});
   const std::string kExpectedPCheckMessageRegex =
       base::StrCat({" Check failed: false. ", base::NumberToString(kTestError),
                     ": ", logging::SystemErrorCodeToString(kTestError)});
+  const std::string kExpectedDPCheckMessageRegex =
+      base::StrCat({" DCHECK failed: false. ", base::NumberToString(kTestError),
+                    ": ", logging::SystemErrorCodeToString(kTestError)});
   const std::string kExpectedNotreachedMessageRegex =
       base::StrCat({" NOTREACHED hit. ", base::NumberToString(kTestError)});
 
@@ -806,7 +817,7 @@
                CHECK(false) << logging::GetLastSystemErrorCode());
 
   set_last_error(kTestError);
-  EXPECT_DCHECK(kExpectedCheckMessageRegex,
+  EXPECT_DCHECK(kExpectedDCheckMessageRegex,
                 DCHECK(false) << logging::GetLastSystemErrorCode());
 
   set_last_error(kTestError);
@@ -814,7 +825,7 @@
                PCHECK(false) << logging::GetLastSystemErrorCode());
 
   set_last_error(kTestError);
-  EXPECT_DCHECK(kExpectedPCheckMessageRegex,
+  EXPECT_DCHECK(kExpectedDPCheckMessageRegex,
                 DPCHECK(false) << logging::GetLastSystemErrorCode());
 
   set_last_error(kTestError);
diff --git a/tot/base/command_line.cc b/tot/base/command_line.cc
index 3631cee..d4d3bc5 100644
--- a/tot/base/command_line.cc
+++ b/tot/base/command_line.cc
@@ -2,17 +2,15 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifdef UNSAFE_BUFFERS_BUILD
-// TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
-#pragma allow_unsafe_buffers
-#endif
-
 #include "base/command_line.h"
 
+#include <algorithm>
+#include <array>
 #include <ostream>
 #include <string_view>
 
 #include "base/check_op.h"
+#include "base/compiler_specific.h"
 #include "base/containers/contains.h"
 #include "base/containers/span.h"
 #include "base/debug/debugging_buildflags.h"
@@ -20,7 +18,6 @@
 #include "base/logging.h"
 #include "base/notreached.h"
 #include "base/numerics/checked_math.h"
-#include "base/ranges/algorithm.h"
 #include "base/strings/strcat.h"
 #include "base/strings/string_split.h"
 #include "base/strings/string_tokenizer.h"
@@ -54,13 +51,24 @@
 // By putting slash last, we can control whether it is treaded as a switch
 // value by changing the value of switch_prefix_count to be one less than
 // the array size.
-constexpr CommandLine::StringViewType kSwitchPrefixes[] = {L"--", L"-", L"/"};
+constexpr auto kSwitchPrefixes = std::to_array<CommandLine::StringViewType>({
+    L"--",
+    L"-",
+    L"/",
+});
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
 // Unixes don't use slash as a switch.
-constexpr CommandLine::StringViewType kSwitchPrefixes[] = {"--", "-"};
+constexpr auto kSwitchPrefixes = std::to_array<CommandLine::StringViewType>({
+    "--",
+    "-",
+});
 #endif
 size_t switch_prefix_count = std::size(kSwitchPrefixes);
 
+bool IsSwitchNameValid(std::string_view switch_name) {
+  return ToLowerASCII(switch_name) == switch_name;
+}
+
 #if BUILDFLAG(IS_WIN)
 // Switch string that specifies the single argument to the command line.
 // If present, everything after this switch is interpreted as a single
@@ -75,8 +83,9 @@
 size_t GetSwitchPrefixLength(CommandLine::StringViewType string) {
   for (size_t i = 0; i < switch_prefix_count; ++i) {
     CommandLine::StringType prefix(kSwitchPrefixes[i]);
-    if (string.substr(0, prefix.length()) == prefix)
+    if (string.substr(0, prefix.length()) == prefix) {
       return prefix.length();
+    }
   }
   return 0;
 }
@@ -89,13 +98,15 @@
   switch_string->clear();
   switch_value->clear();
   size_t prefix_length = GetSwitchPrefixLength(string);
-  if (prefix_length == 0 || prefix_length == string.length())
+  if (prefix_length == 0 || prefix_length == string.length()) {
     return false;
+  }
 
   const size_t equals_position = string.find(kSwitchValueSeparator);
   *switch_string = string.substr(0, equals_position);
-  if (equals_position != CommandLine::StringType::npos)
+  if (equals_position != CommandLine::StringType::npos) {
     *switch_value = string.substr(equals_position + 1);
+  }
   return true;
 }
 
@@ -104,8 +115,9 @@
 bool IsSwitchWithKey(CommandLine::StringViewType string,
                      CommandLine::StringViewType switch_key_without_prefix) {
   size_t prefix_length = GetSwitchPrefixLength(string);
-  if (prefix_length == 0 || prefix_length == string.length())
+  if (prefix_length == 0 || prefix_length == string.length()) {
     return false;
+  }
 
   const size_t equals_position = string.find(kSwitchValueSeparator);
   return string.substr(prefix_length, equals_position - prefix_length) ==
@@ -175,20 +187,17 @@
 
 CommandLine::CommandLine(NoProgram no_program) : argv_(1), begin_args_(1) {}
 
-CommandLine::CommandLine(const FilePath& program)
-    : argv_(1),
-      begin_args_(1) {
+CommandLine::CommandLine(const FilePath& program) : argv_(1), begin_args_(1) {
   SetProgram(program);
 }
 
 CommandLine::CommandLine(int argc, const CommandLine::CharType* const* argv)
     : argv_(1), begin_args_(1) {
-  InitFromArgv(argc, argv);
+  // SAFETY: required from caller.
+  UNSAFE_BUFFERS(InitFromArgv(argc, argv));
 }
 
-CommandLine::CommandLine(const StringVector& argv)
-    : argv_(1),
-      begin_args_(1) {
+CommandLine::CommandLine(const StringVector& argv) : argv_(1), begin_args_(1) {
   InitFromArgv(argv);
 }
 
@@ -241,8 +250,10 @@
   current_process_commandline_ = new CommandLine(NO_PROGRAM);
   // On Windows we need to convert the command line arguments to std::wstring.
   CommandLine::StringVector argv_vector;
-  for (int i = 0; i < argc; ++i)
-    argv_vector.push_back(UTF8ToWide(argv[i]));
+  for (int i = 0; i < argc; ++i) {
+    // SAFETY: required from caller.
+    argv_vector.push_back(UTF8ToWide(UNSAFE_BUFFERS(argv[i])));
+  }
   current_process_commandline_->InitFromArgv(argv_vector);
 }
 #endif  // BUILDFLAG(IS_WIN)
@@ -260,7 +271,8 @@
 #if BUILDFLAG(IS_WIN)
   current_process_commandline_->ParseFromString(::GetCommandLineW());
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
-  current_process_commandline_->InitFromArgv(argc, argv);
+  // SAFETY: required from caller.
+  UNSAFE_BUFFERS(current_process_commandline_->InitFromArgv(argc, argv));
 #else
 #error Unsupported platform
 #endif
@@ -305,8 +317,10 @@
 void CommandLine::InitFromArgv(int argc,
                                const CommandLine::CharType* const* argv) {
   StringVector new_argv;
-  for (int i = 0; i < argc; ++i)
-    new_argv.push_back(argv[i]);
+  for (int i = 0; i < argc; ++i) {
+    // SAFETY: required from caller.
+    new_argv.push_back(UNSAFE_BUFFERS(argv[i]));
+  }
   InitFromArgv(new_argv);
 }
 
@@ -338,7 +352,7 @@
 }
 
 bool CommandLine::HasSwitch(std::string_view switch_string) const {
-  DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
+  CHECK(IsSwitchNameValid(switch_string), base::NotFatalUntil::M134);
   return Contains(switches_, switch_string);
 }
 
@@ -364,13 +378,31 @@
 #endif
 }
 
+std::string CommandLine::GetSwitchValueUTF8(
+    std::string_view switch_string) const {
+  StringType value = GetSwitchValueNative(switch_string);
+
+#if BUILDFLAG(IS_WIN)
+  const std::string maybe_utf8_value = WideToUTF8(value);
+#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
+  const std::string maybe_utf8_value = value;
+#endif
+
+  if (!IsStringUTF8(maybe_utf8_value)) {
+    DLOG(WARNING) << "Value of switch (" << switch_string << ") is not UTF8.";
+    return {};
+  }
+  return maybe_utf8_value;
+}
+
 FilePath CommandLine::GetSwitchValuePath(std::string_view switch_string) const {
   return FilePath(GetSwitchValueNative(switch_string));
 }
 
 CommandLine::StringType CommandLine::GetSwitchValueNative(
     std::string_view switch_string) const {
-  DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
+  CHECK(IsSwitchNameValid(switch_string), base::NotFatalUntil::M134);
+
   auto result = switches_.find(switch_string);
   return result == switches_.end() ? StringType() : result->second;
 }
@@ -410,8 +442,9 @@
     combined_switch_string.insert(0, kSwitchPrefixes[0].data(),
                                   kSwitchPrefixes[0].size());
   }
-  if (!value.empty())
+  if (!value.empty()) {
     base::StrAppend(&combined_switch_string, {kSwitchValueSeparator, value});
+  }
   // Append the switch and update the switches/arguments divider |begin_args_|.
   argv_.insert(argv_.begin() + begin_args_, combined_switch_string);
   begin_args_ = (CheckedNumeric(begin_args_) + 1).ValueOrDie();
@@ -419,6 +452,14 @@
 
 void CommandLine::AppendSwitchASCII(std::string_view switch_string,
                                     std::string_view value_string) {
+  AppendSwitchUTF8(switch_string, value_string);
+}
+
+void CommandLine::AppendSwitchUTF8(std::string_view switch_string,
+                                   std::string_view value_string) {
+  DCHECK(IsStringUTF8(value_string))
+      << "Switch (" << switch_string << ") value (" << value_string
+      << ") is not UTF8.";
 #if BUILDFLAG(IS_WIN)
   AppendSwitchNative(switch_string, UTF8ToWide(value_string));
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
@@ -432,17 +473,20 @@
 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
   sequence_checker_.Check();
 #endif
+  CHECK(IsSwitchNameValid(switch_key_without_prefix),
+        base::NotFatalUntil::M134);
+
 #if BUILDFLAG(IS_WIN)
   StringType switch_key_native = UTF8ToWide(switch_key_without_prefix);
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
   StringType switch_key_native(switch_key_without_prefix);
 #endif
 
-  DCHECK_EQ(ToLowerASCII(switch_key_without_prefix), switch_key_without_prefix);
   DCHECK_EQ(0u, GetSwitchPrefixLength(switch_key_native));
   auto it = switches_.find(switch_key_without_prefix);
-  if (it == switches_.end())
+  if (it == switches_.end()) {
     return;
+  }
   switches_.erase(it);
   // Also erase from the switches section of |argv_| and update |begin_args_|
   // accordingly.
@@ -475,9 +519,10 @@
   // Gather all arguments after the last switch (may include kSwitchTerminator).
   StringVector args(argv_.begin() + begin_args_, argv_.end());
   // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
-  auto switch_terminator = ranges::find(args, kSwitchTerminator);
-  if (switch_terminator != args.end())
+  auto switch_terminator = std::ranges::find(args, kSwitchTerminator);
+  if (switch_terminator != args.end()) {
     args.erase(switch_terminator);
+  }
   return args;
 }
 
@@ -500,13 +545,14 @@
 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
   sequence_checker_.Check();
 #endif
-  argv_.push_back(StringType(value));
+  argv_.emplace_back(value);
 }
 
 void CommandLine::AppendArguments(const CommandLine& other,
                                   bool include_program) {
-  if (include_program)
+  if (include_program) {
     SetProgram(other.GetProgram());
+  }
   if (!other.argv().empty()) {
     AppendSwitchesAndArguments(span(other.argv()).subspan<1>());
   }
@@ -516,8 +562,9 @@
 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
   sequence_checker_.Check();
 #endif
-  if (wrapper.empty())
+  if (wrapper.empty()) {
     return;
+  }
   // Split the wrapper command based on whitespace (with quoting).
   // StringViewType does not currently work directly with StringTokenizerT.
   using CommandLineTokenizer =
@@ -538,8 +585,9 @@
 #if BUILDFLAG(IS_WIN)
 void CommandLine::ParseFromString(StringViewType command_line) {
   command_line = TrimWhitespace(command_line, TRIM_ALL);
-  if (command_line.empty())
+  if (command_line.empty()) {
     return;
+  }
   raw_command_line_string_ = command_line;
 
   int num_args = 0;
@@ -553,8 +601,9 @@
     auto command_line_to_argv_w_proc =
         reinterpret_cast<decltype(::CommandLineToArgvW)*>(
             ::GetProcAddress(downlevel_shell32_dll, "CommandLineToArgvW"));
-    if (command_line_to_argv_w_proc)
+    if (command_line_to_argv_w_proc) {
       args = command_line_to_argv_w_proc(command_line.data(), &num_args);
+    }
   } else {
     // Since the apiset is not available, allow the delayload of shell32.dll
     // to take place.
@@ -563,13 +612,14 @@
 
   DPLOG_IF(FATAL, !args) << "CommandLineToArgvW failed on command line: "
                          << command_line;
-  StringVector argv(args, args + num_args);
+  StringVector argv(args, UNSAFE_TODO(args + num_args));
   InitFromArgv(argv);
   raw_command_line_string_ = StringViewType();
   LocalFree(args);
 
-  if (downlevel_shell32_dll)
+  if (downlevel_shell32_dll) {
     ::FreeLibrary(downlevel_shell32_dll);
+  }
 }
 
 #endif  // BUILDFLAG(IS_WIN)
@@ -622,8 +672,9 @@
     StringType switch_string;
     StringType switch_value;
     parse_switches &= arg != kSwitchTerminator;
-    if (i > 1)
+    if (i > 1) {
       params.append(FILE_PATH_LITERAL(" "));
+    }
     if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
       params.append(switch_string);
       if (!switch_value.empty()) {
@@ -730,8 +781,9 @@
   // argument is present.
   const size_t arg_position =
       single_arg_switch_position + single_arg_switch.length() + 1;
-  if (arg_position >= raw_command_line_string_.length())
+  if (arg_position >= raw_command_line_string_.length()) {
     return;
+  }
   has_single_argument_switch_ = true;
   const StringViewType arg = raw_command_line_string_.substr(arg_position);
   if (!arg.empty()) {
diff --git a/tot/base/command_line.h b/tot/base/command_line.h
index 1e9bcda..0005cb0 100644
--- a/tot/base/command_line.h
+++ b/tot/base/command_line.h
@@ -26,8 +26,8 @@
 #include <vector>
 
 #include "base/base_export.h"
-#include "base/containers/span.h"
 #include "base/compiler_specific.h"
+#include "base/containers/span.h"
 #include "base/debug/debugging_buildflags.h"
 #include "build/build_config.h"
 
@@ -71,6 +71,7 @@
   explicit CommandLine(const FilePath& program);
 
   // Construct a new command line from an argument list.
+  // TODO(tsepez): two-arg form should be UNSAFE_BUFFER_USAGE.
   CommandLine(int argc, const CharType* const* argv);
   explicit CommandLine(const StringVector& argv);
 
@@ -101,6 +102,7 @@
   // CommandLineToArgvW to parse the command line and convert it back to
   // argc and argv. Tests who don't want this dependency on shell32 and need
   // to honor the arguments passed in should use this function.
+  // TODO(tsepez): should be UNSAFE_BUFFER_USAGE.
   static void InitUsingArgvForTesting(int argc, const char* const* argv);
 #endif
 
@@ -109,7 +111,8 @@
   // don't trust the CRT's parsing of the command line, but it still must be
   // called to set up the command line. Returns false if initialization has
   // already occurred, and true otherwise. Only the caller receiving a 'true'
-  // return value should take responsibility for calling Reset.
+  // return value should take responsibility for calling Reset().
+  // TODO(tsepez): should be UNSAFE_BUFFER_USAGE.
   static bool Init(int argc, const char* const* argv);
 
   // Destroys the current process CommandLine singleton. This is necessary if
@@ -128,6 +131,7 @@
   static bool InitializedForCurrentProcess();
 
   // Initialize from an argv vector.
+  // TODO(tsepez): two-arg form should be UNSAFE_BUFFER_USAGE.
   void InitFromArgv(int argc, const CharType* const* argv);
   void InitFromArgv(const StringVector& argv);
 
@@ -197,6 +201,7 @@
   // value or isn't present, this method returns the empty string.
   // Switch names must be lowercase.
   std::string GetSwitchValueASCII(std::string_view switch_string) const;
+  std::string GetSwitchValueUTF8(std::string_view switch_string) const;
   FilePath GetSwitchValuePath(std::string_view switch_string) const;
   StringType GetSwitchValueNative(std::string_view switch_string) const;
 
@@ -210,6 +215,7 @@
   void AppendSwitchNative(std::string_view switch_string, StringViewType value);
   void AppendSwitchASCII(std::string_view switch_string,
                          std::string_view value);
+  void AppendSwitchUTF8(std::string_view switch_string, std::string_view value);
 
   // Removes the switch that matches |switch_key_without_prefix|, regardless of
   // prefix and value. If no such switch is present, this has no effect.
diff --git a/tot/base/command_line_fuzzer.cc b/tot/base/command_line_fuzzer.cc
index 2704f6a..531f28b 100644
--- a/tot/base/command_line_fuzzer.cc
+++ b/tot/base/command_line_fuzzer.cc
@@ -2,6 +2,8 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "base/command_line.h"
+
 #include <fuzzer/FuzzedDataProvider.h>
 #include <stdint.h>
 
@@ -10,9 +12,7 @@
 #include <tuple>
 
 #include "base/check.h"
-#include "base/command_line.h"
 #include "base/files/file_path.h"
-#include "base/ranges/algorithm.h"
 #include "base/strings/string_util.h"
 #include "base/strings/utf_string_conversions.h"
 #include "build/build_config.h"
@@ -34,8 +34,9 @@
     FuzzedDataProvider& provider) {
   CommandLine::StringVector strings(
       provider.ConsumeIntegralInRange<int>(0, 100));
-  for (auto& item : strings)
+  for (auto& item : strings) {
     item = GenerateNativeString(provider);
+  }
   return strings;
 }
 
@@ -50,7 +51,8 @@
 bool IsValidSwitchName(const std::string& text) {
   // This duplicates the logic in command_line.cc, but it's not exposed in form
   // of public interface.
-  return !text.empty() && !ranges::any_of(text, IsForbiddenSwitchCharacter) &&
+  return !text.empty() &&
+         !std::ranges::any_of(text, IsForbiddenSwitchCharacter) &&
          !StartsWith(text, "-") && !StartsWith(text, "/");
 }
 
@@ -105,15 +107,17 @@
       case 2: {
         // Add an argument.
         CommandLine::StringType arg = GenerateNativeString(provider);
-        if (!arg.empty() && IsStringASCII(arg))
+        if (!arg.empty() && IsStringASCII(arg)) {
           command_line.AppendArgNative(arg);
+        }
         break;
       }
       case 3: {
         // Add a wrapper.
         CommandLine::StringType wrapper = GenerateNativeString(provider);
-        if (!wrapper.empty())
+        if (!wrapper.empty()) {
           command_line.PrependWrapper(wrapper);
+        }
         break;
       }
       case 4: {
diff --git a/tot/base/command_line_unittest.cc b/tot/base/command_line_unittest.cc
index 36619e0..23180c4 100644
--- a/tot/base/command_line_unittest.cc
+++ b/tot/base/command_line_unittest.cc
@@ -9,6 +9,7 @@
 
 #include "base/command_line.h"
 
+#include <array>
 #include <memory>
 #include <string>
 #include <string_view>
@@ -19,6 +20,7 @@
 #include "base/strings/strcat.h"
 #include "base/strings/string_util.h"
 #include "base/strings/utf_string_conversions.h"
+#include "base/test/gtest_util.h"
 #include "build/build_config.h"
 #include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
@@ -104,8 +106,8 @@
   EXPECT_EQ("", cl.GetSwitchValueASCII("foo"));
   EXPECT_EQ("", cl.GetSwitchValueASCII("bar"));
   EXPECT_EQ("", cl.GetSwitchValueASCII("cruller"));
-  EXPECT_EQ("--dog=canine --cat=feline", cl.GetSwitchValueASCII(
-      "other-switches"));
+  EXPECT_EQ("--dog=canine --cat=feline",
+            cl.GetSwitchValueASCII("other-switches"));
   EXPECT_EQ("45--output-rotation", cl.GetSwitchValueASCII("input-translation"));
 
   const CommandLine::StringVector& args = cl.GetArgs();
@@ -178,8 +180,8 @@
   EXPECT_EQ("", cl.GetSwitchValueASCII("foo"));
   EXPECT_EQ("", cl.GetSwitchValueASCII("bar"));
   EXPECT_EQ("", cl.GetSwitchValueASCII("cruller"));
-  EXPECT_EQ("--dog=canine --cat=feline", cl.GetSwitchValueASCII(
-      "other-switches"));
+  EXPECT_EQ("--dog=canine --cat=feline",
+            cl.GetSwitchValueASCII("other-switches"));
   EXPECT_EQ("45--output-rotation", cl.GetSwitchValueASCII("input-translation"));
   EXPECT_EQ(kTricky, cl.GetSwitchValueNative("quotes"));
 
@@ -326,6 +328,102 @@
 #endif
 }
 
+// Test methods for appending valid UTF8 values to a command line.
+TEST(CommandLineTest, UTF8Valid) {
+  std::string ascii_switch = "ascii";
+  std::string ascii_value = "Opdateringkontroleringfout";
+  std::string arabic_switch = "arabic";
+  std::string arabic_value = "خطأ في عملية التحقق من التحديث: 5555.";
+  std::string hindi_switch = "hindi";
+  std::string hindi_value = "अपडेट जांच में यह गड़बड़ी है: 5555.";
+  std::string japanese_switch = "japanese";
+  std::string japanese_value = "更新確認エラー: 5555。";
+
+  CommandLine cl(FilePath(FILE_PATH_LITERAL("Program")));
+
+  cl.AppendSwitchUTF8(ascii_switch, ascii_value);
+  cl.AppendSwitchUTF8(arabic_switch, arabic_value);
+  cl.AppendSwitchUTF8(hindi_switch, hindi_value);
+  cl.AppendSwitchUTF8(japanese_switch, japanese_value);
+
+  EXPECT_TRUE(cl.HasSwitch(ascii_switch));
+  EXPECT_EQ(ascii_value, cl.GetSwitchValueASCII(ascii_switch));
+  EXPECT_EQ(ascii_value, cl.GetSwitchValueUTF8(ascii_switch));
+  EXPECT_TRUE(cl.HasSwitch(arabic_switch));
+  EXPECT_TRUE(cl.GetSwitchValueASCII(arabic_switch).empty());
+  EXPECT_EQ(arabic_value, cl.GetSwitchValueUTF8(arabic_switch));
+  EXPECT_TRUE(cl.HasSwitch(hindi_switch));
+  EXPECT_TRUE(cl.GetSwitchValueASCII(hindi_switch).empty());
+  EXPECT_EQ(hindi_value, cl.GetSwitchValueUTF8(hindi_switch));
+  EXPECT_TRUE(cl.HasSwitch(japanese_switch));
+  EXPECT_TRUE(cl.GetSwitchValueASCII(japanese_switch).empty());
+  EXPECT_EQ(japanese_value, cl.GetSwitchValueUTF8(japanese_switch));
+}
+
+class CommandLineUTF8InvalidTest
+    : public ::testing::TestWithParam<std::string> {
+ protected:
+  std::string switch_value() const { return GetParam(); }
+};
+
+INSTANTIATE_TEST_SUITE_P(
+    CommandLineUTF8InvalidTestCases,
+    CommandLineUTF8InvalidTest,
+    ::testing::Values(
+        // Invalid encoding of U+1FFFE (0x8F instead of 0x9F)
+        "\xF0\x8F\xBF\xBE",
+
+        // Surrogate code points
+        "\xED\xA0\x80\xED\xBF\xBF",
+        "\xED\xA0\x8F",
+        "\xED\xBF\xBF",
+
+        // Overlong sequences
+        "\xC0\x80",                  // U+0000
+        "\xC1\x80\xC1\x81",          // "AB"
+        "\xE0\x80\x80",              // U+0000
+        "\xE0\x82\x80",              // U+0080
+        "\xE0\x9F\xBF",              // U+07FF
+        "\xF0\x80\x80\x8D",          // U+000D
+        "\xF0\x80\x82\x91",          // U+0091
+        "\xF0\x80\xA0\x80",          // U+0800
+        "\xF0\x8F\xBB\xBF",          // U+FEFF (BOM)
+        "\xF8\x80\x80\x80\xBF",      // U+003F
+        "\xFC\x80\x80\x80\xA0\xA5",  // U+00A5
+
+        // Beyond U+10FFFF (the upper limit of Unicode codespace)
+        "\xF4\x90\x80\x80",          // U+110000
+        "\xF8\xA0\xBF\x80\xBF",      // 5 bytes
+        "\xFC\x9C\xBF\x80\xBF\x80",  // 6 bytes
+
+        // BOM in UTF-16(BE|LE)
+        "\xFE\xFF",
+        "\xFF\xFE",
+
+        // Strings in legacy encodings. We can certainly make up strings
+        // in a legacy encoding that are valid in UTF-8, but in real data,
+        // most of them are invalid as UTF-8.
+
+        // cafe with U+00E9 in ISO-8859-1
+        "caf\xE9",
+        // U+AC00, U+AC001 in EUC-KR
+        "\xB0\xA1\xB0\xA2",
+        // U+4F60 U+597D in Big5
+        "\xA7\x41\xA6\x6E",
+        // "abc" with U+201[CD] in windows-125[0-8]
+        // clang-format off
+        "\x93" "abc\x94",
+        // clang-format on
+        // U+0639 U+064E U+0644 U+064E in ISO-8859-6
+        "\xD9\xEE\xE4\xEE",
+        // U+03B3 U+03B5 U+03B9 U+03AC in ISO-8859-7
+        "\xE3\xE5\xE9\xDC"));
+
+TEST_P(CommandLineUTF8InvalidTest, Test) {
+  CommandLine cl(FilePath(FILE_PATH_LITERAL("Program")));
+  EXPECT_DCHECK_DEATH({ cl.AppendSwitchUTF8("invalid", switch_value()); });
+}
+
 TEST(CommandLineTest, AppendSwitchesDashDash) {
   const CommandLine::CharType* const raw_argv[] = {FILE_PATH_LITERAL("prog"),
                                                    FILE_PATH_LITERAL("--"),
@@ -528,10 +626,12 @@
   CommandLine assigned = *initial;
   CommandLine::SwitchMap switch_map = initial->GetSwitches();
   initial.reset();
-  for (const auto& pair : switch_map)
+  for (const auto& pair : switch_map) {
     EXPECT_TRUE(copy_constructed.HasSwitch(pair.first));
-  for (const auto& pair : switch_map)
+  }
+  for (const auto& pair : switch_map) {
     EXPECT_TRUE(assigned.HasSwitch(pair.first));
+  }
 }
 
 TEST(CommandLineTest, CopySwitches) {
@@ -563,10 +663,11 @@
       "bbbbbbbbb",
       "c",
   };
-  static constexpr CommandLine::StringViewType kArgs[] = {
-      FILE_PATH_LITERAL("beebop"),
-      FILE_PATH_LITERAL("alouie"),
-  };
+  constexpr static const auto kArgs =
+      std::to_array<CommandLine::StringViewType>({
+          FILE_PATH_LITERAL("beebop"),
+          FILE_PATH_LITERAL("alouie"),
+      });
   CommandLine initial(CommandLine::NO_PROGRAM);
   for (auto a_switch : kSwitches) {
     initial.AppendSwitch(a_switch);
diff --git a/tot/base/compiler_specific.h b/tot/base/compiler_specific.h
index 2e2c21f..f484a2f 100644
--- a/tot/base/compiler_specific.h
+++ b/tot/base/compiler_specific.h
@@ -59,7 +59,9 @@
 //     // This body will not be inlined into callers.
 //   }
 // ```
-#if __has_cpp_attribute(gnu::noinline)
+#if __has_cpp_attribute(clang::noinline)
+#define NOINLINE [[clang::noinline]]
+#elif __has_cpp_attribute(gnu::noinline)
 #define NOINLINE [[gnu::noinline]]
 #elif __has_cpp_attribute(msvc::noinline)
 #define NOINLINE [[msvc::noinline]]
@@ -67,6 +69,24 @@
 #define NOINLINE
 #endif
 
+// Annotates a call site indicating that the callee should not be inlined.
+//
+// See also:
+//   https://clang.llvm.org/docs/AttributeReference.html#noinline
+//
+// Usage:
+// ```
+//   void Func() {
+//      // This specific call to `DoSomething` should not be inlined.
+//      NOINLINE_CALL DoSomething();
+//   }
+// ```
+#if __has_cpp_attribute(clang::noinline)
+#define NOINLINE_CALL [[clang::noinline]]
+#else
+#define NOINLINE_CALL
+#endif
+
 // Annotates a function indicating it should not be optimized.
 //
 // See also:
@@ -102,7 +122,9 @@
 // Since `ALWAYS_INLINE` is performance-oriented but can hamper debugging,
 // ignore it in debug mode.
 #if defined(NDEBUG)
-#if __has_cpp_attribute(gnu::always_inline)
+#if __has_cpp_attribute(clang::always_inline)
+#define ALWAYS_INLINE [[clang::always_inline]] inline
+#elif __has_cpp_attribute(gnu::always_inline)
 #define ALWAYS_INLINE [[gnu::always_inline]] inline
 #elif defined(COMPILER_MSVC)
 #define ALWAYS_INLINE __forceinline
@@ -112,6 +134,30 @@
 #define ALWAYS_INLINE inline
 #endif
 
+// Annotates a call site indicating the calee should always be inlined.
+//
+// See also:
+//   https://clang.llvm.org/docs/AttributeReference.html#always-inline-force-inline
+//
+// Usage:
+// ```
+//   void Func() {
+//     // This specific call will be inlined if possible.
+//     ALWAYS_INLINE_CALL DoSomething();
+//   }
+// ```
+//
+// Since `ALWAYS_INLINE_CALL` is performance-oriented but can hamper debugging,
+// ignore it in debug mode.
+#if defined(NDEBUG)
+#if __has_cpp_attribute(clang::always_inline)
+#define ALWAYS_INLINE_CALL [[clang::always_inline]]
+#endif
+#endif
+#if !defined(ALWAYS_INLINE_CALL)
+#define ALWAYS_INLINE_CALL
+#endif
+
 // Annotates a function indicating it should never be tail called. Useful to
 // make sure callers of the annotated function are never omitted from call
 // stacks. Often useful with `NOINLINE` to make sure the function itself is also
diff --git a/tot/base/component_export.h b/tot/base/component_export.h
index cc468b8..0c70e8d 100644
--- a/tot/base/component_export.h
+++ b/tot/base/component_export.h
@@ -61,7 +61,7 @@
 // or absense of an extra comma can be used to conditionally shift subsequent
 // argument positions and thus influence which argument is selected.
 #define COMPONENT_MACRO_CONDITIONAL_COMMA_(...) \
-  COMPONENT_MACRO_CONDITIONAL_COMMA_IMPL_(__VA_ARGS__,)
+  COMPONENT_MACRO_CONDITIONAL_COMMA_IMPL_(__VA_ARGS__, )
 #define COMPONENT_MACRO_CONDITIONAL_COMMA_IMPL_(x, ...) \
   COMPONENT_MACRO_CONDITIONAL_COMMA_##x##_
 #define COMPONENT_MACRO_CONDITIONAL_COMMA_1_ ,
diff --git a/tot/base/component_export_unittest.cc b/tot/base/component_export_unittest.cc
index b2692ff..12c1156 100644
--- a/tot/base/component_export_unittest.cc
+++ b/tot/base/component_export_unittest.cc
@@ -3,6 +3,7 @@
 // found in the LICENSE file.
 
 #include "base/component_export.h"
+
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace base {
diff --git a/tot/base/containers/README.md b/tot/base/containers/README.md
index 50633fe..b702ebd 100644
--- a/tot/base/containers/README.md
+++ b/tot/base/containers/README.md
@@ -4,97 +4,105 @@
 
 ## What goes here
 
-This directory contains some STL-like containers.
+This directory contains some stdlib-like containers.
 
 Things should be moved here that are generally applicable across the code base.
 Don't add things here just because you need them in one place and think others
-may someday want something similar. You can put specialized containers in
-your component's directory and we can promote them here later if we feel there
-is broad applicability.
+may someday want something similar. You can put specialized containers in your
+component's directory and we can promote them here later if we feel there is
+broad applicability.
 
 ### Design and naming
 
 Fundamental [//base principles](../README.md#design-and-naming) apply, i.e.:
 
-Containers should adhere as closely to STL as possible. Functions and behaviors
-not present in STL should only be added when they are related to the specific
-data structure implemented by the container.
+Containers should adhere as closely to stdlib as possible. Functions and
+behaviors not present in stdlib should only be added when they are related to
+the specific data structure implemented by the container.
 
-For STL-like containers our policy is that they should use STL-like naming even
-when it may conflict with the style guide. So functions and class names should
-be lower case with underscores. Non-STL-like classes and functions should use
-Google naming. Be sure to use the base namespace.
+For stdlib-like containers our policy is that they should use stdlib-like naming
+even when it may conflict with the style guide. So functions and class names
+should be lower case with underscores. Non-stdlib-like classes and functions
+should use Google naming. Be sure to use the base namespace.
 
 ## Map and set selection
 
 ### Usage advice
 
-*   Do not use `base::flat_map` or `base::flat_set` if the number of items will
-    be large or unbounded and elements will be inserted/deleted outside of the
-    containers constructor/destructor - they have O(n) performance on inserts
-    and deletes of individual items.
+1.  If you just need a generic map or set container without any additional
+    properties then prefer to use `absl::flat_hash_map` and
+    `absl::flat_hash_set`. These are versatile containers that have good
+    performance on both large and small sized data.
 
-*   Do not default to using `std::unordered_set` and `std::unordered_map`. In
-    the common case, query performance is unlikely to be sufficiently higher
-    than `std::map` to make a difference, insert performance is slightly worse,
-    and the memory overhead is high. This makes sense mostly for large tables
-    where you expect a lot of lookups.
+    1.  Is pointer-stability of values (but not keys) required? Then use
+        `absl::flat_hash_map<Key, std::unique_ptr<Value>>`.
+    2.  Is pointer-stability of keys required? Then use `absl::node_hash_map`
+        and `absl::node_hash_set`.
 
-*   Most maps and sets in Chrome are small and contain objects that can be moved
-    efficiently. In this case, consider `base::flat_map` and `base::flat_set`.
-    You need to be aware of the maximum expected size of the container since
-    individual inserts and deletes are O(n), giving O(n^2) construction time for
-    the entire map. But because it avoids mallocs in most cases, inserts are
-    better or comparable to other containers even for several dozen items, and
-    efficiently-moved types are unlikely to have performance problems for most
-    cases until you have hundreds of items. If your container can be constructed
-    in one shot, the constructor from vector gives O(n log n) construction times
-    and it should be strictly better than a `std::map`.
+2.  If you require sorted order, then the best choice depends on whether your
+    map is going to be written once and read many times, or if it is going to be
+    written frequently throughout its lifetime.
 
-    Conceptually inserting a range of n elements into a `base::flat_map` or
-    `base::flat_set` behaves as if insert() was called for each individually
-    element. Thus in case the input range contains repeated elements, only the
-    first one of these duplicates will be inserted into the container. This
-    behaviour applies to construction from a range as well.
+    1.  If the map is written once, then `base::flat_map` and `base::flat_set`
+        are good choices. While they have poor asymptotic behavior on writes, on
+        a write-once container this performance is no worse than the standard
+        library tree containers and so they are strictly better in terms of
+        overhead.
+    2.  If the map is always very small, then `base::flat_map` and
+        `base::flat_set` are again good choices, even if the map is being
+        written to multiple times. While mutations are O(n) this cost is
+        negligible for very small values of n compared to the cost of doing a
+        malloc on every mutation.
+    3.  If the map is written multiple times and is large then then `std::map`
+        and `std::set` are the best choices.
+    4.  If you require pointer stability (on either the key or value) then
+        `std::map` and `std::set` are the also the best choices.
 
-*   `base::small_map` has better runtime memory usage without the poor mutation
-    performance of large containers that `base::flat_map` has. But this
-    advantage is partially offset by additional code size. Prefer in cases where
-    you make many objects so that the code/heap tradeoff is good.
+When using `base::flat_map` and `base::flat_set` there are also fixed versions
+of these that are backed by a `std::array` instead of a `std::vector` and which
+don't provide mutating operators, but which are constexpr friendly and support
+stack allocation. If you are using the flat structures because your container is
+only written once then the fixed versions may be an even better alternative,
+particularly if you're looking for a structure that can be used as a
+compile-time lookup table.
 
-*   Use `std::map` and `std::set` if you can't decide. Even if they're not
-    great, they're unlikely to be bad or surprising.
+Note that this advice never suggests the use of `std::unordered_map` and
+`std::unordered_set`. These containers provides similar features to the Abseil
+flat hash containers but with worse performance. They should only be used if
+absolutely required for compatibility with third-party code.
 
-### Map and set details
+Also note that this advice does not suggest the use of the Abseil btree
+structures, `absl::btree_map` and `absl::btree_set`. This is because while these
+types do provide good performance for cases where you need a sorted container
+they have been found to introduce a very large code size penalty when using them
+in Chromium. Until this problem can be resolved they should not be used in
+Chromium code.
 
-Sizes are on 64-bit platforms. Stable iterators aren't invalidated when the
-container is mutated.
+### Map and set implementation details
 
-| Container                                  | Empty size            | Per-item overhead | Stable iterators? | Insert/delete complexity     |
-|:------------------------------------------ |:--------------------- |:----------------- |:----------------- |:-----------------------------|
-| `std::map`, `std::set`                     | 16 bytes              | 32 bytes          | Yes               | O(log n)                     |
-| `std::unordered_map`, `std::unordered_set` | 128 bytes             | 16 - 24 bytes     | No                | O(1)                         |
-| `base::flat_map`, `base::flat_set`         | 24 bytes              | 0 (see notes)     | No                | O(n)                         |
-| `base::small_map`                          | 24 bytes (see notes)  | 32 bytes          | No                | depends on fallback map type |
+Sizes are on 64-bit platforms. Ordered iterators means that iteration occurs in
+the sorted key order. Stable iterators means that iterators are not invalidated
+by unrelated modifications to the container. Stable pointers means that pointers
+to keys and values are not invalidated by unrelated modifications to the
+container.
 
-**Takeaways:** `std::unordered_map` and `std::unordered_set` have high
-overhead for small container sizes, so prefer these only for larger workloads.
+The table lists the values for maps, but the same properties apply to the
+corresponding set types.
 
-Code size comparisons for a block of code (see appendix) on Windows using
-strings as keys.
 
-| Container            | Code size  |
-|:-------------------- |:---------- |
-| `std::unordered_map` | 1646 bytes |
-| `std::map`           | 1759 bytes |
-| `base::flat_map`     | 1872 bytes |
-| `base::small_map`    | 2410 bytes |
+| Container             | Empty size | Per-item overhead | Ordered iterators? | Stable iterators? | Stable pointers? | Lookup complexity | Mutate complexity |
+|:--------------------- |:---------- |:----------------- |:------------------ |:----------------- |:---------------- |:----------------- |:----------------- |
+| `std::map`            | 16 bytes   | 32 bytes          | Yes                | Yes               | Yes              | O(log n)          | O(log n)          |
+| `std::unordered_map`  | 128 bytes  | 16-24 bytes       | No                 | No                | Yes              | O(1)              | O(1)              |
+| `base::flat_map`      | 24 bytes   | 0 bytes           | Yes                | No                | No               | O(log n)          | O(n)              |
+| `absl::flat_hash_map` | 40 bytes   | 1 byte            | No                 | No                | No               | O(1)              | O(1)              |
+| `absl::node_hash_map` | 40 bytes   | 1 byte            | No                 | No                | Yes              | O(1)              | O(1)              |
 
-**Takeaways:** `base::small_map` generates more code because of the inlining of
-both brute-force and red-black tree searching. This makes it less attractive
-for random one-off uses. But if your code is called frequently, the runtime
-memory benefits will be more important. The code sizes of the other maps are
-close enough it's not worth worrying about.
+Note that all of these containers except for `std::map` have some additional
+memory overhead based on their load factor that isn't accounted for by their
+per-item overhead. This includes `base::flat_map` which doesn't have a hash
+table load factor but does have the `std::vector` equivalent, unused capacity
+from its double-on-resize allocation strategy.
 
 ### std::map and std::set
 
@@ -216,20 +224,43 @@
 Both `MakeFixedFlatSet` and `MakeFixedFlatMap` require callers to explicitly
 specify the key (and mapped) type.
 
-### base::small\_map
+### absl::flat\_hash\_map and absl::flat\_hash\_set
 
-A small inline buffer that is brute-force searched that overflows into a full
-`std::map` or `std::unordered_map`. This gives the memory benefit of
-`base::flat_map` for small data sizes without the degenerate insertion
-performance for large container sizes.
+A hash table. These use Abseil's "swiss table" design which is elaborated on in
+more detail at https://abseil.io/about/design/swisstables and
+https://abseil.io/docs/cpp/guides/container#hash-tables. The short version is
+that it uses an open addressing scheme with a lookup scheme that is designed to
+minimize memory accesses and branch mispredicts.
 
-Since instantiations require both code for a `std::map` and a brute-force search
-of the inline container, plus a fancy iterator to cover both cases, code size
-is larger.
+The flat hash map structures also store the key and value directly in the hash
+table slots, eliminating the need for additional memory allocations for
+inserting or removing individual nodes. The comes at the cost of eliminating
+pointer stability: unlike the standard library hash tables a rehash will not
+only invalidate all iterators but also all pointers to the stored elements.
 
-The initial size in the above table is assuming a very small inline table. The
-actual size will be `sizeof(int) + min(sizeof(std::map), sizeof(T) *
-inline_size)`.
+In practical use these Abseil containers perform well enough that they are a
+good default choice for a map or set container when you don't have any stronger
+constraints. In fact, even when you require value pointer-stability it is still
+generally better to wrap the value in a `std::unique_ptr` than to use an
+alternative structure that provides such stability directly.
+
+### absl::node\_hash\_map and absl::node\_hash\_set
+
+A variant of the Abseil hash maps that stores the key-value pair in a separately
+allocated node rather than directly in the hash table slots. This guarantees
+pointer-stability for both the keys and values in the table, invalidating them
+only when the element is deleted, but it comes at the cost of requiring an
+additional allocation for every element inserted.
+
+There are two main uses for this structure. One is for cases where you require a
+map with pointer-stability for the key (not the value), which cannot be done
+with the Abseil flat map or set. The other is for cases where you want a drop-in
+replacement for an existing `std::unordered_map` or `std::unordered_set` and you
+aren't sure if pointer-stability is required. If you know that pointer-stability
+is unnecessary then it would be better to convert to the flat tables but this
+may be difficult to prove when working on unfamiliar code or doing a large scale
+change. In such cases the node hash maps are still generally superior to the
+standard library maps.
 
 ## Deque
 
@@ -363,32 +394,3 @@
 Therefore, the minimal checks that we are adding to these base classes are the
 most efficient and effective way to achieve the beginning of the safety that we
 need. (Note that we cannot account for undefined behavior in callers.)
-
-## Appendix
-
-### Code for map code size comparison
-
-This just calls insert and query a number of times, with `printf`s that prevent
-things from being dead-code eliminated.
-
-```cpp
-TEST(Foo, Bar) {
-  base::small_map<std::map<std::string, Flubber>> foo;
-  foo.insert(std::make_pair("foo", Flubber(8, "bar")));
-  foo.insert(std::make_pair("bar", Flubber(8, "bar")));
-  foo.insert(std::make_pair("foo1", Flubber(8, "bar")));
-  foo.insert(std::make_pair("bar1", Flubber(8, "bar")));
-  foo.insert(std::make_pair("foo", Flubber(8, "bar")));
-  foo.insert(std::make_pair("bar", Flubber(8, "bar")));
-  auto found = foo.find("asdf");
-  printf("Found is %d\n", (int)(found == foo.end()));
-  found = foo.find("foo");
-  printf("Found is %d\n", (int)(found == foo.end()));
-  found = foo.find("bar");
-  printf("Found is %d\n", (int)(found == foo.end()));
-  found = foo.find("asdfhf");
-  printf("Found is %d\n", (int)(found == foo.end()));
-  found = foo.find("bar1");
-  printf("Found is %d\n", (int)(found == foo.end()));
-}
-```
diff --git a/tot/base/containers/adapters_unittest.cc b/tot/base/containers/adapters_unittest.cc
index d0cb9fc..ca58242 100644
--- a/tot/base/containers/adapters_unittest.cc
+++ b/tot/base/containers/adapters_unittest.cc
@@ -4,6 +4,7 @@
 
 #include "base/containers/adapters.h"
 
+#include <array>
 #include <ranges>
 #include <utility>
 #include <vector>
@@ -126,7 +127,7 @@
 }
 
 TEST(AdaptersTest, ReversedArray) {
-  int v[3] = {3, 2, 1};
+  std::array<int, 3> v = {3, 2, 1};
   int j = 0;
   for (int& i : base::Reversed(v)) {
     EXPECT_EQ(++j, i);
diff --git a/tot/base/containers/buffer_iterator_unittest.cc b/tot/base/containers/buffer_iterator_unittest.cc
index 27efd25..01b9e6e 100644
--- a/tot/base/containers/buffer_iterator_unittest.cc
+++ b/tot/base/containers/buffer_iterator_unittest.cc
@@ -77,9 +77,9 @@
   }
 }
 
-TEST(BufferIteratorTest, ObjectSizeOverflow) {
+TEST(BufferIteratorTest, ObjectDoesNotFit) {
   char buffer[64];
-  BufferIterator<char> iterator(buffer, std::numeric_limits<size_t>::max());
+  BufferIterator<char> iterator(buffer);
 
   auto* pointer = iterator.Object<uint64_t>();
   EXPECT_TRUE(pointer);
@@ -216,8 +216,7 @@
   for (int i = 0; i < kNumCopies; i++) {
     as_writable_bytes(span(buffer))
         .subspan(i * sizeof(TestStruct))
-        .first<sizeof(TestStruct)>()
-        .copy_from(byte_span_from_ref(expected));
+        .copy_prefix_from(byte_span_from_ref(expected));
   }
 
   BufferIterator<char> iterator(buffer);
@@ -239,8 +238,9 @@
   EXPECT_TRUE(iterator.Span<char>(4).empty());
 
   std::string result;
-  while (const char* c = iterator.Object<char>())
+  while (const char* c = iterator.Object<char>()) {
     result += *c;
+  }
   EXPECT_EQ(result, "cat");
 }
 
diff --git a/tot/base/containers/checked_iterators.h b/tot/base/containers/checked_iterators.h
index 312a8dd..3052bb2 100644
--- a/tot/base/containers/checked_iterators.h
+++ b/tot/base/containers/checked_iterators.h
@@ -1,6 +1,11 @@
 // Copyright 2018 The Chromium Authors
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
+//
+// This file intentionally uses the `CHECK()` macro instead of the `CHECK_op()`
+// macros, as `CHECK()` generates significantly less code and is more likely to
+// optimize reasonably, even in non-official release builds. Please do not
+// change the `CHECK()` calls back to `CHECK_op()` calls.
 
 #ifndef BASE_CONTAINERS_CHECKED_ITERATORS_H_
 #define BASE_CONTAINERS_CHECKED_ITERATORS_H_
@@ -49,7 +54,7 @@
   UNSAFE_BUFFER_USAGE constexpr CheckedContiguousIterator(T* start,
                                                           const T* end)
       : start_(start), current_(start), end_(end) {
-    CHECK_LE(start, end);
+    CHECK(start <= end);
   }
 
   // Constructs an iterator from `start` to `end`, starting at `current`.
@@ -64,8 +69,8 @@
                                                           T* current,
                                                           const T* end)
       : start_(start), current_(current), end_(end) {
-    CHECK_LE(start, current);
-    CHECK_LE(current, end);
+    CHECK(start <= current);
+    CHECK(current <= end);
   }
 
   constexpr CheckedContiguousIterator(const CheckedContiguousIterator& other) =
@@ -83,8 +88,8 @@
     // We explicitly don't delegate to the 3-argument constructor here. Its
     // CHECKs would be redundant, since we expect |other| to maintain its own
     // invariant. However, DCHECKs never hurt anybody. Presumably.
-    DCHECK_LE(other.start_, other.current_);
-    DCHECK_LE(other.current_, other.end_);
+    DCHECK(other.start_ <= other.current_);
+    DCHECK(other.current_ <= other.end_);
   }
 
   ~CheckedContiguousIterator() = default;
@@ -105,7 +110,7 @@
   }
 
   constexpr CheckedContiguousIterator& operator++() {
-    CHECK_NE(current_, end_);
+    CHECK(current_ != end_);
     // SAFETY: `current_ <= end_` is an invariant maintained internally, and the
     // CHECK above ensures that we are not at the end yet, so incrementing stays
     // in bounds of the allocation.
@@ -120,7 +125,7 @@
   }
 
   constexpr CheckedContiguousIterator& operator--() {
-    CHECK_NE(current_, start_);
+    CHECK(current_ != start_);
     // SAFETY: `current_ >= start_` is an invariant maintained internally, and
     // the CHECK above ensures that we are not at the start yet, so decrementing
     // stays in bounds of the allocation.
@@ -137,8 +142,8 @@
   constexpr CheckedContiguousIterator& operator+=(difference_type rhs) {
     // NOTE: Since the max allocation size is PTRDIFF_MAX (in our compilers),
     // subtracting two pointers from the same allocation can not underflow.
-    CHECK_LE(rhs, end_ - current_);
-    CHECK_GE(rhs, start_ - current_);
+    CHECK(rhs <= end_ - current_);
+    CHECK(rhs >= start_ - current_);
     // SAFETY: `current_ <= end_` is an invariant maintained internally. The
     // checks above ensure:
     // `start_ - current_ <= rhs <= end_ - current_`.
@@ -164,8 +169,8 @@
   constexpr CheckedContiguousIterator& operator-=(difference_type rhs) {
     // NOTE: Since the max allocation size is PTRDIFF_MAX (in our compilers),
     // subtracting two pointers from the same allocation can not underflow.
-    CHECK_GE(rhs, current_ - end_);
-    CHECK_LE(rhs, current_ - start_);
+    CHECK(rhs >= current_ - end_);
+    CHECK(rhs <= current_ - start_);
     // SAFETY: `start_ <= current_` is an invariant maintained internally. The
     // checks above ensure:
     // `current_ - end_ <= rhs <= current_ - start_`.
@@ -190,20 +195,20 @@
   }
 
   constexpr reference operator*() const {
-    CHECK_NE(current_, end_);
+    CHECK(current_ != end_);
     return *current_;
   }
 
   constexpr pointer operator->() const {
-    CHECK_NE(current_, end_);
+    CHECK(current_ != end_);
     return current_;
   }
 
   constexpr reference operator[](difference_type rhs) const {
     // NOTE: Since the max allocation size is PTRDIFF_MAX (in our compilers),
     // subtracting two pointers from the same allocation can not underflow.
-    CHECK_GE(rhs, start_ - current_);
-    CHECK_LT(rhs, end_ - current_);
+    CHECK(rhs >= start_ - current_);
+    CHECK(rhs < end_ - current_);
     // SAFETY: `start_ <= current_ <= end_` is an invariant maintained
     // internally. The checks above ensure:
     // `start_ - current_ <= rhs < end_ - current_`.
@@ -233,8 +238,8 @@
 
  private:
   constexpr void CheckComparable(const CheckedContiguousIterator& other) const {
-    CHECK_EQ(start_, other.start_);
-    CHECK_EQ(end_, other.end_);
+    CHECK(start_ == other.start_);
+    CHECK(end_ == other.end_);
   }
 
   // RAW_PTR_EXCLUSION: The embedding class is stack-scoped.
diff --git a/tot/base/containers/checked_iterators_unittest.cc b/tot/base/containers/checked_iterators_unittest.cc
index 0840182..a8905e8 100644
--- a/tot/base/containers/checked_iterators_unittest.cc
+++ b/tot/base/containers/checked_iterators_unittest.cc
@@ -9,7 +9,6 @@
 
 #include "base/check_op.h"
 #include "base/debug/alias.h"
-#include "base/ranges/algorithm.h"
 #include "base/test/gtest_util.h"
 #include "build/build_config.h"
 #include "testing/gtest/include/gtest/gtest.h"
@@ -215,7 +214,7 @@
   Iter out_end = std::copy(in_begin, in_end, out_begin);
   EXPECT_EQ(out_end, out_begin + (in_end - in_begin));
 
-  EXPECT_TRUE(ranges::equal(arr_in, arr_out));
+  EXPECT_TRUE(std::ranges::equal(arr_in, arr_out));
 }
 #endif  // defined(_LIBCPP_VERSION)
 
diff --git a/tot/base/containers/circular_deque.h b/tot/base/containers/circular_deque.h
index 1e46f21..7e8ff24 100644
--- a/tot/base/containers/circular_deque.h
+++ b/tot/base/containers/circular_deque.h
@@ -8,7 +8,6 @@
 #include <algorithm>
 #include <cstddef>
 #include <iterator>
-#include <type_traits>
 #include <utility>
 
 #include "base/check.h"
@@ -18,8 +17,7 @@
 #include "base/memory/raw_ptr_exclusion.h"
 #include "base/numerics/checked_math.h"
 #include "base/numerics/safe_conversions.h"
-#include "base/ranges/algorithm.h"
-#include "base/ranges/from_range.h"
+#include "base/types/cxx23_from_range.h"
 
 #if DCHECK_IS_ON()
 #include <ostream>
@@ -592,20 +590,19 @@
   // Requires that `first` and `last` are valid iterators into a container, with
   // `first <= last`.
   template <typename InputIterator>
-    requires(std::input_iterator<InputIterator>)
+    requires(std::forward_iterator<InputIterator>)
   UNSAFE_BUFFER_USAGE void assign(InputIterator first, InputIterator last) {
     // Possible future enhancement, dispatch on iterator tag type. For forward
     // iterators we can use std::difference to preallocate the space required
     // and only do one copy.
     ClearRetainCapacity();
-    while (first != last) {
+    // SAFETY: Pointers are iterators, so `first` may be a pointer. We require
+    // the caller to provide valid pointers such that `last` is for the same
+    // allocation and `first <= last`, and we've checked in the loop condition
+    // that `first != last` so incrementing will stay a valid pointer for the
+    // allocation.
+    for (; first != last; UNSAFE_BUFFERS(++first)) {
       emplace_back(*first);
-      // SAFETY: Pointers are iterators, so `first` may be a pointer. We require
-      // the caller to provide valid pointers such that `last` is for the same
-      // allocation and `first <= last`, and we've checked in the loop condition
-      // that `first != last` so incrementing will stay a valid pointer for the
-      // allocation.
-      UNSAFE_BUFFERS(++first);
     }
     IncrementGeneration();
   }
@@ -828,7 +825,7 @@
   }
 
   template <class InputIterator>
-    requires(std::input_iterator<InputIterator>)
+    requires(std::forward_iterator<InputIterator>)
   void insert(const_iterator pos, InputIterator first, InputIterator last) {
     ValidateIterator(pos);
 
@@ -1264,18 +1261,18 @@
 // Implementations of base::Erase[If] (see base/stl_util.h).
 template <class T, class Value>
 size_t Erase(circular_deque<T>& container, const Value& value) {
-  auto it = ranges::remove(container, value);
-  size_t removed = std::distance(it, container.end());
-  container.erase(it, container.end());
-  return removed;
+  auto removed = std::ranges::remove(container, value);
+  size_t num_removed = removed.size();
+  container.erase(removed.begin(), removed.end());
+  return num_removed;
 }
 
 template <class T, class Predicate>
 size_t EraseIf(circular_deque<T>& container, Predicate pred) {
-  auto it = ranges::remove_if(container, pred);
-  size_t removed = std::distance(it, container.end());
-  container.erase(it, container.end());
-  return removed;
+  auto removed = std::ranges::remove_if(container, pred);
+  size_t num_removed = removed.size();
+  container.erase(removed.begin(), removed.end());
+  return num_removed;
 }
 
 }  // namespace base
diff --git a/tot/base/containers/circular_deque_unittest.cc b/tot/base/containers/circular_deque_unittest.cc
index ebe8e7e..b18672d 100644
--- a/tot/base/containers/circular_deque_unittest.cc
+++ b/tot/base/containers/circular_deque_unittest.cc
@@ -43,7 +43,7 @@
 
 class DestructorCounter {
  public:
-  DestructorCounter(int* counter) : counter_(counter) {}
+  explicit DestructorCounter(int* counter) : counter_(counter) {}
   ~DestructorCounter() { ++(*counter_); }
 
  private:
@@ -116,7 +116,7 @@
   circular_deque<MoveOnlyInt> first(base::from_range, values);
 
   circular_deque<MoveOnlyInt> second(std::move(first));
-  EXPECT_TRUE(first.empty());
+  EXPECT_TRUE(first.empty());  // NOLINT(bugprone-use-after-move)
   EXPECT_EQ(6u, second.size());
   for (int i = 0; i < 6; i++) {
     EXPECT_EQ(i + 1, second[i].data());
@@ -192,7 +192,7 @@
   circular_deque<int> move;
   EXPECT_TRUE(move.empty());
   move = std::move(first);
-  EXPECT_TRUE(first.empty());
+  EXPECT_TRUE(first.empty());  // NOLINT(bugprone-use-after-move)
   EXPECT_EQ(6u, move.size());
   for (int i = 0; i < 6; i++) {
     EXPECT_EQ(i + 1, move[i]);
diff --git a/tot/base/containers/contains.h b/tot/base/containers/contains.h
index d263b30..4ae9925 100644
--- a/tot/base/containers/contains.h
+++ b/tot/base/containers/contains.h
@@ -5,25 +5,20 @@
 #ifndef BASE_CONTAINERS_CONTAINS_H_
 #define BASE_CONTAINERS_CONTAINS_H_
 
+// Provides `Contains()`, a general purpose utility to check whether a container
+// contains a value. This will probe whether a `contains` or `find` member
+// function on `container` exists, and fall back to a generic linear search over
+// `container`.
+
+#include <algorithm>
 #include <ranges>
 #include <type_traits>
 #include <utility>
-
-#include "base/ranges/algorithm.h"
 // TODO(dcheng): Remove this after fixing any IWYU errors.
-#include "base/ranges/ranges.h"
+#include <ranges>
 
 namespace base {
 
-namespace internal {
-
-// Small helper to detect whether a given type has a nested `key_type` typedef.
-// Used below to catch misuses of the API for associative containers.
-template <typename T>
-concept HasKeyType = requires { typename T::key_type; };
-
-}  // namespace internal
-
 // A general purpose utility to check whether `container` contains `value`. This
 // will probe whether a `contains` or `find` member function on `container`
 // exists, and fall back to a generic linear search over `container`.
@@ -39,22 +34,22 @@
     return container.find(value) != container.end();
   } else {
     static_assert(
-        !internal::HasKeyType<Container>,
+        !requires { typename Container::key_type; },
         "Error: About to perform linear search on an associative container. "
         "Either use a more generic comparator (e.g. std::less<>) or, if a "
         "linear search is desired, provide an explicit projection parameter.");
-    return ranges::find(container, value) != std::ranges::end(container);
+    return std::ranges::find(container, value) != std::ranges::end(container);
   }
 }
 
-// Overload that allows to provide an additional projection invocable. This
-// projection will be applied to every element in `container` before comparing
-// it with `value`. This will always perform a linear search.
+// Overload that allows callers to provide an additional projection invocable.
+// This projection will be applied to every element in `container` before
+// comparing it with `value`. This will always perform a linear search.
 template <typename Container, typename Value, typename Proj>
 constexpr bool Contains(const Container& container,
                         const Value& value,
                         Proj proj) {
-  return ranges::find(container, value, std::move(proj)) !=
+  return std::ranges::find(container, value, std::move(proj)) !=
          std::ranges::end(container);
 }
 
diff --git a/tot/base/containers/contains_nocompile.nc b/tot/base/containers/contains_nocompile.nc
index f588ae3..4a95c93 100644
--- a/tot/base/containers/contains_nocompile.nc
+++ b/tot/base/containers/contains_nocompile.nc
@@ -7,18 +7,17 @@
 
 #include <set>
 #include <string_view>
+#include <string>
 
 #include "base/containers/contains.h"
 
-
-
 namespace base {
 
 // The following code would perform a linear search through the set which is
 // likely unexpected and not intended. This is because the expression
 // `set.find(kFoo)` is ill-formed, since there is no implimit conversion from
 // std::string_view to `std::string`. This means Contains would fall back to the
-// general purpose `base::ranges::find(set, kFoo)` linear search.
+// general purpose `std::ranges::find(set, kFoo)` linear search.
 // To fix this clients can either use a more generic comparator like std::less<>
 // (in this case `set.find()` accepts any type that is comparable to a
 // std::string), or pass an explicit projection parameter to Contains, at which
diff --git a/tot/base/containers/enum_set.h b/tot/base/containers/enum_set.h
index 71830f3..6e4e0d1 100644
--- a/tot/base/containers/enum_set.h
+++ b/tot/base/containers/enum_set.h
@@ -16,6 +16,7 @@
 #include "base/check.h"
 #include "base/check_op.h"
 #include "base/memory/raw_ptr.h"
+#include "base/types/cxx23_to_underlying.h"
 #include "build/build_config.h"
 
 namespace base {
@@ -25,16 +26,16 @@
 class EnumSet;
 
 template <typename E, E Min, E Max>
-constexpr EnumSet<E, Min, Max> Union(EnumSet<E, Min, Max> set1,
-                                     EnumSet<E, Min, Max> set2);
+EnumSet<E, Min, Max> Union(EnumSet<E, Min, Max> set1,
+                           EnumSet<E, Min, Max> set2);
 
 template <typename E, E Min, E Max>
-constexpr EnumSet<E, Min, Max> Intersection(EnumSet<E, Min, Max> set1,
-                                            EnumSet<E, Min, Max> set2);
+EnumSet<E, Min, Max> Intersection(EnumSet<E, Min, Max> set1,
+                                  EnumSet<E, Min, Max> set2);
 
 template <typename E, E Min, E Max>
-constexpr EnumSet<E, Min, Max> Difference(EnumSet<E, Min, Max> set1,
-                                          EnumSet<E, Min, Max> set2);
+EnumSet<E, Min, Max> Difference(EnumSet<E, Min, Max> set1,
+                                EnumSet<E, Min, Max> set2);
 
 // An EnumSet is a set that can hold enum values between a min and a
 // max value (inclusive of both).  It's essentially a wrapper around
@@ -51,26 +52,24 @@
   static_assert(
       std::is_enum_v<E>,
       "First template parameter of EnumSet must be an enumeration type");
-  using enum_underlying_type = std::underlying_type_t<E>;
 
   static constexpr bool InRange(E value) {
     return (value >= MinEnumValue) && (value <= MaxEnumValue);
   }
 
-  static constexpr enum_underlying_type GetUnderlyingValue(E value) {
-    return static_cast<enum_underlying_type>(value);
-  }
-
  public:
   using EnumType = E;
   static const E kMinValue = MinEnumValue;
   static const E kMaxValue = MaxEnumValue;
   static const size_t kValueCount =
-      GetUnderlyingValue(kMaxValue) - GetUnderlyingValue(kMinValue) + 1;
+      to_underlying(kMaxValue) - to_underlying(kMinValue) + 1;
 
   static_assert(kMinValue <= kMaxValue,
                 "min value must be no greater than max value");
 
+  // Allow use with ::testing::ValuesIn, which expects a value_type defined.
+  using value_type = EnumType;
+
  private:
   // Declaration needed by Iterator.
   using EnumBitSet = std::bitset<kValueCount>;
@@ -228,37 +227,37 @@
 
   // Returns an EnumSet constructed from |bitmask|.
   static constexpr EnumSet FromEnumBitmask(const uint64_t bitmask) {
-    static_assert(GetUnderlyingValue(kMaxValue) < 64,
+    static_assert(to_underlying(kMaxValue) < 64,
                   "The highest enum value must be < 64 for FromEnumBitmask ");
-    static_assert(GetUnderlyingValue(kMinValue) >= 0,
+    static_assert(to_underlying(kMinValue) >= 0,
                   "The lowest enum value must be >= 0 for FromEnumBitmask ");
-    return EnumSet(EnumBitSet(bitmask >> GetUnderlyingValue(kMinValue)));
+    return EnumSet(EnumBitSet(bitmask >> to_underlying(kMinValue)));
   }
   // Returns a bitmask for the EnumSet.
   uint64_t ToEnumBitmask() const {
-    static_assert(GetUnderlyingValue(kMaxValue) < 64,
+    static_assert(to_underlying(kMaxValue) < 64,
                   "The highest enum value must be < 64 for ToEnumBitmask ");
-    static_assert(GetUnderlyingValue(kMinValue) >= 0,
+    static_assert(to_underlying(kMinValue) >= 0,
                   "The lowest enum value must be >= 0 for FromEnumBitmask ");
-    return enums_.to_ullong() << GetUnderlyingValue(kMinValue);
+    return enums_.to_ullong() << to_underlying(kMinValue);
   }
 
   // Returns a uint64_t bit mask representing the values within the range
   // [64*n, 64*n + 63] of the EnumSet.
   std::optional<uint64_t> GetNth64bitWordBitmask(size_t n) const {
     // If the EnumSet contains less than n 64-bit masks, return std::nullopt.
-    if (GetUnderlyingValue(kMaxValue) / 64 < n) {
+    if (to_underlying(kMaxValue) / 64 < n) {
       return std::nullopt;
     }
 
     std::bitset<kValueCount> mask = ~uint64_t{0};
     std::bitset<kValueCount> bits = enums_;
-    if (GetUnderlyingValue(kMinValue) < n * 64) {
-      bits >>= n * 64 - GetUnderlyingValue(kMinValue);
+    if (to_underlying(kMinValue) < n * 64) {
+      bits >>= n * 64 - to_underlying(kMinValue);
     }
     uint64_t result = (bits & mask).to_ullong();
-    if (GetUnderlyingValue(kMinValue) > n * 64) {
-      result <<= GetUnderlyingValue(kMinValue) - n * 64;
+    if (to_underlying(kMinValue) > n * 64) {
+      result <<= to_underlying(kMinValue) - n * 64;
     }
     return result;
   }
@@ -344,14 +343,12 @@
   std::string ToString() const { return enums_.to_string(); }
 
  private:
-  friend constexpr EnumSet Union<E, MinEnumValue, MaxEnumValue>(EnumSet set1,
-                                                                EnumSet set2);
-  friend constexpr EnumSet Intersection<E, MinEnumValue, MaxEnumValue>(
-      EnumSet set1,
-      EnumSet set2);
-  friend constexpr EnumSet Difference<E, MinEnumValue, MaxEnumValue>(
-      EnumSet set1,
-      EnumSet set2);
+  friend EnumSet Union<E, MinEnumValue, MaxEnumValue>(EnumSet set1,
+                                                      EnumSet set2);
+  friend EnumSet Intersection<E, MinEnumValue, MaxEnumValue>(EnumSet set1,
+                                                             EnumSet set2);
+  friend EnumSet Difference<E, MinEnumValue, MaxEnumValue>(EnumSet set1,
+                                                           EnumSet set2);
 
   static constexpr uint64_t bitstring(const std::initializer_list<E>& values) {
     uint64_t result = 0;
@@ -382,13 +379,13 @@
   // Converts a value to/from an index into |enums_|.
   static constexpr size_t ToIndex(E value) {
     CHECK(InRange(value));
-    return static_cast<size_t>(GetUnderlyingValue(value)) -
-           static_cast<size_t>(GetUnderlyingValue(MinEnumValue));
+    return static_cast<size_t>(to_underlying(value)) -
+           static_cast<size_t>(to_underlying(MinEnumValue));
   }
 
   static E FromIndex(size_t i) {
     DCHECK_LT(i, kValueCount);
-    return static_cast<E>(GetUnderlyingValue(MinEnumValue) + i);
+    return static_cast<E>(to_underlying(MinEnumValue) + i);
   }
 
   EnumBitSet enums_;
@@ -406,20 +403,20 @@
 // The usual set operations.
 
 template <typename E, E Min, E Max>
-constexpr EnumSet<E, Min, Max> Union(EnumSet<E, Min, Max> set1,
-                                     EnumSet<E, Min, Max> set2) {
+EnumSet<E, Min, Max> Union(EnumSet<E, Min, Max> set1,
+                           EnumSet<E, Min, Max> set2) {
   return EnumSet<E, Min, Max>(set1.enums_ | set2.enums_);
 }
 
 template <typename E, E Min, E Max>
-constexpr EnumSet<E, Min, Max> Intersection(EnumSet<E, Min, Max> set1,
-                                            EnumSet<E, Min, Max> set2) {
+EnumSet<E, Min, Max> Intersection(EnumSet<E, Min, Max> set1,
+                                  EnumSet<E, Min, Max> set2) {
   return EnumSet<E, Min, Max>(set1.enums_ & set2.enums_);
 }
 
 template <typename E, E Min, E Max>
-constexpr EnumSet<E, Min, Max> Difference(EnumSet<E, Min, Max> set1,
-                                          EnumSet<E, Min, Max> set2) {
+EnumSet<E, Min, Max> Difference(EnumSet<E, Min, Max> set1,
+                                EnumSet<E, Min, Max> set2) {
   return EnumSet<E, Min, Max>(set1.enums_ & ~set2.enums_);
 }
 
diff --git a/tot/base/containers/extend_unittest.cc b/tot/base/containers/extend_unittest.cc
index c5fc055..e586079 100644
--- a/tot/base/containers/extend_unittest.cc
+++ b/tot/base/containers/extend_unittest.cc
@@ -39,9 +39,9 @@
 static_assert(!std::is_copy_constructible_v<NonCopyable>, "");
 
 struct CopyableMovable {
-  bool copied_;
+  bool copied_ = false;
   char c_;
-  explicit CopyableMovable(char c) : copied_(false), c_(c) {}
+  explicit CopyableMovable(char c) : c_(c) {}
   CopyableMovable(const CopyableMovable& other) : copied_(true), c_(other.c_) {}
 
   CopyableMovable& operator=(const CopyableMovable&) = default;
@@ -57,46 +57,55 @@
 
 TEST(ExtendTest, ExtendWithMove) {
   std::vector<NonCopyable> dst;
-  for (char c : {'a', 'b', 'c', 'd'})
+  for (char c : {'a', 'b', 'c', 'd'}) {
     dst.emplace_back(c);
+  }
   std::vector<NonCopyable> src;
-  for (char c : {'e', 'f', 'g'})
+  for (char c : {'e', 'f', 'g'}) {
     src.emplace_back(c);
+  }
   std::vector<NonCopyable> expected;
-  for (char c : {'a', 'b', 'c', 'd', 'e', 'f', 'g'})
+  for (char c : {'a', 'b', 'c', 'd', 'e', 'f', 'g'}) {
     expected.emplace_back(c);
+  }
 
   Extend(dst, std::move(src));
   EXPECT_EQ(dst, expected);
-  EXPECT_TRUE(src.empty());
+  EXPECT_TRUE(src.empty());  // NOLINT(bugprone-use-after-move)
 }
 
 TEST(ExtendTest, ExtendCopyableWithMove) {
   std::vector<CopyableMovable> dst;
-  for (char c : {'a', 'b', 'c', 'd'})
+  for (char c : {'a', 'b', 'c', 'd'}) {
     dst.emplace_back(c);
+  }
   std::vector<CopyableMovable> src;
-  for (char c : {'e', 'f', 'g'})
+  for (char c : {'e', 'f', 'g'}) {
     src.emplace_back(c);
+  }
   std::vector<CopyableMovable> expected;
-  for (char c : {'a', 'b', 'c', 'd', 'e', 'f', 'g'})
+  for (char c : {'a', 'b', 'c', 'd', 'e', 'f', 'g'}) {
     expected.emplace_back(c);
+  }
 
   Extend(dst, std::move(src));
   EXPECT_EQ(dst, expected);
-  EXPECT_TRUE(src.empty());
+  EXPECT_TRUE(src.empty());  // NOLINT(bugprone-use-after-move)
 }
 
 TEST(ExtendTest, ExtendWithCopy) {
   std::vector<CopyableMovable> dst;
-  for (char c : {'a', 'b', 'c', 'd'})
+  for (char c : {'a', 'b', 'c', 'd'}) {
     dst.emplace_back(c);
+  }
   std::vector<CopyableMovable> src;
-  for (char c : {'e', 'f', 'g'})
+  for (char c : {'e', 'f', 'g'}) {
     src.emplace_back(c);
+  }
   std::vector<CopyableMovable> expected;
-  for (char c : {'a', 'b', 'c', 'd', 'e', 'f', 'g'})
+  for (char c : {'a', 'b', 'c', 'd', 'e', 'f', 'g'}) {
     expected.emplace_back(c);
+  }
 
   EXPECT_FALSE(dst[0].copied_);
   Extend(dst, src);
diff --git a/tot/base/containers/fixed_flat_map.h b/tot/base/containers/fixed_flat_map.h
index 62c9c8a..6c05d60 100644
--- a/tot/base/containers/fixed_flat_map.h
+++ b/tot/base/containers/fixed_flat_map.h
@@ -102,7 +102,7 @@
 // Example usage:
 //   constexpr auto kMap = base::MakeFixedFlatMap<std::string_view, int>(
 //       {{"foo", 1}, {"bar", 2}, {"baz", 3}});
-template <class Key, class Mapped, size_t N, class Compare = std::less<>>
+template <class Key, class Mapped, class Compare = std::less<>, size_t N>
 consteval fixed_flat_map<Key, Mapped, N, Compare> MakeFixedFlatMap(
     std::pair<Key, Mapped> (&&data)[N],
     const Compare& comp = Compare()) {
diff --git a/tot/base/containers/fixed_flat_map_unittest.cc b/tot/base/containers/fixed_flat_map_unittest.cc
index e5016a2..845742a 100644
--- a/tot/base/containers/fixed_flat_map_unittest.cc
+++ b/tot/base/containers/fixed_flat_map_unittest.cc
@@ -4,10 +4,10 @@
 
 #include "base/containers/fixed_flat_map.h"
 
+#include <algorithm>
 #include <string>
 #include <string_view>
 
-#include "base/ranges/algorithm.h"
 #include "base/test/gtest_util.h"
 #include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
@@ -37,8 +37,8 @@
 TEST(FixedFlatMapTest, MakeFixedFlatMap_SortedInput) {
   constexpr auto kSquares =
       MakeFixedFlatMap<int, int>({{1, 1}, {2, 4}, {3, 9}, {4, 16}});
-  static_assert(ranges::is_sorted(kSquares), "Error: Map is not sorted.");
-  static_assert(ranges::adjacent_find(kSquares) == kSquares.end(),
+  static_assert(std::ranges::is_sorted(kSquares), "Error: Map is not sorted.");
+  static_assert(std::ranges::adjacent_find(kSquares) == kSquares.end(),
                 "Error: Map contains repeated elements.");
   EXPECT_THAT(kSquares,
               ElementsAre(Pair(1, 1), Pair(2, 4), Pair(3, 9), Pair(4, 16)));
@@ -47,8 +47,8 @@
 TEST(FixedFlatMapTest, MakeFixedFlatMap_UnsortedInput) {
   constexpr auto kMap = MakeFixedFlatMap<std::string_view, int>(
       {{"foo", 1}, {"bar", 2}, {"baz", 3}});
-  static_assert(ranges::is_sorted(kMap), "Error: Map is not sorted.");
-  static_assert(ranges::adjacent_find(kMap) == kMap.end(),
+  static_assert(std::ranges::is_sorted(kMap), "Error: Map is not sorted.");
+  static_assert(std::ranges::adjacent_find(kMap) == kMap.end(),
                 "Error: Map contains repeated elements.");
   EXPECT_THAT(kMap,
               ElementsAre(Pair("bar", 2), Pair("baz", 3), Pair("foo", 1)));
diff --git a/tot/base/containers/fixed_flat_set.h b/tot/base/containers/fixed_flat_set.h
index c6abe91..87b453c 100644
--- a/tot/base/containers/fixed_flat_set.h
+++ b/tot/base/containers/fixed_flat_set.h
@@ -116,7 +116,7 @@
 //
 // Note: Wrapping `Key` in `std::common_type_t` below requires callers to
 // explicitly specify `Key`, which is desired here.
-template <class Key, size_t N, class Compare = std::less<>>
+template <class Key, class Compare = std::less<>, size_t N>
 consteval fixed_flat_set<Key, N, Compare> MakeFixedFlatSet(
     std::common_type_t<Key> (&&data)[N],
     const Compare& comp = Compare()) {
diff --git a/tot/base/containers/fixed_flat_set_unittest.cc b/tot/base/containers/fixed_flat_set_unittest.cc
index 6fc4e06..b5b3b34 100644
--- a/tot/base/containers/fixed_flat_set_unittest.cc
+++ b/tot/base/containers/fixed_flat_set_unittest.cc
@@ -4,9 +4,9 @@
 
 #include "base/containers/fixed_flat_set.h"
 
+#include <algorithm>
 #include <string_view>
 
-#include "base/ranges/algorithm.h"
 #include "base/test/gtest_util.h"
 #include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
@@ -15,8 +15,8 @@
 
 TEST(FixedFlatSetTest, MakeFixedFlatSet_SortedInput) {
   constexpr auto kSet = MakeFixedFlatSet<int>({1, 2, 3, 4});
-  static_assert(ranges::is_sorted(kSet), "Error: Set is not sorted.");
-  static_assert(ranges::adjacent_find(kSet) == kSet.end(),
+  static_assert(std::ranges::is_sorted(kSet), "Error: Set is not sorted.");
+  static_assert(std::ranges::adjacent_find(kSet) == kSet.end(),
                 "Error: Set contains repeated elements.");
   EXPECT_THAT(kSet, ::testing::ElementsAre(1, 2, 3, 4));
 }
@@ -24,8 +24,8 @@
 TEST(FixedFlatSetTest, MakeFixedFlatSet_UnsortedInput) {
   constexpr auto kSet =
       MakeFixedFlatSet<std::string_view>({"foo", "bar", "baz"});
-  static_assert(ranges::is_sorted(kSet), "Error: Set is not sorted.");
-  static_assert(ranges::adjacent_find(kSet) == kSet.end(),
+  static_assert(std::ranges::is_sorted(kSet), "Error: Set is not sorted.");
+  static_assert(std::ranges::adjacent_find(kSet) == kSet.end(),
                 "Error: Set contains repeated elements.");
   EXPECT_THAT(kSet, ::testing::ElementsAre("bar", "baz", "foo"));
 }
diff --git a/tot/base/containers/flat_map.h b/tot/base/containers/flat_map.h
index 42a51c4..25158d4 100644
--- a/tot/base/containers/flat_map.h
+++ b/tot/base/containers/flat_map.h
@@ -280,8 +280,9 @@
 auto flat_map<Key, Mapped, Compare, Container>::operator[](const key_type& key)
     -> mapped_type& {
   iterator found = tree::lower_bound(key);
-  if (found == tree::end() || tree::key_comp()(key, found->first))
+  if (found == tree::end() || tree::key_comp()(key, found->first)) {
     found = tree::unsafe_emplace(found, key, mapped_type());
+  }
   return found->second;
 }
 
@@ -289,8 +290,9 @@
 auto flat_map<Key, Mapped, Compare, Container>::operator[](key_type&& key)
     -> mapped_type& {
   iterator found = tree::lower_bound(key);
-  if (found == tree::end() || tree::key_comp()(key, found->first))
+  if (found == tree::end() || tree::key_comp()(key, found->first)) {
     found = tree::unsafe_emplace(found, std::move(key), mapped_type());
+  }
   return found->second;
 }
 
@@ -301,8 +303,9 @@
     -> std::pair<iterator, bool> {
   auto result =
       tree::emplace_key_args(key, std::forward<K>(key), std::forward<M>(obj));
-  if (!result.second)
+  if (!result.second) {
     result.first->second = std::forward<M>(obj);
+  }
   return result;
 }
 
@@ -314,8 +317,9 @@
     M&& obj) -> iterator {
   auto result = tree::emplace_hint_key_args(hint, key, std::forward<K>(key),
                                             std::forward<M>(obj));
-  if (!result.second)
+  if (!result.second) {
     result.first->second = std::forward<M>(obj);
+  }
   return result.first;
 }
 
@@ -376,8 +380,8 @@
     const Projection& proj = Projection()) {
   Container elements;
   internal::ReserveIfSupported(elements, unprojected_elements);
-  base::ranges::transform(unprojected_elements, std::back_inserter(elements),
-                          proj);
+  std::ranges::transform(unprojected_elements, std::back_inserter(elements),
+                         proj);
   return flat_map<Key, Mapped, KeyCompare, Container>(std::move(elements),
                                                       comp);
 }
diff --git a/tot/base/containers/flat_map_unittest.cc b/tot/base/containers/flat_map_unittest.cc
index ba2941c..cd13e77 100644
--- a/tot/base/containers/flat_map_unittest.cc
+++ b/tot/base/containers/flat_map_unittest.cc
@@ -4,13 +4,13 @@
 
 #include "base/containers/flat_map.h"
 
+#include <algorithm>
 #include <string>
 #include <string_view>
 #include <type_traits>
 #include <utility>
 #include <vector>
 
-#include "base/ranges/algorithm.h"
 #include "base/test/move_only_int.h"
 #include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
@@ -261,8 +261,8 @@
   EXPECT_EQ(22, result.first->second.data());
   EXPECT_TRUE(result.second);
   EXPECT_EQ(1u, m.size());
-  EXPECT_EQ(0, key.data());  // moved from
-  EXPECT_EQ(0, val.data());  // moved from
+  EXPECT_EQ(0, key.data());  // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(0, val.data());  // NOLINT(bugprone-use-after-move)
 
   // Second call with same key should result in an assignment, overwriting the
   // old value. Assignment should be indicated by setting the second pair member
@@ -275,14 +275,14 @@
   EXPECT_EQ(44, result.first->second.data());
   EXPECT_FALSE(result.second);
   EXPECT_EQ(1u, m.size());
-  EXPECT_EQ(1, key.data());  // not moved from
-  EXPECT_EQ(0, val.data());  // moved from
+  EXPECT_EQ(1, key.data());  // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(0, val.data());  // NOLINT(bugprone-use-after-move)
 
   // Check that random insertion results in sorted range.
   base::flat_map<MoveOnlyInt, int> map;
   for (int i : {3, 1, 5, 6, 8, 7, 0, 9, 4, 2}) {
     map.insert_or_assign(MoveOnlyInt(i), i);
-    EXPECT_TRUE(ranges::is_sorted(map));
+    EXPECT_TRUE(std::ranges::is_sorted(map));
   }
 }
 
@@ -298,8 +298,8 @@
   EXPECT_EQ(1, result->first.data());
   EXPECT_EQ(22, result->second.data());
   EXPECT_EQ(1u, m.size());
-  EXPECT_EQ(0, key.data());  // moved from
-  EXPECT_EQ(0, val.data());  // moved from
+  EXPECT_EQ(0, key.data());  // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(0, val.data());  // NOLINT(bugprone-use-after-move)
 
   // Second call with same key should result in an assignment, overwriting the
   // old value. Only the inserted value should be moved from, the key should be
@@ -310,14 +310,14 @@
   EXPECT_EQ(1, result->first.data());
   EXPECT_EQ(44, result->second.data());
   EXPECT_EQ(1u, m.size());
-  EXPECT_EQ(1, key.data());  // not moved from
-  EXPECT_EQ(0, val.data());  // moved from
+  EXPECT_EQ(1, key.data());  // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(0, val.data());  // NOLINT(bugprone-use-after-move)
 
   // Check that random insertion results in sorted range.
   base::flat_map<MoveOnlyInt, int> map;
   for (int i : {3, 1, 5, 6, 8, 7, 0, 9, 4, 2}) {
     map.insert_or_assign(map.end(), MoveOnlyInt(i), i);
-    EXPECT_TRUE(ranges::is_sorted(map));
+    EXPECT_TRUE(std::ranges::is_sorted(map));
   }
 }
 
@@ -338,9 +338,9 @@
   EXPECT_EQ(44, result.first->second.second.data());
   EXPECT_TRUE(result.second);
   EXPECT_EQ(1u, m.size());
-  EXPECT_EQ(0, key.data());   // moved from
-  EXPECT_EQ(0, val1.data());  // moved from
-  EXPECT_EQ(0, val2.data());  // moved from
+  EXPECT_EQ(0, key.data());   // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(0, val1.data());  // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(0, val2.data());  // NOLINT(bugprone-use-after-move)
 
   // Second call with same key should result in a no-op, returning an iterator
   // to the existing element and returning false as the second pair member.
@@ -362,7 +362,7 @@
   base::flat_map<MoveOnlyInt, int> map;
   for (int i : {3, 1, 5, 6, 8, 7, 0, 9, 4, 2}) {
     map.try_emplace(MoveOnlyInt(i), i);
-    EXPECT_TRUE(ranges::is_sorted(map));
+    EXPECT_TRUE(std::ranges::is_sorted(map));
   }
 }
 
@@ -383,9 +383,9 @@
   EXPECT_EQ(22, result->second.first.data());
   EXPECT_EQ(44, result->second.second.data());
   EXPECT_EQ(1u, m.size());
-  EXPECT_EQ(0, key.data());   // moved from
-  EXPECT_EQ(0, val1.data());  // moved from
-  EXPECT_EQ(0, val2.data());  // moved from
+  EXPECT_EQ(0, key.data());   // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(0, val1.data());  // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(0, val2.data());  // NOLINT(bugprone-use-after-move)
 
   // Second call with same key should result in a no-op, returning an iterator
   // to the existing element. Key and values that were attempted to be inserted
@@ -408,7 +408,7 @@
   base::flat_map<MoveOnlyInt, int> map;
   for (int i : {3, 1, 5, 6, 8, 7, 0, 9, 4, 2}) {
     map.try_emplace(map.end(), MoveOnlyInt(i), i);
-    EXPECT_TRUE(ranges::is_sorted(map));
+    EXPECT_TRUE(std::ranges::is_sorted(map));
   }
 }
 
diff --git a/tot/base/containers/flat_set.h b/tot/base/containers/flat_set.h
index b418941..5cd3a82 100644
--- a/tot/base/containers/flat_set.h
+++ b/tot/base/containers/flat_set.h
@@ -5,11 +5,11 @@
 #ifndef BASE_CONTAINERS_FLAT_SET_H_
 #define BASE_CONTAINERS_FLAT_SET_H_
 
+#include <algorithm>
 #include <functional>
 #include <vector>
 
 #include "base/containers/flat_tree.h"
-#include "base/ranges/algorithm.h"
 
 namespace base {
 
@@ -174,8 +174,8 @@
     const Projection& proj = Projection()) {
   Container elements;
   internal::ReserveIfSupported(elements, unprojected_elements);
-  base::ranges::transform(unprojected_elements, std::back_inserter(elements),
-                          proj);
+  std::ranges::transform(unprojected_elements, std::back_inserter(elements),
+                         proj);
   return flat_set<Key, Compare, Container>(std::move(elements), comp);
 }
 
diff --git a/tot/base/containers/flat_tree.h b/tot/base/containers/flat_tree.h
index 26564d7..937ed6b 100644
--- a/tot/base/containers/flat_tree.h
+++ b/tot/base/containers/flat_tree.h
@@ -20,7 +20,6 @@
 #include "base/compiler_specific.h"
 #include "base/containers/span.h"
 #include "base/memory/raw_ptr_exclusion.h"
-#include "base/ranges/algorithm.h"
 
 namespace base {
 
@@ -41,7 +40,7 @@
   // Being unique implies that there are no adjacent elements that
   // compare equal. So this checks that each element is strictly less
   // than the element after it.
-  return ranges::adjacent_find(range, std::not_fn(comp)) ==
+  return std::ranges::adjacent_find(range, std::not_fn(comp)) ==
          std::ranges::end(range);
 }
 
@@ -431,8 +430,9 @@
   std::pair<iterator, bool> insert_or_assign(V&& val) {
     auto position = lower_bound(GetKeyFromValue()(val));
 
-    if (position == end() || value_comp()(val, *position))
+    if (position == end() || value_comp()(val, *position)) {
       return {body_.emplace(position, std::forward<V>(val)), true};
+    }
 
     *position = std::forward<V>(val);
     return {position, false};
@@ -989,8 +989,9 @@
   auto lower = lower_bound(key);
 
   KeyValueCompare comp(comp_);
-  if (lower == end() || comp(key, *lower))
+  if (lower == end() || comp(key, *lower)) {
     return {lower, lower};
+  }
 
   return {lower, std::next(lower)};
 }
@@ -1010,8 +1011,9 @@
   auto lower = lower_bound(key);
 
   KeyValueCompare comp(comp_);
-  if (lower == end() || comp(key, *lower))
+  if (lower == end() || comp(key, *lower)) {
     return {lower, lower};
+  }
 
   return {lower, std::next(lower)};
 }
@@ -1026,7 +1028,7 @@
 auto flat_tree<Key, GetKeyFromValue, KeyCompare, Container>::lower_bound(
     const Key& key) const -> const_iterator {
   KeyValueCompare comp(comp_);
-  return ranges::lower_bound(*this, key, comp);
+  return std::ranges::lower_bound(*this, key, comp);
 }
 
 template <class Key, class GetKeyFromValue, class KeyCompare, class Container>
@@ -1047,7 +1049,7 @@
   const KeyTypeOrK<K>& key_ref = key;
 
   KeyValueCompare comp(comp_);
-  return ranges::lower_bound(*this, key_ref, comp);
+  return std::ranges::lower_bound(*this, key_ref, comp);
 }
 
 template <class Key, class GetKeyFromValue, class KeyCompare, class Container>
@@ -1060,7 +1062,7 @@
 auto flat_tree<Key, GetKeyFromValue, KeyCompare, Container>::upper_bound(
     const Key& key) const -> const_iterator {
   KeyValueCompare comp(comp_);
-  return ranges::upper_bound(*this, key, comp);
+  return std::ranges::upper_bound(*this, key, comp);
 }
 
 template <class Key, class GetKeyFromValue, class KeyCompare, class Container>
@@ -1081,7 +1083,7 @@
   const KeyTypeOrK<K>& key_ref = key;
 
   KeyValueCompare comp(comp_);
-  return ranges::upper_bound(*this, key_ref, comp);
+  return std::ranges::upper_bound(*this, key_ref, comp);
 }
 
 // ----------------------------------------------------------------------------
@@ -1107,8 +1109,9 @@
     const K& key,
     Args&&... args) -> std::pair<iterator, bool> {
   auto lower = lower_bound(key);
-  if (lower == end() || comp_(key, GetKeyFromValue()(*lower)))
+  if (lower == end() || comp_(key, GetKeyFromValue()(*lower))) {
     return {unsafe_emplace(lower, std::forward<Args>(args)...), true};
+  }
   return {lower, false};
 }
 
@@ -1147,10 +1150,10 @@
     base::internal::flat_tree<Key, GetKeyFromValue, KeyCompare, Container>&
         container,
     Predicate pred) {
-  auto it = ranges::remove_if(container, pred);
-  size_t removed = std::distance(it, container.end());
-  container.erase(it, container.end());
-  return removed;
+  auto removed = std::ranges::remove_if(container, pred);
+  size_t num_removed = removed.size();
+  container.erase(removed.begin(), removed.end());
+  return num_removed;
 }
 
 }  // namespace base
diff --git a/tot/base/containers/flat_tree_unittest.cc b/tot/base/containers/flat_tree_unittest.cc
index 8c629e3..5bd62bc 100644
--- a/tot/base/containers/flat_tree_unittest.cc
+++ b/tot/base/containers/flat_tree_unittest.cc
@@ -33,6 +33,7 @@
 // * No tests with min_allocator and no tests counting allocations.
 //   Flat sets currently don't support allocators.
 
+#include <algorithm>
 #include <deque>
 #include <forward_list>
 #include <functional>
@@ -41,14 +42,12 @@
 #include <string>
 #include <vector>
 
-#include "base/ranges/algorithm.h"
 #include "base/test/gtest_util.h"
 #include "base/test/move_only_int.h"
 #include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
-namespace base {
-namespace internal {
+namespace base::internal {
 
 namespace {
 
@@ -127,7 +126,7 @@
 
 struct TemplateConstructor {
   template <typename T>
-  TemplateConstructor(const T&) {}
+  explicit TemplateConstructor(const T&) {}
 
   friend bool operator<(const TemplateConstructor&,
                         const TemplateConstructor&) {
@@ -173,7 +172,7 @@
                                   std::less<>,
                                   std::vector<Emplaceable>>;
 using ReversedTree =
-    flat_tree<int, std::identity, std::greater<int>, std::vector<int>>;
+    flat_tree<int, std::identity, std::greater<>, std::vector<int>>;
 
 using TreeWithStrangeCompare = flat_tree<int,
                                          std::identity,
@@ -219,7 +218,7 @@
 
 TEST(FlatTree, IncompleteType) {
   struct A {
-    using Tree = flat_tree<A, std::identity, std::less<A>, std::vector<A>>;
+    using Tree = flat_tree<A, std::identity, std::less<>, std::vector<A>>;
     int data;
     Tree set_with_incomplete_type;
     Tree::iterator it;
@@ -241,8 +240,8 @@
   Tree cont({{0, 0}, {1, 0}, {0, 1}, {2, 0}, {0, 2}, {1, 1}});
 
   auto AllOfSecondsAreZero = [&cont] {
-    return ranges::all_of(cont,
-                          [](const Pair& elem) { return elem.second == 0; });
+    return std::ranges::all_of(
+        cont, [](const Pair& elem) { return elem.second == 0; });
   };
 
   EXPECT_TRUE(AllOfSecondsAreZero()) << "constructor should be stable";
@@ -378,9 +377,9 @@
   // first item, the second allows us to test for stability. Using a move
   // only type to ensure the vector is not copied.
   std::vector<Pair> storage;
-  storage.push_back(Pair(2, MoveOnlyInt(0)));
-  storage.push_back(Pair(1, MoveOnlyInt(0)));
-  storage.push_back(Pair(2, MoveOnlyInt(1)));
+  storage.emplace_back(2, MoveOnlyInt(0));
+  storage.emplace_back(1, MoveOnlyInt(0));
+  storage.emplace_back(2, MoveOnlyInt(1));
 
   using Tree =
       flat_tree<Pair, std::identity, LessByFirst<Pair>, std::vector<Pair>>;
@@ -462,8 +461,8 @@
   using Pair = std::pair<int, MoveOnlyInt>;
 
   std::vector<Pair> storage;
-  storage.push_back(Pair(1, MoveOnlyInt(0)));
-  storage.push_back(Pair(2, MoveOnlyInt(0)));
+  storage.emplace_back(1, MoveOnlyInt(0));
+  storage.emplace_back(2, MoveOnlyInt(0));
 
   using Tree =
       flat_tree<Pair, std::identity, LessByFirst<Pair>, std::vector<Pair>>;
@@ -798,8 +797,8 @@
     }
   };
 
-  using IntIntMap = flat_tree<int, GetKeyFromIntIntPair, std::less<int>,
-                              std::vector<IntPair>>;
+  using IntIntMap =
+      flat_tree<int, GetKeyFromIntIntPair, std::less<>, std::vector<IntPair>>;
 
   {
     IntIntMap cont;
@@ -862,8 +861,8 @@
     }
   };
 
-  using IntIntMap = flat_tree<int, GetKeyFromIntIntPair, std::less<int>,
-                              std::vector<IntPair>>;
+  using IntIntMap =
+      flat_tree<int, GetKeyFromIntIntPair, std::less<>, std::vector<IntPair>>;
 
   {
     IntIntMap cont;
@@ -997,7 +996,7 @@
   cont.emplace(4);
 
   TypeParam body = std::move(cont).extract();
-  EXPECT_THAT(cont, IsEmpty());
+  EXPECT_THAT(cont, IsEmpty());  // NOLINT(bugprone-use-after-move)
   EXPECT_THAT(body, ElementsAre(1, 2, 3, 4));
 }
 
@@ -1061,8 +1060,9 @@
     T v(0);
 
     auto it = cont.find(v);
-    if (it != cont.end())
+    if (it != cont.end()) {
       cont.erase(it);
+    }
   }
 }
 
@@ -1146,10 +1146,10 @@
 TEST(FlatTree, KeyComp) {
   ReversedTree cont({1, 2, 3, 4, 5});
 
-  EXPECT_TRUE(ranges::is_sorted(cont, cont.key_comp()));
+  EXPECT_TRUE(std::ranges::is_sorted(cont, cont.key_comp()));
   int new_elements[] = {6, 7, 8, 9, 10};
-  ranges::copy(new_elements, std::inserter(cont, cont.end()));
-  EXPECT_TRUE(ranges::is_sorted(cont, cont.key_comp()));
+  std::ranges::copy(new_elements, std::inserter(cont, cont.end()));
+  EXPECT_TRUE(std::ranges::is_sorted(cont, cont.key_comp()));
 }
 
 // value_compare value_comp() const
@@ -1157,10 +1157,10 @@
 TEST(FlatTree, ValueComp) {
   ReversedTree cont({1, 2, 3, 4, 5});
 
-  EXPECT_TRUE(ranges::is_sorted(cont, cont.value_comp()));
+  EXPECT_TRUE(std::ranges::is_sorted(cont, cont.value_comp()));
   int new_elements[] = {6, 7, 8, 9, 10};
-  ranges::copy(new_elements, std::inserter(cont, cont.end()));
-  EXPECT_TRUE(ranges::is_sorted(cont, cont.value_comp()));
+  std::ranges::copy(new_elements, std::inserter(cont, cont.end()));
+  EXPECT_TRUE(std::ranges::is_sorted(cont, cont.value_comp()));
 }
 
 // ----------------------------------------------------------------------------
@@ -1587,5 +1587,4 @@
     ::testing::Types<std::deque<int>, std::vector<int>>;
 INSTANTIATE_TYPED_TEST_SUITE_P(My, FlatTreeTest, IntSequenceContainers);
 
-}  // namespace internal
-}  // namespace base
+}  // namespace base::internal
diff --git a/tot/base/containers/heap_array.h b/tot/base/containers/heap_array.h
index 867855c..d8e5c2b 100644
--- a/tot/base/containers/heap_array.h
+++ b/tot/base/containers/heap_array.h
@@ -11,6 +11,7 @@
 #include <type_traits>
 #include <utility>
 
+#include "base/check_op.h"
 #include "base/compiler_specific.h"
 #include "base/containers/span.h"
 
@@ -125,21 +126,27 @@
   iterator end() LIFETIME_BOUND { return as_span().end(); }
   const_iterator end() const LIFETIME_BOUND { return as_span().end(); }
 
-  T& operator[](size_t idx) LIFETIME_BOUND { return as_span()[idx]; }
-  const T& operator[](size_t idx) const LIFETIME_BOUND {
-    return as_span()[idx];
+  ALWAYS_INLINE T& operator[](size_t idx) LIFETIME_BOUND {
+    CHECK_LT(idx, size_);
+    // SAFETY: bounds checked above.
+    return UNSAFE_BUFFERS(data_.get()[idx]);
+  }
+  ALWAYS_INLINE const T& operator[](size_t idx) const LIFETIME_BOUND {
+    CHECK_LT(idx, size_);
+    // SAFETY: bounds checked above.
+    return UNSAFE_BUFFERS(data_.get()[idx]);
   }
 
   // Access the HeapArray via spans. Note that span<T> is implicilty
   // constructible from HeapArray<T>, so an explicit call to .as_span() is
   // most useful, say, when the compiler can't deduce a template
   // argument type.
-  base::span<T> as_span() LIFETIME_BOUND {
+  ALWAYS_INLINE base::span<T> as_span() LIFETIME_BOUND {
     // SAFETY: `size_` is the number of elements in the `data_` allocation` at
     // all times.
     return UNSAFE_BUFFERS(base::span<T>(data_.get(), size_));
   }
-  base::span<const T> as_span() const LIFETIME_BOUND {
+  ALWAYS_INLINE base::span<const T> as_span() const LIFETIME_BOUND {
     // SAFETY: `size_` is the number of elements in the `data_` allocation` at
     // all times.
     return UNSAFE_BUFFERS(base::span<const T>(data_.get(), size_));
@@ -162,13 +169,17 @@
   // If `count` is unspecified, all remaining elements are included. A CHECK()
   // occurs if any of the parameters results in an out-of-range position in
   // the HeapArray.
-  base::span<T> subspan(size_t offset,
-                        size_t count = base::dynamic_extent) LIFETIME_BOUND {
+  base::span<T> subspan(size_t offset) LIFETIME_BOUND {
+    return as_span().subspan(offset);
+  }
+  base::span<const T> subspan(size_t offset) const LIFETIME_BOUND {
+    return as_span().subspan(offset);
+  }
+  base::span<T> subspan(size_t offset, size_t count) LIFETIME_BOUND {
     return as_span().subspan(offset, count);
   }
   base::span<const T> subspan(size_t offset,
-                              size_t count = base::dynamic_extent) const
-      LIFETIME_BOUND {
+                              size_t count) const LIFETIME_BOUND {
     return as_span().subspan(offset, count);
   }
 
diff --git a/tot/base/containers/heap_array_unittest.cc b/tot/base/containers/heap_array_unittest.cc
index 6b7752c..e984340 100644
--- a/tot/base/containers/heap_array_unittest.cc
+++ b/tot/base/containers/heap_array_unittest.cc
@@ -75,8 +75,8 @@
   base::HeapArray<uint32_t> vec(std::move(that));
   EXPECT_EQ(vec.size(), 2u);
   EXPECT_NE(vec.data(), nullptr);
-  EXPECT_EQ(that.size(), 0u);
-  EXPECT_EQ(that.data(), nullptr);
+  EXPECT_EQ(that.size(), 0u);       // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(that.data(), nullptr);  // NOLINT(bugprone-use-after-move)
 }
 
 TEST(HeapArray, MoveAssign) {
@@ -85,8 +85,8 @@
   vec = std::move(that);
   EXPECT_EQ(vec.size(), 2u);
   EXPECT_NE(vec.data(), nullptr);
-  EXPECT_EQ(that.size(), 0u);
-  EXPECT_EQ(that.data(), nullptr);
+  EXPECT_EQ(that.size(), 0u);       // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(that.data(), nullptr);  // NOLINT(bugprone-use-after-move)
 }
 
 TEST(HeapArray, DataAndIndex) {
@@ -322,8 +322,8 @@
   auto smaller_that = std::move(that).take_first(1u);
   EXPECT_EQ(smaller_that.size(), 1u);
   EXPECT_EQ(that_data, smaller_that.data());
-  EXPECT_EQ(that.size(), 0u);
-  EXPECT_EQ(that.data(), nullptr);
+  EXPECT_EQ(that.size(), 0u);       // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(that.data(), nullptr);  // NOLINT(bugprone-use-after-move)
 }
 
 TEST(HeapArray, TakeFirstWithZeroSize) {
@@ -331,8 +331,8 @@
   auto smaller_that = std::move(that).take_first(0u);
   EXPECT_EQ(smaller_that.size(), 0u);
   EXPECT_EQ(smaller_that.data(), nullptr);
-  EXPECT_EQ(that.size(), 0u);
-  EXPECT_EQ(that.data(), nullptr);
+  EXPECT_EQ(that.size(), 0u);       // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(that.data(), nullptr);  // NOLINT(bugprone-use-after-move)
 }
 
 TEST(HeapArrayDeathTest, TakeFirstWithOverSize) {
diff --git a/tot/base/containers/id_map_unittest.cc b/tot/base/containers/id_map_unittest.cc
index 65236bd..1392f4a 100644
--- a/tot/base/containers/id_map_unittest.cc
+++ b/tot/base/containers/id_map_unittest.cc
@@ -2,15 +2,11 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifdef UNSAFE_BUFFERS_BUILD
-// TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
-#pragma allow_unsafe_buffers
-#endif
-
 #include "base/containers/id_map.h"
 
 #include <stdint.h>
 
+#include <array>
 #include <functional>
 #include <memory>
 
@@ -144,8 +140,8 @@
   }
 
   // IDMap has no predictable iteration order.
-  int32_t ids_in_iteration_order[kCount];
-  const TestObject* objs_in_iteration_order[kCount];
+  std::array<int32_t, kCount> ids_in_iteration_order;
+  std::array<const TestObject*, kCount> objs_in_iteration_order;
   int counter = 0;
   for (IDMap<TestObject*>::const_iterator iter(&map); !iter.IsAtEnd();
        iter.Advance()) {
@@ -254,8 +250,8 @@
   }
 
   // IDMap has no predictable iteration order.
-  int32_t ids_in_iteration_order[kCount];
-  const TestObject* objs_in_iteration_order[kCount];
+  std::array<int32_t, kCount> ids_in_iteration_order;
+  std::array<const TestObject*, kCount> objs_in_iteration_order;
   int counter = 0;
   for (IDMap<TestObject*>::const_iterator iter(&map); !iter.IsAtEnd();
        iter.Advance()) {
@@ -293,11 +289,11 @@
   const int kCount = 3;
 
   int external_del_count = 0;
-  DestructorCounter* external_obj[kCount];
-  int map_external_ids[kCount];
+  std::array<DestructorCounter*, kCount> external_obj;
+  std::array<int, kCount> map_external_ids;
 
   int owned_del_count = 0;
-  int map_owned_ids[kCount];
+  std::array<int, kCount> map_owned_ids;
 
   IDMap<DestructorCounter*> map_external;
   IDMap<std::unique_ptr<DestructorCounter>> map_owned;
diff --git a/tot/base/containers/intrusive_heap.h b/tot/base/containers/intrusive_heap.h
index 4bbab74..70ecf19 100644
--- a/tot/base/containers/intrusive_heap.h
+++ b/tot/base/containers/intrusive_heap.h
@@ -144,8 +144,7 @@
 #include "base/check_op.h"
 #include "base/compiler_specific.h"
 #include "base/memory/ptr_util.h"
-#include "base/ranges/algorithm.h"
-#include "base/ranges/from_range.h"
+#include "base/types/cxx23_from_range.h"
 #include "third_party/abseil-cpp/absl/container/inlined_vector.h"
 
 namespace base {
@@ -479,9 +478,10 @@
     }
 
     // Repair the heap and ensure handles are pointing to the right index.
-    ranges::make_heap(impl_.heap_, value_comp());
-    for (size_t i = 0; i < size(); ++i)
+    std::ranges::make_heap(impl_.heap_, value_comp());
+    for (size_t i = 0; i < size(); ++i) {
       SetHeapHandle(i);
+    }
 
     // Explicitly delete elements last.
     elements_to_delete.clear();
@@ -683,16 +683,19 @@
   // as possible.
   void SetHeapHandle(HeapHandle handle) {
     DCHECK(handle.IsValid());
-    if (handle_)
+    if (handle_) {
       *handle_ = handle;
+    }
   }
   void ClearHeapHandle() {
-    if (handle_)
+    if (handle_) {
       handle_->reset();
+    }
   }
   HeapHandle GetHeapHandle() const {
-    if (handle_)
+    if (handle_) {
       return *handle_;
+    }
     return HeapHandle::Invalid();
   }
 
@@ -769,8 +772,9 @@
 }
 
 BASE_EXPORT inline void CheckInvalidOrEqualTo(HeapHandle handle, size_t index) {
-  if (handle.IsValid())
+  if (handle.IsValid()) {
     DCHECK_EQ(index, handle.index());
+  }
 }
 
 }  // namespace intrusive_heap
@@ -914,8 +918,9 @@
 IntrusiveHeap<T, Compare, HeapHandleAccessor>::ToIndex(const_iterator pos) {
   DCHECK(cbegin() <= pos);
   DCHECK(pos <= cend());
-  if (pos == cend())
+  if (pos == cend()) {
     return HeapHandle::kInvalidIndex;
+  }
   return pos - cbegin();
 }
 
@@ -925,8 +930,9 @@
     const_reverse_iterator pos) {
   DCHECK(crbegin() <= pos);
   DCHECK(pos <= crend());
-  if (pos == crend())
+  if (pos == crend()) {
     return HeapHandle::kInvalidIndex;
+  }
   return (pos.base() - cbegin()) - 1;
 }
 
@@ -1025,8 +1031,9 @@
   while (hole_pos != 0) {
     // If our parent is >= to us, we can stop.
     size_type parent = intrusive_heap::ParentIndex(hole_pos);
-    if (!Less(parent, element))
+    if (!Less(parent, element)) {
       break;
+    }
 
     MoveHole(parent, hole_pos);
     hole_pos = parent;
@@ -1054,19 +1061,22 @@
   while (true) {
     // If this spot has no children, then we've gone down as far as we can go.
     size_type left = intrusive_heap::LeftIndex(hole_pos);
-    if (left >= n)
+    if (left >= n) {
       break;
+    }
     size_type right = left + 1;
 
     // Get the larger of the potentially two child nodes.
     size_type largest = left;
-    if (right < n && Less(left, right))
+    if (right < n && Less(left, right)) {
       largest = right;
+    }
 
     // If we're not deterministically moving the element all the way down to
     // become a leaf, then stop when it is >= the largest of the children.
-    if (!FillElementType::kIsLeafElement && !Less(element, largest))
+    if (!FillElementType::kIsLeafElement && !Less(element, largest)) {
       break;
+    }
 
     MoveHole(largest, hole_pos);
     hole_pos = largest;
diff --git a/tot/base/containers/intrusive_heap_unittest.cc b/tot/base/containers/intrusive_heap_unittest.cc
index 895c208..fcf51b1 100644
--- a/tot/base/containers/intrusive_heap_unittest.cc
+++ b/tot/base/containers/intrusive_heap_unittest.cc
@@ -32,10 +32,12 @@
     size_t left = intrusive_heap::LeftIndex(i);
     size_t right = left + 1;
 
-    if (left < heap.size())
+    if (left < heap.size()) {
       EXPECT_FALSE(less(heap[i], heap[left]));
-    if (right < heap.size())
+    }
+    if (right < heap.size()) {
       EXPECT_FALSE(less(heap[i], heap[right]));
+    }
 
     intrusive_heap::CheckInvalidOrEqualTo(handle_access.GetHeapHandle(&heap[i]),
                                           i);
@@ -61,8 +63,9 @@
   // 7 4 6 1 3 2 5 0
   std::vector<int> expected{7, 4, 6, 1, 3, 2, 5, 0};
   std::vector<int> actual;
-  for (const auto& element : heap)
+  for (const auto& element : heap) {
     actual.push_back(element.value());
+  }
   ASSERT_THAT(actual, testing::ContainerEq(expected));
 }
 
@@ -233,8 +236,9 @@
 
   size_t old_size = heap->size();
   size_t index = static_cast<size_t>(base::RandInt(0, old_size - 1));
-  if (op == kReplaceTop)
+  if (op == kReplaceTop) {
     index = 0;
+  }
   int new_value = base::RandInt(0, 1000);
   typename IntrusiveHeap<T>::const_iterator it;
 
@@ -310,16 +314,16 @@
   EXPECT_EQ(4u, heap2.size());
   EXPECT_FALSE(heap2.empty());
   ExpectHeap(heap2);
-  EXPECT_EQ(0u, heap.size());
-  EXPECT_TRUE(heap.empty());
+  EXPECT_EQ(0u, heap.size());  // NOLINT(bugprone-use-after-move)
+  EXPECT_TRUE(heap.empty());   // NOLINT(bugprone-use-after-move)
   ExpectHeap(heap);
 
   heap = std::move(heap2);
   EXPECT_EQ(4u, heap.size());
   EXPECT_FALSE(heap.empty());
   ExpectHeap(heap);
-  EXPECT_EQ(0u, heap2.size());
-  EXPECT_TRUE(heap2.empty());
+  EXPECT_EQ(0u, heap2.size());  // NOLINT(bugprone-use-after-move)
+  EXPECT_TRUE(heap2.empty());   // NOLINT(bugprone-use-after-move)
   ExpectHeap(heap2);
 }
 
@@ -460,19 +464,20 @@
  public:
   explicit Value(int value) : value_(value) {}
   Value() : value_(-1) {}
-  Value(Value&& other) noexcept
-      : InternalHeapHandleStorage(std::move(other)),
-        value_(std::exchange(other.value_, -1)) {}
+  Value(Value&& other) noexcept : value_(std::exchange(other.value_, -1)) {
+    InternalHeapHandleStorage::operator=(std::move(other));
+  }
   Value(const Value& other) : value_(other.value_) {
     HeapHandle h = other.GetHeapHandle();
-    if (h.IsValid())
+    if (h.IsValid()) {
       SetHeapHandle(h);
+    }
   }
   ~Value() override = default;
 
   Value& operator=(Value&& other) noexcept {
-    InternalHeapHandleStorage::operator=(std::move(other));
     value_ = std::exchange(other.value_, -1);
+    InternalHeapHandleStorage::operator=(std::move(other));
     return *this;
   }
   Value& operator=(const Value& other) {
@@ -535,18 +540,21 @@
   bool operator<(const TestElement& other) const { return key > other.key; }
 
   void SetHeapHandle(HeapHandle h) {
-    if (handle)
+    if (handle) {
       *handle = h;
+    }
   }
 
   void ClearHeapHandle() {
-    if (handle)
+    if (handle) {
       handle->reset();
+    }
   }
 
   HeapHandle GetHeapHandle() const {
-    if (handle)
+    if (handle) {
       return *handle;
+    }
     return HeapHandle::Invalid();
   }
 };
@@ -573,7 +581,7 @@
 
     // Move constructor.
     IntrusiveHeapInt heap2(std::move(heap));
-    EXPECT_TRUE(heap.empty());
+    EXPECT_TRUE(heap.empty());  // NOLINT(bugprone-use-after-move)
     ExpectCanonical(heap2);
   }
 
@@ -598,7 +606,7 @@
   // Move assignment.
   IntrusiveHeapInt heap2;
   heap2 = std::move(heap);
-  EXPECT_TRUE(heap.empty());
+  EXPECT_TRUE(heap.empty());  // NOLINT(bugprone-use-after-move)
   ExpectCanonical(heap2);
 }
 
@@ -825,8 +833,9 @@
 TEST(IntrusiveHeapTest, InsertDescending) {
   IntrusiveHeap<TestElement> heap;
 
-  for (int i = 0; i < 50; i++)
+  for (int i = 0; i < 50; i++) {
     heap.insert({50 - i, nullptr});
+  }
 
   EXPECT_EQ(1, heap.top().key);
   EXPECT_EQ(50u, heap.size());
@@ -903,8 +912,9 @@
 TEST(IntrusiveHeapTest, PopMany) {
   IntrusiveHeap<TestElement> heap;
 
-  for (int i = 0; i < 500; i++)
+  for (int i = 0; i < 500; i++) {
     heap.insert({i, nullptr});
+  }
 
   EXPECT_FALSE(heap.empty());
   EXPECT_EQ(500u, heap.size());
@@ -946,13 +956,15 @@
 TEST(IntrusiveHeapTest, ReplaceTop) {
   IntrusiveHeap<TestElement> heap;
 
-  for (int i = 0; i < 500; i++)
+  for (int i = 0; i < 500; i++) {
     heap.insert({500 - i, nullptr});
+  }
 
   EXPECT_EQ(1, heap.top().key);
 
-  for (int i = 0; i < 500; i++)
+  for (int i = 0; i < 500; i++) {
     heap.ReplaceTop({1000 + i, nullptr});
+  }
 
   EXPECT_EQ(1000, heap.top().key);
 }
@@ -967,8 +979,9 @@
 
   EXPECT_EQ(0, heap.top().key);
 
-  for (int i = 0; i < 50; i++)
+  for (int i = 0; i < 50; i++) {
     heap.ReplaceTop({100 + i, nullptr});
+  }
 
   for (int i = 0; i < 50; i++) {
     EXPECT_EQ((100 + i), heap.top().key);
@@ -1106,8 +1119,9 @@
   std::array<HeapHandle, 10> index;
   IntrusiveHeap<TestElement> heap;
 
-  for (int i = 0; i < 10; i++)
+  for (int i = 0; i < 10; i++) {
     heap.insert({static_cast<int>(i ^ (i + 1)), &index[i]});
+  }
 
   for (int i = 0; i < 10; i++) {
     EXPECT_EQ(heap.at(index[i]).key, i ^ (i + 1));
@@ -1123,8 +1137,9 @@
   std::array<HeapHandle, 10> index;
   IntrusiveHeap<TestElement> heap;
 
-  for (int i = 0; i < 10; i++)
+  for (int i = 0; i < 10; i++) {
     heap.insert({i, &index[i]});
+  }
   ASSERT_EQ(heap.size(), 10u);
 
   // Remove all even elements.
@@ -1132,8 +1147,9 @@
   ASSERT_EQ(heap.size(), 5u);
 
   // Handles were correctly updated.
-  for (int i = 0; i < 10; i++)
+  for (int i = 0; i < 10; i++) {
     EXPECT_EQ(IsEven(i), !index[i].IsValid());
+  }
 
   // Now iterate over all elements of the heap and check their handles.
   for (size_t i = 0; i < heap.size(); i++) {
diff --git a/tot/base/containers/linked_list.cc b/tot/base/containers/linked_list.cc
index 1471a98..fca8b79 100644
--- a/tot/base/containers/linked_list.cc
+++ b/tot/base/containers/linked_list.cc
@@ -6,9 +6,7 @@
 
 #include "base/check_op.h"
 
-namespace base {
-
-namespace internal {
+namespace base::internal {
 
 LinkNodeBase::LinkNodeBase() = default;
 
@@ -56,6 +54,4 @@
   e->next_ = this;
 }
 
-}  // namespace internal
-
-}  // namespace base
+}  // namespace base::internal
diff --git a/tot/base/containers/linked_list.h b/tot/base/containers/linked_list.h
index 83e8b4b..0a26caa 100644
--- a/tot/base/containers/linked_list.h
+++ b/tot/base/containers/linked_list.h
@@ -144,13 +144,9 @@
   LinkNode<T>* next() const { return static_cast<LinkNode<T>*>(next_base()); }
 
   // Cast from the node-type to the value type.
-  const T* value() const {
-    return static_cast<const T*>(this);
-  }
+  const T* value() const { return static_cast<const T*>(this); }
 
-  T* value() {
-    return static_cast<T*>(this);
-  }
+  T* value() { return static_cast<T*>(this); }
 };
 
 template <typename T>
@@ -164,21 +160,13 @@
   LinkedList& operator=(const LinkedList&) = delete;
 
   // Appends |e| to the end of the linked list.
-  void Append(LinkNode<T>* e) {
-    e->InsertBefore(&root_);
-  }
+  void Append(LinkNode<T>* e) { e->InsertBefore(&root_); }
 
-  LinkNode<T>* head() const {
-    return root_.next();
-  }
+  LinkNode<T>* head() const { return root_.next(); }
 
-  LinkNode<T>* tail() const {
-    return root_.previous();
-  }
+  LinkNode<T>* tail() const { return root_.previous(); }
 
-  const LinkNode<T>* end() const {
-    return &root_;
-  }
+  const LinkNode<T>* end() const { return &root_; }
 
   bool empty() const { return head() == end(); }
 
diff --git a/tot/base/containers/linked_list_unittest.cc b/tot/base/containers/linked_list_unittest.cc
index d7d87ac..48cdc0e 100644
--- a/tot/base/containers/linked_list_unittest.cc
+++ b/tot/base/containers/linked_list_unittest.cc
@@ -23,8 +23,8 @@
 
 class MultipleInheritanceNodeBase {
  public:
-  MultipleInheritanceNodeBase() : field_taking_up_space_(0) {}
-  int field_taking_up_space_;
+  MultipleInheritanceNodeBase() = default;
+  int field_taking_up_space_ = 0;
 };
 
 class MultipleInheritanceNode : public MultipleInheritanceNodeBase,
@@ -52,8 +52,7 @@
                                     bool forward) {
   size_t i = 0;
   for (const LinkNode<Node>* node = (forward ? list.head() : list.tail());
-       node != list.end();
-       node = (forward ? node->next() : node->previous())) {
+       node != list.end(); node = (forward ? node->next() : node->previous())) {
     ASSERT_LT(i, node_ids.size());
     EXPECT_EQ(node_ids[forward ? i : node_ids.size() - i - 1],
               node->value()->id());
@@ -336,8 +335,8 @@
 
   MovableNode n2_new(std::move(n2));
 
-  EXPECT_EQ(nullptr, n2.next());
-  EXPECT_EQ(nullptr, n2.previous());
+  EXPECT_EQ(nullptr, n2.next());      // NOLINT(bugprone-use-after-move)
+  EXPECT_EQ(nullptr, n2.previous());  // NOLINT(bugprone-use-after-move)
 
   EXPECT_EQ(&n1, n2_new.previous());
   EXPECT_EQ(&n2_new, n1.next());
diff --git a/tot/base/containers/lru_cache.h b/tot/base/containers/lru_cache.h
index 95e69b5..8575476 100644
--- a/tot/base/containers/lru_cache.h
+++ b/tot/base/containers/lru_cache.h
@@ -126,8 +126,9 @@
   // recency list.
   iterator Get(const key_type& key) {
     typename KeyIndex::iterator index_iter = index_.find(key);
-    if (index_iter == index_.end())
+    if (index_iter == index_.end()) {
       return end();
+    }
     typename ValueList::iterator iter = index_iter->second;
 
     // Move the touched item to the front of the recency ordering.
@@ -139,15 +140,17 @@
   // result without affecting the ordering (unlike Get()).
   iterator Peek(const key_type& key) {
     typename KeyIndex::const_iterator index_iter = index_.find(key);
-    if (index_iter == index_.end())
+    if (index_iter == index_.end()) {
       return end();
+    }
     return index_iter->second;
   }
 
   const_iterator Peek(const key_type& key) const {
     typename KeyIndex::const_iterator index_iter = index_.find(key);
-    if (index_iter == index_.end())
+    if (index_iter == index_.end()) {
       return end();
+    }
     return index_iter->second;
   }
 
@@ -160,6 +163,9 @@
 
   // Erases the item referenced by the given iterator. An iterator to the item
   // following it will be returned. The iterator must be valid.
+  // Note that caller should avoid using std::remove_if() with this container as
+  // the iterator from begin()/end() is not designed to have the key modified,
+  // see comment on begin().
   iterator Erase(iterator pos) {
     index_.erase(GetKeyFromValue()(*pos));
     return ordering_.erase(pos);
@@ -177,8 +183,9 @@
   // Shrinks the cache so it only holds |new_size| items. If |new_size| is
   // bigger or equal to the current number of items, this will do nothing.
   void ShrinkToSize(size_type new_size) {
-    for (size_type i = size(); i > new_size; i--)
+    for (size_type i = size(); i > new_size; i--) {
       Erase(rbegin());
+    }
   }
 
   // Deletes everything from the cache.
@@ -201,6 +208,10 @@
   // Note that since these iterators are actually iterators over a list, you
   // can keep them as you insert or delete things (as long as you don't delete
   // the one you are pointing to) and they will still be valid.
+  // Also, caller should avoid moving the order of items around, or any
+  // operation that modifies the key in the value with these iterators, such as
+  // using std::remove_if(). This is because the key in index_ is not updated
+  // and the container will be corrupted.
   iterator begin() { return ordering_.begin(); }
   const_iterator begin() const { return ordering_.begin(); }
   iterator end() { return ordering_.end(); }
diff --git a/tot/base/containers/map_util.h b/tot/base/containers/map_util.h
index 17ac4fa..fe7d8b1 100644
--- a/tot/base/containers/map_util.h
+++ b/tot/base/containers/map_util.h
@@ -66,6 +66,40 @@
   return it != map.end() ? base::to_address(it->second) : nullptr;
 }
 
+// Insert or assign into a map type. This has semantics very similar to the
+// following statements:
+//
+//    map[key] = Element(params...)
+//    map[key] = element;
+//    map[key] = std::move(element);
+//    map.insert_or_assign(key, element);
+//
+// Where key can be any heterogeneous comparable overload of the key_type for
+// map. In particular, there is no need to construct a temporary `key` of the
+// type stored in the map as long as `key` is comparable with the
+// `Map::key_type`.
+//
+// The `element` is copied or moved into the map, depending on whether it is
+// passed by lvalue or rvalue reference.
+//
+// TODO(crbug.com/376532871): This can be removed once map::operator[] and
+// map::insert_or_assign support heterogenous key overloads, in C++26.
+template <typename Map,
+          typename Key,
+          typename MappedElementType =
+              std::pointer_traits<internal::MappedType<Map>>::element_type>
+Map::iterator InsertOrAssign(Map& map,
+                             const Key& key,
+                             MappedElementType&& element) {
+  auto it = map.lower_bound(key);
+  if (it == map.end() || it->first != key) {
+    it = map.emplace_hint(it, key, std::forward<MappedElementType>(element));
+  } else {
+    it->second = std::forward<MappedElementType>(element);
+  }
+  return it;
+}
+
 }  // namespace base
 
 #endif  // BASE_CONTAINERS_MAP_UTIL_H_
diff --git a/tot/base/containers/map_util_unittest.cc b/tot/base/containers/map_util_unittest.cc
index 14ba76b..f187833 100644
--- a/tot/base/containers/map_util_unittest.cc
+++ b/tot/base/containers/map_util_unittest.cc
@@ -56,6 +56,79 @@
   EXPECT_EQ(FindPtrOrNull(mapping, kMissingKey), nullptr);
 }
 
+struct LeftVsRightValue {
+  enum RefType {
+    UNKNOWN,
+    EMPLACED,
+    LVALUE,
+    RVALUE,
+  };
+
+  explicit LeftVsRightValue(int n) : ref_type(EMPLACED), value(n) {}
+  LeftVsRightValue(LeftVsRightValue&& n) : ref_type(RVALUE), value(n.value) {}
+  LeftVsRightValue(const LeftVsRightValue& n)
+      : ref_type(LVALUE), value(n.value) {}
+
+  LeftVsRightValue& operator=(LeftVsRightValue&& n) {
+    ref_type = RVALUE;
+    value = n.value;
+    return *this;
+  }
+
+  LeftVsRightValue& operator=(const LeftVsRightValue& n) {
+    ref_type = LVALUE;
+    value = n.value;
+    return *this;
+  }
+
+  RefType ref_type = UNKNOWN;
+  int value = 0;
+};
+
+TEST(MapUtilTest, InsertOrAssign) {
+  using StringToValueMap = std::map<std::string, LeftVsRightValue, std::less<>>;
+  StringToValueMap map;
+
+  // Heterogenous keys - all of types comparable with std::string.
+  const char key1[] = "This is key 1. It is very long";
+  std::string_view key2 = "This is key 2. It is also very long";
+  std::string key3 = "This is key 3. It, like keys 1 and 2, is long";
+
+  // Insert a new key with a value that is an implicit rvalue.
+  auto it = InsertOrAssign(map, key1, LeftVsRightValue(1));
+  EXPECT_EQ(it->second.ref_type, LeftVsRightValue::RVALUE);
+  EXPECT_EQ(it->second.value, 1);
+
+  // Update that key with a value that is an implicit rvalue.
+  it = InsertOrAssign(map, key1, LeftVsRightValue(2));
+  EXPECT_EQ(it->second.ref_type, LeftVsRightValue::RVALUE);
+  EXPECT_EQ(it->second.value, 2);
+
+  // Insert new key with a value that is an explicit rvalue.
+  LeftVsRightValue v3(3);
+  it = InsertOrAssign(map, key2, std::move(v3));
+  EXPECT_EQ(it->second.ref_type, LeftVsRightValue::RVALUE);
+  EXPECT_EQ(it->second.value, 3);
+
+  // Update that key with a value that is an explicit rvalue.
+  LeftVsRightValue v4(4);
+  it = InsertOrAssign(map, key2, std::move(v4));
+  EXPECT_EQ(it->second.ref_type, LeftVsRightValue::RVALUE);
+  EXPECT_EQ(it->second.value, 4);
+
+  // Insert new key with a value that is an lvalue.
+  LeftVsRightValue v5(5);
+  it = InsertOrAssign(map, key3, v5);
+  EXPECT_EQ(it->second.ref_type, LeftVsRightValue::LVALUE);
+  EXPECT_EQ(it->second.value, 5);
+
+  // Update that key with a value that is an lvalue.
+  LeftVsRightValue v6(6);
+  it = InsertOrAssign(map, key3, v6);
+  EXPECT_EQ(it->second.ref_type, LeftVsRightValue::LVALUE);
+  EXPECT_EQ(it->second.value, 6);
+}
+
 }  // namespace
 
 }  // namespace base
diff --git a/tot/base/containers/ring_buffer.h b/tot/base/containers/ring_buffer.h
index 2a49d7a..d3e75e6 100644
--- a/tot/base/containers/ring_buffer.h
+++ b/tot/base/containers/ring_buffer.h
@@ -72,14 +72,16 @@
 
     Iterator& operator++() {
       index_++;
-      if (index_ == kSize)
+      if (index_ == kSize) {
         out_of_range_ = true;
+      }
       return *this;
     }
 
     Iterator& operator--() {
-      if (index_ == 0)
+      if (index_ == 0) {
         out_of_range_ = true;
+      }
       index_--;
       return *this;
     }
@@ -103,8 +105,9 @@
   // Example usage (iterate from oldest to newest value):
   //  for (RingBuffer<T, kSize>::Iterator it = ring_buffer.Begin(); it; ++it) {}
   Iterator Begin() const {
-    if (current_index_ < kSize)
+    if (current_index_ < kSize) {
       return Iterator(*this, kSize - current_index_);
+    }
     return Iterator(*this, 0);
   }
 
diff --git a/tot/base/containers/small_map.h b/tot/base/containers/small_map.h
index f17d509..11be28b 100644
--- a/tot/base/containers/small_map.h
+++ b/tot/base/containers/small_map.h
@@ -107,17 +107,22 @@
 template <typename M>
 struct has_key_equal {
   typedef char sml;  // "small" is sometimes #defined so we use an abbreviation.
-  typedef struct { char dummy[2]; } big;
+  typedef struct {
+    char dummy[2];
+  } big;
   // Two functions, one accepts types that have a key_equal member, and one that
   // accepts anything. They each return a value of a different size, so we can
   // determine at compile-time which function would have been called.
-  template <typename U> static big test(typename U::key_equal*);
-  template <typename> static sml test(...);
+  template <typename U>
+  static big test(typename U::key_equal*);
+  template <typename>
+  static sml test(...);
   // Determines if M::key_equal exists by looking at the size of the return
   // type of the compiler-chosen test() function.
   static const bool value = (sizeof(test<M>(0)) == sizeof(big));
 };
-template <typename M> const bool has_key_equal<M>::value;
+template <typename M>
+const bool has_key_equal<M>::value;
 
 // Base template used for map types that do NOT have an M::key_equal member,
 // e.g., std::map<>. These maps have a strict weak ordering comparator rather
@@ -178,7 +183,9 @@
   }
 
   constexpr void operator=(const small_map& src) {
-    if (&src == this) return;
+    if (&src == this) {
+      return;
+    }
 
     // This is not optimal. If src and dest are both using the small array, we
     // could skip the teardown and reconstruct. One problem to be resolved is
diff --git a/tot/base/containers/small_map_unittest.cc b/tot/base/containers/small_map_unittest.cc
index 6096740..6407d1d 100644
--- a/tot/base/containers/small_map_unittest.cc
+++ b/tot/base/containers/small_map_unittest.cc
@@ -50,11 +50,11 @@
   m[1234] = 90;
   m[-5] = 6;
 
-  EXPECT_EQ(m[   9],  2);
-  EXPECT_EQ(m[   0],  5);
+  EXPECT_EQ(m[9], 2);
+  EXPECT_EQ(m[0], 5);
   EXPECT_EQ(m[1234], 90);
-  EXPECT_EQ(m[   8], 23);
-  EXPECT_EQ(m[  -5],  6);
+  EXPECT_EQ(m[8], 23);
+  EXPECT_EQ(m[-5], 6);
   EXPECT_EQ(m.size(), 5u);
   EXPECT_FALSE(m.empty());
   EXPECT_TRUE(m.UsingFullMap());
@@ -126,11 +126,11 @@
 
   {
     small_map<std::unordered_map<int, int>> m(src);
-    EXPECT_EQ(m[   9],  2);
-    EXPECT_EQ(m[   0],  5);
+    EXPECT_EQ(m[9], 2);
+    EXPECT_EQ(m[0], 5);
     EXPECT_EQ(m[1234], 90);
-    EXPECT_EQ(m[   8], 23);
-    EXPECT_EQ(m[  -5],  6);
+    EXPECT_EQ(m[8], 23);
+    EXPECT_EQ(m[-5], 6);
     EXPECT_EQ(m.size(), 5u);
     EXPECT_FALSE(m.empty());
     EXPECT_TRUE(m.UsingFullMap());
@@ -143,8 +143,9 @@
   typename small_map<inner>::const_iterator it;
   for (it = a.begin(); it != a.end(); ++it) {
     typename small_map<inner>::const_iterator it_in_b = b.find(it->first);
-    if (it_in_b == b.end() || it_in_b->second != it->second)
+    if (it_in_b == b.end() || it_in_b->second != it->second) {
       return false;
+    }
   }
   return true;
 }
@@ -176,25 +177,21 @@
   small_map<std::unordered_map<int, int>> dest_small;
   dest_small = src_small;
   EXPECT_TRUE(SmallMapEqual(dest_small, src_small));
-  EXPECT_EQ(dest_small.UsingFullMap(),
-            src_small.UsingFullMap());
+  EXPECT_EQ(dest_small.UsingFullMap(), src_small.UsingFullMap());
 
   small_map<std::unordered_map<int, int>> dest_large;
   dest_large = src_large;
   EXPECT_TRUE(SmallMapEqual(dest_large, src_large));
-  EXPECT_EQ(dest_large.UsingFullMap(),
-            src_large.UsingFullMap());
+  EXPECT_EQ(dest_large.UsingFullMap(), src_large.UsingFullMap());
 
   // Assignments which assign from full to small, and vice versa.
   dest_small = src_large;
   EXPECT_TRUE(SmallMapEqual(dest_small, src_large));
-  EXPECT_EQ(dest_small.UsingFullMap(),
-            src_large.UsingFullMap());
+  EXPECT_EQ(dest_small.UsingFullMap(), src_large.UsingFullMap());
 
   dest_large = src_small;
   EXPECT_TRUE(SmallMapEqual(dest_large, src_small));
-  EXPECT_EQ(dest_large.UsingFullMap(),
-            src_small.UsingFullMap());
+  EXPECT_EQ(dest_large.UsingFullMap(), src_small.UsingFullMap());
 
   // Double check that SmallMapEqual works:
   dest_large[42] = 666;
@@ -209,11 +206,11 @@
     VLOG(1) << "Iteration " << i;
     // insert an element
     std::pair<small_map<std::unordered_map<int, int>>::iterator, bool> ret;
-    ret = sm.insert(std::make_pair(i, 100*i));
+    ret = sm.insert(std::make_pair(i, 100 * i));
     EXPECT_TRUE(ret.second);
     EXPECT_TRUE(ret.first == sm.find(i));
     EXPECT_EQ(ret.first->first, i);
-    EXPECT_EQ(ret.first->second, 100*i);
+    EXPECT_EQ(ret.first->second, 100 * i);
 
     // try to insert it again with different value, fails, but we still get an
     // iterator back with the original value.
@@ -221,7 +218,7 @@
     EXPECT_FALSE(ret.second);
     EXPECT_TRUE(ret.first == sm.find(i));
     EXPECT_EQ(ret.first->first, i);
-    EXPECT_EQ(ret.first->second, 100*i);
+    EXPECT_EQ(ret.first->second, 100 * i);
 
     // check the state of the map.
     for (int j = 1; j <= i; ++j) {
@@ -241,7 +238,7 @@
     VLOG(1) << "Elements " << elements;
     std::unordered_map<int, int> normal_map;
     for (int i = 1; i <= elements; ++i) {
-      normal_map.insert(std::make_pair(i, 100*i));
+      normal_map.insert(std::make_pair(i, 100 * i));
     }
 
     small_map<std::unordered_map<int, int>> sm;
@@ -251,7 +248,7 @@
       VLOG(1) << "Iteration " << i;
       EXPECT_TRUE(sm.find(i) != sm.end());
       EXPECT_EQ(sm.find(i)->first, i);
-      EXPECT_EQ(sm.find(i)->second, 100*i);
+      EXPECT_EQ(sm.find(i)->second, 100 * i);
     }
   }
 }
@@ -264,8 +261,8 @@
   m["tuesday"] = 2;
   m["wednesday"] = 3;
 
-  EXPECT_EQ(m["monday"   ], 1);
-  EXPECT_EQ(m["tuesday"  ], 2);
+  EXPECT_EQ(m["monday"], 1);
+  EXPECT_EQ(m["tuesday"], 2);
   EXPECT_EQ(m["wednesday"], 3);
   EXPECT_EQ(m.count("tuesday"), 1u);
   EXPECT_FALSE(m.UsingFullMap());
@@ -287,7 +284,7 @@
 
   EXPECT_EQ(m.erase("tuesday"), 1u);
 
-  EXPECT_EQ(m["monday"   ], 1);
+  EXPECT_EQ(m["monday"], 1);
   EXPECT_EQ(m["wednesday"], 3);
   EXPECT_EQ(m.count("tuesday"), 0u);
   EXPECT_EQ(m.erase("tuesday"), 0u);
@@ -361,7 +358,7 @@
 }
 
 TEST(SmallMap, NonHashMap) {
-  small_map<std::map<int, int>, 4, std::equal_to<int>> m;
+  small_map<std::map<int, int>, 4, std::equal_to<>> m;
   EXPECT_TRUE(m.empty());
 
   m[9] = 2;
@@ -373,8 +370,7 @@
   EXPECT_FALSE(m.empty());
   EXPECT_FALSE(m.UsingFullMap());
 
-  small_map<std::map<int, int>, 4, std::equal_to<int>>::iterator iter(
-      m.begin());
+  small_map<std::map<int, int>, 4, std::equal_to<>>::iterator iter(m.begin());
   ASSERT_TRUE(iter != m.end());
   EXPECT_EQ(iter->first, 9);
   EXPECT_EQ(iter->second, 2);
@@ -389,11 +385,11 @@
   m[1234] = 90;
   m[-5] = 6;
 
-  EXPECT_EQ(m[   9],  2);
-  EXPECT_EQ(m[   0],  5);
+  EXPECT_EQ(m[9], 2);
+  EXPECT_EQ(m[0], 5);
   EXPECT_EQ(m[1234], 90);
-  EXPECT_EQ(m[   8], 23);
-  EXPECT_EQ(m[  -5],  6);
+  EXPECT_EQ(m[8], 23);
+  EXPECT_EQ(m[-5], 6);
   EXPECT_EQ(m.size(), 5u);
   EXPECT_FALSE(m.empty());
   EXPECT_TRUE(m.UsingFullMap());
@@ -460,7 +456,7 @@
 }  // anonymous namespace
 
 TEST(SmallMap, SubclassInitializationWithFunctionPointer) {
-  small_map<unordered_map_add_item, 4, std::equal_to<int>,
+  small_map<unordered_map_add_item, 4, std::equal_to<>,
             void (&)(unordered_map_add_item*)>
       m(InitMap);
 
@@ -481,7 +477,7 @@
 }
 
 TEST(SmallMap, SubclassInitializationWithFunctionObject) {
-  small_map<unordered_map_add_item, 4, std::equal_to<int>,
+  small_map<unordered_map_add_item, 4, std::equal_to<>,
             unordered_map_add_item_initializer>
       m(unordered_map_add_item_initializer(-1));
 
@@ -511,9 +507,7 @@
   MoveOnlyType() : value_(0) {}
   explicit MoveOnlyType(V value) : value_(value) {}
 
-  MoveOnlyType(MoveOnlyType&& other) {
-    *this = std::move(other);
-  }
+  MoveOnlyType(MoveOnlyType&& other) { *this = std::move(other); }
 
   MoveOnlyType& operator=(MoveOnlyType&& other) {
     value_ = other.value_;
diff --git a/tot/base/containers/span.h b/tot/base/containers/span.h
index fa0f607..a8bc5eb 100644
--- a/tot/base/containers/span.h
+++ b/tot/base/containers/span.h
@@ -1,6 +1,11 @@
 // Copyright 2017 The Chromium Authors
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
+//
+// This file intentionally uses the `CHECK()` macro instead of the `CHECK_op()`
+// macros, as `CHECK()` generates significantly less code and is more likely to
+// optimize reasonably, even in non-official release builds. Please do not
+// change the `CHECK()` calls back to `CHECK_op()` calls.
 
 #ifndef BASE_CONTAINERS_SPAN_H_
 #define BASE_CONTAINERS_SPAN_H_
@@ -23,12 +28,15 @@
 #include <span>
 #include <type_traits>
 #include <utility>
+#include <vector>
 
 #include "base/check.h"
 #include "base/compiler_specific.h"
 #include "base/containers/checked_iterators.h"
+#include "base/numerics/integral_constant_like.h"
 #include "base/numerics/safe_conversions.h"
 #include "base/strings/cstring_view.h"
+#include "base/strings/to_string.h"
 #include "base/types/to_address.h"
 
 // A span is a view of contiguous elements that can be accessed like an array,
@@ -103,14 +111,15 @@
 // -------------------------------------
 // By default spans have dynamic extent, which means that the size is available
 // at runtime via `size()`, a la other containers and views. By using a second
-// template parameter, a span's extent can be fixed at compile time; this can
-// move some constraint checks to compile time and slightly improve codegen, at
-// the cost of verbosity and more template instantiations. Methods like
-// `first()` or `subspan()` also provide templated overloads that produce
-// fixed-extent spans; these are preferred when the size is known at compile
-// time, in part because e.g. `first(1)` is a compile-error (the `int` arg is
-// not compatible with the `StrictNumeric<size_t>` param; use `first(1u)`
-// instead), but `first<1>()` is not.
+// template parameter or passing a `std::integral_constant` to the second (size)
+// constructor arg, a span's extent can be fixed at compile time; this can move
+// some constraint checks to compile time and slightly improve codegen, at the
+// cost of verbosity and more template instantiations. Methods like `first()` or
+// `subspan()` also provide templated overloads that produce fixed-extent spans;
+// these are preferred when the size is known at compile time, in part because
+// e.g. `first(1)` is a compile-error (the `int` arg is not compatible with the
+// `StrictNumeric<size_t>` param; use `first(1u)` instead), but `first<1>()` is
+// not.
 //
 // A fixed-extent span implicitly converts to a dynamic-extent span (e.g.
 // `span<int, 6>` is implicitly convertible to `span<int>`), so most code that
@@ -122,6 +131,8 @@
 // span:
 // - Explicit construction of `span<T, N>`, which `CHECK()`s if the size doesn't
 //   match.
+// - Construction of `span(T*, fixed_extent<N>)`, which is equivalent to the
+//   above.
 // - `to_fixed_extent<N>()`, which returns `std::nullopt` if the size doesn't
 //   match.
 // - `first<N>()`, `last<N>()`, and `subspan<Index, N>()`, which `CHECK()` if
@@ -144,6 +155,24 @@
 // (N.B. There is no entry above for `std::vector<int* const>`, since per the
 // C++ standard, `std::vector`'s element type must be non-const.)
 //
+// Byte spans, `std::has_unique_object_representations_v<>`, and conversions
+// -------------------------------------------------------------------------
+// Because byte spans are often used to copy and hash objects, the byte span
+// conversion functions (e.g. `as_bytes()`, `as_byte_span()`) require the
+// element type to meet `std::has_unique_object_representations_v<>`. For types
+// which do not meet this requirement but need conversion to a byte span, there
+// are two workarounds:
+//   1. If the type is safe to convert to a byte span in general, specialize
+//      `kCanSafelyConvertToByteSpan<T>` to be true for it. For example, Blink's
+//      `AtomicString` is not trivially copyable, but it is interned, so hashing
+//      and comparing the hashed values is safe.
+//   2. If the type is not safe in general but is safe for a particular use
+//      case, pass `base::allow_nonunique_obj` as the first arg to the byte span
+//      conversion functions. For example, floating-point values are not unique
+//      (among other reasons, because `+0` and `-0` are distinct but compare
+//      equal), but they are trivially copyable, so serializing them to disk and
+//      then deserializing is OK.
+//
 // Spans using `raw_ptr<T>` for internal storage
 // ---------------------------------------------
 // Provided via the type alias `raw_span<T[, N]>` (see base/memory/raw_span.h).
@@ -162,6 +191,11 @@
 // and related utilities. Chromium aims to follow the draft except where noted
 // below; please report other divergences you find.
 //
+// Differences from [span.syn]:
+// - For convenience, provides `fixed_extent<N>` as an alias to
+//   `std::integral_constant<size_t, N>`, to aid in constructing fixed-extent
+//   spans from pointers.
+//
 // Differences from [span.overview]:
 // - `span` takes an optional third template argument that can be used to
 //   customize the underlying storage pointer type. This allows implementing
@@ -198,8 +232,12 @@
 // Differences from [span.sub]:
 // - As in [span.cons], `size_t` parameters are changed to
 //   `StrictNumeric<size_type>`.
+// - There are separate overloads for one-arg and two-arg forms of subspan,
+//   and the two-arg form does not accept dynamic_extent as a count.
 // - For convenience, provides `span::split_at()` to split a single span into
 //   two at a given offset.
+// - For convenience, provides `span::take_first[_elem]()` to remove the first
+//   portion of a dynamic-extent span and return it.
 //
 // Differences from [span.obs]:
 // - For convenience, provides `span::operator==()` to check whether two spans
@@ -220,9 +258,9 @@
 // Differences from [span.objectrep]:
 // - For convenience, provides `span::to_fixed_extent<N>()` to attempt
 //   conversion to a fixed-extent span, and return null on failure.
-// - Because Chromium bans `std::byte`, `as_[writeable_]bytes()` use `uint8_t`
+// - Because Chromium bans `std::byte`, `as_[writable_]bytes()` use `uint8_t`
 //   instead of `std::byte` as the returned element type.
-// - For convenience, provides `as_[writeable_]chars()` and `as_string_view()`
+// - For convenience, provides `as_[writable_]chars()` and `as_string_view()`
 //   to convert to other "view of bytes"-like objects.
 // - For convenience, provides an `operator<<()` overload that accepts a span
 //   and prints a byte representation. Also provides a `PrintTo()` overload to
@@ -235,12 +273,22 @@
 //   convert `basic_cstring_view<T>` to spans, preserving the null terminator.
 // - For convenience, provides `as_[writable_]byte_span()` to convert
 //   spanifiable objects directly to byte spans.
+// - For safety, bans types which do not meet
+//   `std::has_unique_object_representations_v<>` from all byte span conversion
+//   functions by default. See more detailed comments above for workarounds.
 
 namespace base {
 
 // [span.syn]: Constants
 inline constexpr size_t dynamic_extent = std::numeric_limits<size_t>::max();
 
+// Provides a compile-time fixed extent to the `count` argument of the span
+// constructor.
+//
+// (Not in `std::`.)
+template <size_t N>
+using fixed_extent = std::integral_constant<size_t, N>;
+
 // [views.span]: class template `span<>`
 template <typename ElementType,
           size_t Extent = dynamic_extent,
@@ -266,17 +314,23 @@
 
 namespace base {
 
-namespace internal {
-
-// Exposition-only concept from [span.syn]
+// Allows global use of a type for conversion to byte spans.
 template <typename T>
-concept IntegralConstantLike =
-    std::is_integral_v<decltype(T::value)> &&
-    !std::is_same_v<bool, std::remove_const_t<decltype(T::value)>> &&
-    std::convertible_to<T, decltype(T::value)> &&
-    std::equality_comparable_with<T, decltype(T::value)> &&
-    std::bool_constant<T() == T::value>::value &&
-    std::bool_constant<static_cast<decltype(T::value)>(T()) == T::value>::value;
+inline constexpr bool kCanSafelyConvertToByteSpan =
+    std::has_unique_object_representations_v<T>;
+template <typename T, typename U>
+inline constexpr bool kCanSafelyConvertToByteSpan<std::pair<T, U>> =
+    kCanSafelyConvertToByteSpan<std::remove_cvref_t<T>> &&
+    kCanSafelyConvertToByteSpan<std::remove_cvref_t<U>>;
+
+// Type tag to provide to byte span conversion functions to bypass
+// `std::has_unique_object_representations_v<>` check.
+struct allow_nonunique_obj_t {
+  explicit allow_nonunique_obj_t() = default;
+};
+inline constexpr allow_nonunique_obj_t allow_nonunique_obj{};
+
+namespace internal {
 
 // Exposition-only concept from [span.syn]
 template <typename T>
@@ -296,25 +350,32 @@
 template <typename T>
 concept SpanConstructibleFrom = requires(T&& t) { span(std::forward<T>(t)); };
 
+// Returns the element type of `span(T)`.
+template <typename T>
+  requires SpanConstructibleFrom<T>
+using ElementTypeOfSpanConstructedFrom =
+    typename decltype(span(std::declval<T>()))::element_type;
+
 template <typename T, typename It>
 concept CompatibleIter =
     std::contiguous_iterator<It> &&
     LegalDataConversion<std::remove_reference_t<std::iter_reference_t<It>>, T>;
 
-// Disallow general-purpose range construction from types that have dedicated
-// constructors.
-// Arrays should go through the array constructors.
+// True when `T` is a `span`.
 template <typename T>
-inline constexpr bool kCompatibleRangeType = !std::is_array_v<T>;
-// `span`s should go through the copy constructor.
-template <typename T, size_t N, typename P>
-inline constexpr bool kCompatibleRangeType<span<T, N, P>> = false;
+inline constexpr bool kIsSpan = false;
+template <typename ElementType, size_t Extent, typename InternalPtrType>
+inline constexpr bool kIsSpan<span<ElementType, Extent, InternalPtrType>> =
+    true;
 
 template <typename T, typename R>
 concept CompatibleRange =
     std::ranges::contiguous_range<R> && std::ranges::sized_range<R> &&
-    (std::ranges::borrowed_range<R> ||
-     std::is_const_v<T>)&&kCompatibleRangeType<std::remove_cvref_t<R>> &&
+    (std::ranges::borrowed_range<R> || (std::is_const_v<T>)) &&
+    // `span`s should go through the copy constructor.
+    (!kIsSpan<std::remove_cvref_t<R>> &&
+     // Arrays should go through the array constructors.
+     (!std::is_array_v<std::remove_cvref_t<R>>)) &&
     LegalDataConversion<
         std::remove_reference_t<std::ranges::range_reference_t<R>>,
         T>;
@@ -340,6 +401,30 @@
 inline constexpr size_t kComputedExtent =
     kComputedExtentImpl<std::remove_cvref_t<T>>;
 
+template <typename T>
+concept CanSafelyConvertToByteSpan =
+    kCanSafelyConvertToByteSpan<std::remove_cvref_t<T>>;
+
+template <typename T>
+concept ByteSpanConstructibleFrom =
+    SpanConstructibleFrom<T> &&
+    CanSafelyConvertToByteSpan<ElementTypeOfSpanConstructedFrom<T>>;
+
+// Allows one-off use of a type that wouldn't normally convert to a byte span.
+template <typename T>
+concept CanSafelyConvertNonUniqueToByteSpan =
+    // Non-trivially-copyable elements usually aren't safe even to serialize;
+    // when they are that's normally unconditionally true and can be handled
+    // using `kCanSafelyConvertToByteSpan`.
+    std::is_trivially_copyable_v<T> &&
+    // If this fails, `allow_nonunique_obj` wasn't necessary.
+    !std::has_unique_object_representations_v<T>;
+
+template <typename T>
+concept ByteSpanConstructibleFromNonUnique =
+    SpanConstructibleFrom<T> &&
+    CanSafelyConvertNonUniqueToByteSpan<ElementTypeOfSpanConstructedFrom<T>>;
+
 template <typename ByteType,
           typename ElementType,
           size_t Extent,
@@ -397,7 +482,7 @@
   UNSAFE_BUFFER_USAGE constexpr explicit span(It first,
                                               StrictNumeric<size_type> count)
       : data_(to_address(first)) {
-    CHECK_EQ(size_type{count}, extent);
+    CHECK(size_type{count} == extent);
 
     // Non-zero `count` implies non-null `data_`. Use `SpanOrSize<T>` to
     // represent a size that might not be accompanied by the actual data.
@@ -597,7 +682,7 @@
     return UNSAFE_BUFFERS(span<element_type, Count>(data(), Count));
   }
   constexpr auto first(StrictNumeric<size_type> count) const {
-    CHECK_LE(size_type{count}, extent);
+    CHECK(size_type{count} <= extent);
     // SAFETY: `data()` points to at least `extent` elements, so the new data
     // scope is a strict subset of the old.
     return UNSAFE_BUFFERS(span<element_type>(data(), count));
@@ -614,7 +699,7 @@
         span<element_type, Count>(data() + (extent - Count), Count));
   }
   constexpr auto last(StrictNumeric<size_type> count) const {
-    CHECK_LE(size_type{count}, extent);
+    CHECK(size_type{count} <= extent);
     // SAFETY: `data()` points to at least `extent` elements, so the new data
     // scope is a strict subset of the old.
     return UNSAFE_BUFFERS(
@@ -641,19 +726,21 @@
       return UNSAFE_BUFFERS(span<element_type, Count>(data() + Offset, Count));
     }
   }
-  constexpr auto subspan(
-      StrictNumeric<size_type> offset,
-      StrictNumeric<size_type> count = dynamic_extent) const {
-    CHECK_LE(size_type{offset}, extent);
+  constexpr auto subspan(StrictNumeric<size_type> offset) const {
+    CHECK(size_type{offset} <= extent);
     const size_type remaining = extent - size_type{offset};
-    if (count == dynamic_extent) {
-      // SAFETY: `data()` points to at least `extent` elements, so `offset`
-      // specifies a valid element index or the past-the-end index, and
-      // `remaining` cannot index past-the-end elements.
-      return UNSAFE_BUFFERS(
-          span<element_type>(data() + size_type{offset}, remaining));
-    }
-    CHECK_LE(size_type{count}, remaining);
+    // SAFETY: `data()` points to at least `extent` elements, so `offset`
+    // specifies a valid element index or the past-the-end index, and
+    // `remaining` cannot index past-the-end elements.
+    return UNSAFE_BUFFERS(
+        span<element_type>(data() + size_type{offset}, remaining));
+  }
+  constexpr auto subspan(StrictNumeric<size_type> offset,
+                         StrictNumeric<size_type> count) const {
+    DCHECK(size_type{count} != dynamic_extent)
+        << "base does not allow dynamic_extent in two-arg subspan()";
+    CHECK(size_type{offset} <= size() &&
+          size_type{count} <= size() - size_type{offset});
     // SAFETY: `data()` points to at least `extent` elements, so `offset`
     // specifies a valid element index or the past-the-end index, and `count` is
     // no larger than the number of remaining valid elements.
@@ -695,15 +782,15 @@
     requires(std::is_const_v<element_type> &&
              std::equality_comparable<const element_type>)
   {
-    return std::ranges::equal(span<const element_type>(lhs),
-                              span<const element_type>(rhs));
+    return std::ranges::equal(span<const element_type, extent>(lhs),
+                              span<const element_type, extent>(rhs));
   }
   friend constexpr bool operator==(span lhs,
                                    span<const element_type, extent> rhs)
     requires(!std::is_const_v<element_type> &&
              std::equality_comparable<const element_type>)
   {
-    return std::ranges::equal(span<const element_type>(lhs), rhs);
+    return std::ranges::equal(span<const element_type, extent>(lhs), rhs);
   }
   template <typename OtherElementType,
             size_t OtherExtent,
@@ -714,7 +801,7 @@
   friend constexpr bool operator==(
       span lhs,
       span<OtherElementType, OtherExtent, OtherInternalPtrType> rhs) {
-    return std::ranges::equal(span<const element_type>(lhs),
+    return std::ranges::equal(span<const element_type, extent>(lhs),
                               span<const OtherElementType, OtherExtent>(rhs));
   }
 
@@ -782,7 +869,7 @@
   constexpr pointer get_at(StrictNumeric<size_type> idx) const
     requires(extent > 0)
   {
-    CHECK_LT(size_type{idx}, extent);
+    CHECK(size_type{idx} < extent);
     // SAFETY: `data()` points to at least `extent` elements, so `idx` must be
     // the index of a valid element.
     return UNSAFE_BUFFERS(data() + size_type{idx});
@@ -968,7 +1055,7 @@
   constexpr void copy_from(span<const element_type> other)
     requires(!std::is_const_v<element_type>)
   {
-    CHECK_EQ(size(), other.size());
+    CHECK(size() == other.size());
     if (std::is_constant_evaluated()) {
       // Comparing pointers to different objects at compile time yields
       // unspecified behavior, which would halt compilation. Instead,
@@ -1003,7 +1090,7 @@
       return;
     }
 
-    CHECK_EQ(size(), other.size());
+    CHECK(size() == other.size());
     // See comments in `copy_from()` re: use of templated comparison objects.
     DCHECK(std::less_equal{}(to_address(end()), to_address(other.begin())) ||
            std::greater_equal{}(to_address(begin()), to_address(other.end())));
@@ -1026,13 +1113,13 @@
   // First `count` elements.
   template <size_t Count>
   constexpr auto first() const {
-    CHECK_LE(Count, size());
+    CHECK(Count <= size());
     // SAFETY: `data()` points to at least `size()` elements, so the new data
     // scope is a strict subset of the old.
     return UNSAFE_BUFFERS(span<element_type, Count>(data(), Count));
   }
   constexpr auto first(StrictNumeric<size_t> count) const {
-    CHECK_LE(size_type{count}, size());
+    CHECK(size_type{count} <= size());
     // SAFETY: `data()` points to at least `size()` elements, so the new data
     // scope is a strict subset of the old.
     return UNSAFE_BUFFERS(span<element_type>(data(), count));
@@ -1041,14 +1128,14 @@
   // Last `count` elements.
   template <size_t Count>
   constexpr auto last() const {
-    CHECK_LE(Count, size());
+    CHECK(Count <= size());
     // SAFETY: `data()` points to at least `size()` elements, so the new data
     // scope is a strict subset of the old.
     return UNSAFE_BUFFERS(
         span<element_type, Count>(data() + (size() - Count), Count));
   }
   constexpr auto last(StrictNumeric<size_type> count) const {
-    CHECK_LE(size_type{count}, size());
+    CHECK(size_type{count} <= size());
     // SAFETY: `data()` points to at least `size()` elements, so the new data
     // scope is a strict subset of the old.
     return UNSAFE_BUFFERS(
@@ -1058,7 +1145,7 @@
   // `count` elements beginning at `offset`.
   template <size_t Offset, size_t Count = dynamic_extent>
   constexpr auto subspan() const {
-    CHECK_LE(Offset, size());
+    CHECK(Offset <= size());
     const size_type remaining = size() - Offset;
     if constexpr (Count == dynamic_extent) {
       // SAFETY: `data()` points to at least `size()` elements, so `Offset`
@@ -1067,25 +1154,27 @@
       return UNSAFE_BUFFERS(
           span<element_type, Count>(data() + Offset, remaining));
     }
-    CHECK_LE(Count, remaining);
+    CHECK(Count <= remaining);
     // SAFETY: `data()` points to at least `size()` elements, so `Offset`
     // specifies a valid element index or the past-the-end index, and `Count` is
     // no larger than the number of remaining valid elements.
     return UNSAFE_BUFFERS(span<element_type, Count>(data() + Offset, Count));
   }
-  constexpr auto subspan(
-      StrictNumeric<size_type> offset,
-      StrictNumeric<size_type> count = dynamic_extent) const {
-    CHECK_LE(size_type{offset}, size());
+  constexpr auto subspan(StrictNumeric<size_type> offset) const {
+    CHECK(size_type{offset} <= size());
     const size_type remaining = size() - size_type{offset};
-    if (count == dynamic_extent) {
-      // SAFETY: `data()` points to at least `size()` elements, so `offset`
-      // specifies a valid element index or the past-the-end index, and
-      // `remaining` cannot index past-the-end elements.
-      return UNSAFE_BUFFERS(
-          span<element_type>(data() + size_type{offset}, remaining));
-    }
-    CHECK_LE(size_type{count}, remaining);
+    // SAFETY: `data()` points to at least `size()` elements, so `offset`
+    // specifies a valid element index or the past-the-end index, and
+    // `remaining` cannot index past-the-end elements.
+    return UNSAFE_BUFFERS(
+        span<element_type>(data() + size_type{offset}, remaining));
+  }
+  constexpr auto subspan(StrictNumeric<size_type> offset,
+                         StrictNumeric<size_type> count) const {
+    DCHECK(size_type{count} != dynamic_extent)
+        << "base does not allow dynamic_extent in two-arg subspan()";
+    CHECK(size_type{offset} <= size() &&
+          size_type{count} <= size() - size_type{offset});
     // SAFETY: `data()` points to at least `size()` elements, so `offset`
     // specifies a valid element index or the past-the-end index, and `count` is
     // no larger than the number of remaining valid elements.
@@ -1100,13 +1189,40 @@
   // `split_at_mut()`.)
   template <size_t Offset>
   constexpr auto split_at() const {
-    CHECK_LE(Offset, size());
+    CHECK(Offset <= size());
     return std::pair(first<Offset>(), subspan<Offset>());
   }
   constexpr auto split_at(StrictNumeric<size_type> offset) const {
     return std::pair(first(offset), subspan(offset));
   }
 
+  // Returns a span of the first N elements, removing them.
+  // When `Offset` is outside the span, the underlying call will `CHECK()`. For
+  // a non-fatal alternative, consider `SpanReader`.
+  //
+  // (Not in `std::span`; convenient for processing a stream of disparate
+  // objects or looping over elements.)
+  template <size_t Offset>
+  constexpr auto take_first() {
+    const auto [first, rest] = split_at<Offset>();
+    *this = rest;
+    return first;
+  }
+  // When `offset` is outside the span, the underlying call will `CHECK()`.
+  constexpr auto take_first(StrictNumeric<size_type> offset) {
+    const auto [first, rest] = split_at(offset);
+    *this = rest;
+    return first;
+  }
+
+  // Returns the first element, removing it.
+  // When `empty()`, the underlying call will `CHECK()`. For a non-fatal
+  // alternative, consider `SpanReader`.
+  //
+  // (Not in `std::span`; convenient for processing a stream of disparate
+  // objects or looping over elements.)
+  constexpr auto take_first_elem() { return take_first<1>().front(); }
+
   // [span.obs]: Observers
   // Size.
   constexpr size_type size() const noexcept { return size_; }
@@ -1202,7 +1318,7 @@
   //
   // (Not in `std::`; necessary when underlying memory is not yet initialized.)
   constexpr pointer get_at(StrictNumeric<size_type> idx) const {
-    CHECK_LT(size_type{idx}, size());
+    CHECK(size_type{idx} < size());
     // SAFETY: `data()` points to at least `size()` elements, so `idx` must be
     // the index of a valid element.
     return UNSAFE_BUFFERS(data() + size_type{idx});
@@ -1287,29 +1403,59 @@
 
 // [span.objectrep]: Views of object representation
 template <typename ElementType, size_t Extent, typename InternalPtrType>
+  requires(internal::CanSafelyConvertToByteSpan<ElementType>)
 constexpr auto as_bytes(span<ElementType, Extent, InternalPtrType> s) {
   return internal::as_byte_span<const uint8_t>(s);
 }
 template <typename ElementType, size_t Extent, typename InternalPtrType>
-  requires(!std::is_const_v<ElementType>)
+  requires(internal::CanSafelyConvertNonUniqueToByteSpan<ElementType>)
+constexpr auto as_bytes(allow_nonunique_obj_t,
+                        span<ElementType, Extent, InternalPtrType> s) {
+  return internal::as_byte_span<const uint8_t>(s);
+}
+template <typename ElementType, size_t Extent, typename InternalPtrType>
+  requires(internal::CanSafelyConvertToByteSpan<ElementType> &&
+           !std::is_const_v<ElementType>)
 constexpr auto as_writable_bytes(span<ElementType, Extent, InternalPtrType> s) {
   return internal::as_byte_span<uint8_t>(s);
 }
+template <typename ElementType, size_t Extent, typename InternalPtrType>
+  requires(internal::CanSafelyConvertNonUniqueToByteSpan<ElementType> &&
+           !std::is_const_v<ElementType>)
+constexpr auto as_writable_bytes(allow_nonunique_obj_t,
+                                 span<ElementType, Extent, InternalPtrType> s) {
+  return internal::as_byte_span<uint8_t>(s);
+}
 
-// Like `as_[writeable_]bytes()`, but uses `[const] char` rather than `[const]
+// Like `as_[writable_]bytes()`, but uses `[const] char` rather than `[const]
 // uint8_t`.
 //
 // (Not in `std::`; eases span adoption in Chromium, which uses `char` in many
 // cases that rightfully should be `uint8_t`.)
 template <typename ElementType, size_t Extent, typename InternalPtrType>
+  requires(internal::CanSafelyConvertToByteSpan<ElementType>)
 constexpr auto as_chars(span<ElementType, Extent, InternalPtrType> s) {
   return internal::as_byte_span<const char>(s);
 }
 template <typename ElementType, size_t Extent, typename InternalPtrType>
-  requires(!std::is_const_v<ElementType>)
+  requires(internal::CanSafelyConvertNonUniqueToByteSpan<ElementType>)
+constexpr auto as_chars(allow_nonunique_obj_t,
+                        span<ElementType, Extent, InternalPtrType> s) {
+  return internal::as_byte_span<const char>(s);
+}
+template <typename ElementType, size_t Extent, typename InternalPtrType>
+  requires(internal::CanSafelyConvertToByteSpan<ElementType> &&
+           !std::is_const_v<ElementType>)
 constexpr auto as_writable_chars(span<ElementType, Extent, InternalPtrType> s) {
   return internal::as_byte_span<char>(s);
 }
+template <typename ElementType, size_t Extent, typename InternalPtrType>
+  requires(internal::CanSafelyConvertNonUniqueToByteSpan<ElementType> &&
+           !std::is_const_v<ElementType>)
+constexpr auto as_writable_chars(allow_nonunique_obj_t,
+                                 span<ElementType, Extent, InternalPtrType> s) {
+  return internal::as_byte_span<char>(s);
+}
 
 // Converts a span over byte-like elements to `std::string_view`.
 //
@@ -1419,13 +1565,26 @@
 //
 // (Not in `std::`.)
 template <typename T>
+  requires(internal::CanSafelyConvertToByteSpan<T>)
 constexpr auto byte_span_from_ref(const T& t LIFETIME_BOUND) {
   return as_bytes(span_from_ref(t));
 }
 template <typename T>
+  requires(internal::CanSafelyConvertNonUniqueToByteSpan<T>)
+constexpr auto byte_span_from_ref(allow_nonunique_obj_t,
+                                  const T& t LIFETIME_BOUND) {
+  return as_bytes(allow_nonunique_obj, span_from_ref(t));
+}
+template <typename T>
+  requires(internal::CanSafelyConvertToByteSpan<T>)
 constexpr auto byte_span_from_ref(T& t LIFETIME_BOUND) {
   return as_writable_bytes(span_from_ref(t));
 }
+template <typename T>
+  requires(internal::CanSafelyConvertNonUniqueToByteSpan<T>)
+constexpr auto byte_span_from_ref(allow_nonunique_obj_t, T& t LIFETIME_BOUND) {
+  return as_writable_bytes(allow_nonunique_obj, span_from_ref(t));
+}
 
 // Converts a `const CharT[]` literal to a `span<const CharT>`, omitting the
 // trailing '\0' (internal '\0's, if any, are preserved). For comparison:
@@ -1506,39 +1665,71 @@
 //
 // (Not in `std::`.)
 template <int&... ExplicitArgumentBarrier, typename T>
-  requires(internal::SpanConstructibleFrom<const T&>)
+  requires(internal::ByteSpanConstructibleFrom<const T&>)
 constexpr auto as_byte_span(const T& t LIFETIME_BOUND) {
   return as_bytes(span(t));
 }
 template <int&... ExplicitArgumentBarrier, typename T>
-  requires(internal::SpanConstructibleFrom<const T&> &&
+  requires(internal::ByteSpanConstructibleFromNonUnique<const T&>)
+constexpr auto as_byte_span(allow_nonunique_obj_t, const T& t LIFETIME_BOUND) {
+  return as_bytes(allow_nonunique_obj, span(t));
+}
+template <int&... ExplicitArgumentBarrier, typename T>
+  requires(internal::ByteSpanConstructibleFrom<const T&> &&
            std::ranges::borrowed_range<T>)
 constexpr auto as_byte_span(const T& t) {
   return as_bytes(span(t));
 }
+template <int&... ExplicitArgumentBarrier, typename T>
+  requires(internal::ByteSpanConstructibleFromNonUnique<const T&> &&
+           std::ranges::borrowed_range<T>)
+constexpr auto as_byte_span(allow_nonunique_obj_t, const T& t) {
+  return as_bytes(allow_nonunique_obj, span(t));
+}
 // Array arguments require dedicated specializations because if only the
 // generalized functions are available, the compiler cannot deduce the template
 // parameter.
 template <int&... ExplicitArgumentBarrier, typename ElementType, size_t Extent>
+  requires(internal::CanSafelyConvertToByteSpan<ElementType>)
 constexpr auto as_byte_span(const ElementType (&arr LIFETIME_BOUND)[Extent]) {
   return as_bytes(span<const ElementType, Extent>(arr));
 }
+template <int&... ExplicitArgumentBarrier, typename ElementType, size_t Extent>
+  requires(internal::CanSafelyConvertNonUniqueToByteSpan<ElementType>)
+constexpr auto as_byte_span(allow_nonunique_obj_t,
+                            const ElementType (&arr LIFETIME_BOUND)[Extent]) {
+  return as_bytes(allow_nonunique_obj, span<const ElementType, Extent>(arr));
+}
 template <int&... ExplicitArgumentBarrier, typename T>
-  requires(internal::SpanConstructibleFrom<T &&> &&
-           !std::is_const_v<
-               typename decltype(span(std::declval<T>()))::element_type>)
+  requires(internal::ByteSpanConstructibleFrom<T &&> &&
+           !std::is_const_v<internal::ElementTypeOfSpanConstructedFrom<T>>)
 // NOTE: `t` is not marked as lifetimebound because the "non-const
 // `element_type`" requirement above will in turn require `T` to be a borrowed
 // range.
 constexpr auto as_writable_byte_span(T&& t) {
   return as_writable_bytes(span(t));
 }
+template <int&... ExplicitArgumentBarrier, typename T>
+  requires(internal::ByteSpanConstructibleFromNonUnique<T &&> &&
+           !std::is_const_v<internal::ElementTypeOfSpanConstructedFrom<T>>)
+constexpr auto as_writable_byte_span(allow_nonunique_obj_t, T&& t) {
+  return as_writable_bytes(allow_nonunique_obj, span(t));
+}
 template <int&... ExplicitArgumentBarrier, typename ElementType, size_t Extent>
-  requires(!std::is_const_v<ElementType>)
+  requires(internal::CanSafelyConvertToByteSpan<ElementType> &&
+           !std::is_const_v<ElementType>)
 constexpr auto as_writable_byte_span(
     ElementType (&arr LIFETIME_BOUND)[Extent]) {
   return as_writable_bytes(span<ElementType, Extent>(arr));
 }
+template <int&... ExplicitArgumentBarrier, typename ElementType, size_t Extent>
+  requires(internal::CanSafelyConvertNonUniqueToByteSpan<ElementType> &&
+           !std::is_const_v<ElementType>)
+constexpr auto as_writable_byte_span(
+    allow_nonunique_obj_t,
+    ElementType (&arr LIFETIME_BOUND)[Extent]) {
+  return as_writable_bytes(allow_nonunique_obj, span<ElementType, Extent>(arr));
+}
 
 }  // namespace base
 
diff --git a/tot/base/containers/span_nocompile.nc b/tot/base/containers/span_nocompile.nc
index ca06bbc..29685024 100644
--- a/tot/base/containers/span_nocompile.nc
+++ b/tot/base/containers/span_nocompile.nc
@@ -11,6 +11,7 @@
 #include <set>
 #include <string>
 #include <string_view>
+#include <type_traits>
 #include <vector>
 
 namespace base {
@@ -338,6 +339,42 @@
   (void)(span(non_arr) == span(non_arr));  // expected-error@*:* {{invalid operands to binary expression}}
 }
 
+void ByteConversionsFromNonUnique() {
+  // Test that byte span constructions from a type the does not meet
+  // `std::has_unique_object_representations_v<>` fail by default.
+  struct S {
+    float f = 0;
+  };
+  static_assert(!std::has_unique_object_representations_v<S>);
+
+  // `as_[writable_](bytes,chars)()`
+  S arr[] = {{1}, {2}, {3}};
+  span sp(arr);
+  as_bytes(sp);           // expected-error {{no matching function for call}}
+  as_writable_bytes(sp);  // expected-error {{no matching function for call}}
+  as_chars(sp);           // expected-error {{no matching function for call}}
+  as_writable_chars(sp);  // expected-error {{no matching function for call}}
+
+  // `byte_span_from_ref()`
+  const S const_obj;
+  S obj;
+  // Read-only
+  byte_span_from_ref(const_obj);  // expected-error {{no matching function for call}}
+  // Writable
+  byte_span_from_ref(obj);        // expected-error {{no matching function for call}}
+
+  // `as_[writable_]byte_span()`
+  std::vector<S> vec;
+  // Non-borrowed range
+  as_byte_span(std::vector<S>());           // expected-error {{no matching function for call}}
+  // Borrowed range
+  as_byte_span(vec);                        // expected-error {{no matching function for call}}
+  as_writable_byte_span(vec);               // expected-error {{no matching function for call}}
+  // Array
+  as_byte_span(arr);                        // expected-error {{no matching function for call}}
+  as_writable_byte_span(arr);               // expected-error {{no matching function for call}}
+}
+
 void AsStringViewNotBytes() {
   const int arr[] = {1, 2, 3};
   as_string_view(span(arr));  // expected-error@*:* {{no matching function for call to 'as_string_view'}}
diff --git a/tot/base/containers/span_unittest.cc b/tot/base/containers/span_unittest.cc
index 6c92d80..d009256 100644
--- a/tot/base/containers/span_unittest.cc
+++ b/tot/base/containers/span_unittest.cc
@@ -17,13 +17,13 @@
 #include <utility>
 #include <vector>
 
+#include "base/bit_cast.h"
 #include "base/compiler_specific.h"
 #include "base/containers/adapters.h"
 #include "base/containers/checked_iterators.h"
 #include "base/debug/alias.h"
 #include "base/memory/raw_span.h"
 #include "base/numerics/byte_conversions.h"
-#include "base/ranges/algorithm.h"
 #include "base/strings/cstring_view.h"
 #include "base/strings/utf_ostream_operators.h"
 #include "base/test/gtest_util.h"
@@ -48,10 +48,8 @@
         std::is_same_v<decltype(span(v.begin(), v.size())), span<const int>>);
     static_assert(
         std::is_same_v<decltype(span(v.data(), v.size())), span<const int>>);
-    static_assert(
-        std::is_same_v<decltype(span(v.cbegin(),
-                                     std::integral_constant<size_t, 0>())),
-                       span<const int, 0>>);
+    static_assert(std::is_same_v<decltype(span(v.cbegin(), fixed_extent<0>())),
+                                 span<const int, 0>>);
   }
 
   {
@@ -62,10 +60,8 @@
         std::is_same_v<decltype(span(v.begin(), v.size())), span<int>>);
     static_assert(
         std::is_same_v<decltype(span(v.data(), v.size())), span<int>>);
-    static_assert(
-        std::is_same_v<decltype(span(v.cbegin(),
-                                     std::integral_constant<size_t, 0>())),
-                       span<const int, 0>>);
+    static_assert(std::is_same_v<decltype(span(v.cbegin(), fixed_extent<0>())),
+                                 span<const int, 0>>);
   }
 
   {
@@ -181,6 +177,16 @@
   for (size_t i = 0; i < static_span.size(); ++i) {
     EXPECT_EQ(vector[i], static_span[i]);
   }
+
+  CHECK_GE(vector.size(), 6);
+  // SAFETY: the `CHECK_GE()` just above ensures the `6` below is a valid extent
+  // of `vector.data()`.
+  auto static_span_from_constant =
+      UNSAFE_BUFFERS(span(vector.data(), fixed_extent<6>()));
+  static_assert(
+      std::same_as<decltype(static_span_from_constant), span<int, 6>>);
+  EXPECT_EQ(vector.data(), static_span_from_constant.data());
+  EXPECT_EQ(vector.size(), static_span_from_constant.size());
 }
 
 TEST(SpanTest, ConstructFromDataAndZeroSize) {
@@ -1261,14 +1267,13 @@
   }
 }
 
-TEST(SpanTest, TemplatedSubspanFromDynamicSpan) {
+TEST(SpanTest, TemplatedSubspanOnDynamicSpan) {
   int array[] = {1, 2, 3};
-  span<int, 3> span(array);
+  span<int> span(array);
 
   {
     auto subspan = span.subspan<0>();
     EXPECT_EQ(span.data(), subspan.data());
-    static_assert(3 == decltype(subspan)::extent);
     EXPECT_THAT(subspan, ElementsAre(1, 2, 3));
   }
 
@@ -1277,7 +1282,6 @@
     // SAFETY: `array` has three elmenents, so `span` has three elements, so
     // `span.data() + 1` points within it.
     EXPECT_EQ(UNSAFE_BUFFERS(span.data() + 1), subspan.data());
-    static_assert(2 == decltype(subspan)::extent);
     EXPECT_THAT(subspan, ElementsAre(2, 3));
   }
 
@@ -1286,7 +1290,6 @@
     // SAFETY: `array` has three elmenents, so `span` has three elements, so
     // `span.data() + 2` points within it.
     EXPECT_EQ(UNSAFE_BUFFERS(span.data() + 2), subspan.data());
-    static_assert(1 == decltype(subspan)::extent);
     EXPECT_THAT(subspan, ElementsAre(3));
   }
 
@@ -1296,7 +1299,6 @@
     // `span.data() + 3` points to one byte beyond the object as permitted by
     // C++ specification.
     EXPECT_EQ(UNSAFE_BUFFERS(span.data() + 3), subspan.data());
-    static_assert(0 == decltype(subspan)::extent);
     EXPECT_THAT(subspan, IsEmpty());
   }
 
@@ -1647,7 +1649,7 @@
   static constexpr int kArray[] = {1, 6, 1, 8, 0};
   constexpr span<const int> span(kArray);
 
-  static_assert(ranges::equal(kArray, span));
+  static_assert(std::ranges::equal(kArray, span));
   static_assert(1 == span.begin()[0]);
   static_assert(1 == *(span.begin() += 0));
   static_assert(6 == *(span.begin() += 1));
@@ -1663,7 +1665,7 @@
   static constexpr int kArray[] = {1, 6, 1, 8, 0};
   constexpr span<const int> span(kArray);
 
-  EXPECT_TRUE(ranges::equal(Reversed(kArray), Reversed(span)));
+  EXPECT_TRUE(std::ranges::equal(Reversed(kArray), Reversed(span)));
 }
 
 TEST(SpanTest, AsBytes) {
@@ -1854,6 +1856,88 @@
   }
 }
 
+// Create some structs to test byte span conversion from non-unique-rep objects.
+namespace {
+struct NonUnique {
+  float f = 0;
+};
+static_assert(!std::has_unique_object_representations_v<NonUnique>);
+
+struct Allowlisted : NonUnique {};
+static_assert(!std::has_unique_object_representations_v<Allowlisted>);
+}  // namespace
+
+// Verify we can compile byte span conversions for the above with appropriate
+// carve-outs.
+template <>
+inline constexpr bool kCanSafelyConvertToByteSpan<Allowlisted> = true;
+TEST(SpanTest, ByteSpansFromNonUnique) {
+  // Note: This test is just a compile test, and assumes the functionality tests
+  // above are sufficient to verify that aspect.
+
+  {
+    static_assert(!internal::CanSafelyConvertToByteSpan<NonUnique>);
+
+    // `as_[writable_](bytes,chars)()`
+    NonUnique arr[] = {{1}, {2}, {3}};
+    span sp(arr);
+    as_bytes(allow_nonunique_obj, sp);
+    as_writable_bytes(allow_nonunique_obj, sp);
+    as_chars(allow_nonunique_obj, sp);
+    as_writable_chars(allow_nonunique_obj, sp);
+
+    // `byte_span_from_ref()`
+    const NonUnique const_obj;
+    NonUnique obj;
+    // Read-only
+    byte_span_from_ref(allow_nonunique_obj, const_obj);
+    // Writable
+    byte_span_from_ref(allow_nonunique_obj, obj);
+
+    // `as_[writable_]byte_span()`
+    std::vector<NonUnique> vec;
+    // Non-borrowed range
+    as_byte_span(allow_nonunique_obj, std::vector<NonUnique>());
+    // Borrowed range
+    as_byte_span(allow_nonunique_obj, vec);
+    as_writable_byte_span(allow_nonunique_obj, vec);
+    // Array
+    as_byte_span(allow_nonunique_obj, arr);
+    as_writable_byte_span(allow_nonunique_obj, arr);
+  }
+
+  {
+    static_assert(internal::CanSafelyConvertToByteSpan<Allowlisted>);
+
+    // `as_[writable_](bytes,chars)()`
+    Allowlisted arr[] = {{1}, {2}, {3}};
+    span sp(arr);
+    as_bytes(sp);
+    as_writable_bytes(sp);
+    as_chars(sp);
+    as_writable_chars(sp);
+
+    // `byte_span_from_ref()`
+    const Allowlisted const_obj;
+    Allowlisted obj;
+    // Read-only
+    byte_span_from_ref(const_obj);
+    // Writable
+    byte_span_from_ref(obj);
+
+    // `as_[writable_]byte_span()`
+    std::vector<Allowlisted> vec;
+    // Non-borrowed range
+    as_byte_span(std::vector<Allowlisted>());
+    // Borrowed range
+    as_byte_span(vec);
+    as_writable_byte_span(vec);
+    // Array
+    as_byte_span(arr);
+    as_writable_byte_span(arr);
+  }
+}
+
 TEST(SpanTest, AsStringView) {
   {
     constexpr uint8_t kArray[] = {'h', 'e', 'l', 'l', 'o'};
@@ -2025,7 +2109,7 @@
   int array[] = {5, 4, 3, 2, 1};
 
   span<int> dynamic_span = array;
-  ranges::sort(dynamic_span);
+  std::ranges::sort(dynamic_span);
   EXPECT_THAT(array, ElementsAre(1, 2, 3, 4, 5));
   std::sort(dynamic_span.rbegin(), dynamic_span.rend());
   EXPECT_THAT(array, ElementsAre(5, 4, 3, 2, 1));
@@ -2033,7 +2117,7 @@
   span<int, 5> static_span = array;
   std::sort(static_span.rbegin(), static_span.rend(), std::greater<>());
   EXPECT_THAT(array, ElementsAre(1, 2, 3, 4, 5));
-  ranges::sort(static_span, std::greater<>());
+  std::ranges::sort(static_span, std::greater<>());
   EXPECT_THAT(array, ElementsAre(5, 4, 3, 2, 1));
 }
 
@@ -2132,13 +2216,14 @@
   EXPECT_THAT(vec, ElementsAre(9, 9, 6));
 
   struct NonTrivial {
-    NonTrivial(int o) : i(o) {}
+    explicit NonTrivial(int o) : i(o) {}
     NonTrivial(const NonTrivial& o) : i(o) {}
     NonTrivial& operator=(const NonTrivial& o) {
-      i = o;
+      i = int{o};
       return *this;
     }
-    operator int() const { return i; }
+    explicit operator int() const { return i; }
+    bool operator==(int j) const { return i == j; }
     int i;
   };
 
@@ -2164,21 +2249,27 @@
     EXPECT_THAT(long_arr_is_long, ElementsAre(1, 2, 3, 4, 5, 6, 7));
   }
   {
-    NonTrivial long_arr_is_long[] = {1, 2, 3, 4, 5, 6, 7};
+    NonTrivial long_arr_is_long[] = {
+        NonTrivial(1), NonTrivial(2), NonTrivial(3), NonTrivial(4),
+        NonTrivial(5), NonTrivial(6), NonTrivial(7)};
     auto left = span(long_arr_is_long).first<5>();
     auto right = span(long_arr_is_long).last<5>();
     left.copy_from(right);
     EXPECT_THAT(long_arr_is_long, ElementsAre(3, 4, 5, 6, 7, 6, 7));
   }
   {
-    NonTrivial long_arr_is_long[] = {1, 2, 3, 4, 5, 6, 7};
+    NonTrivial long_arr_is_long[] = {
+        NonTrivial(1), NonTrivial(2), NonTrivial(3), NonTrivial(4),
+        NonTrivial(5), NonTrivial(6), NonTrivial(7)};
     auto left = span(long_arr_is_long).first<5>();
     auto right = span(long_arr_is_long).last<5>();
     right.copy_from(left);
     EXPECT_THAT(long_arr_is_long, ElementsAre(1, 2, 1, 2, 3, 4, 5));
   }
   {
-    NonTrivial long_arr_is_long[] = {1, 2, 3, 4, 5, 6, 7};
+    NonTrivial long_arr_is_long[] = {
+        NonTrivial(1), NonTrivial(2), NonTrivial(3), NonTrivial(4),
+        NonTrivial(5), NonTrivial(6), NonTrivial(7)};
     auto left = span(long_arr_is_long).first<5>();
     left.copy_from(left);
     EXPECT_THAT(long_arr_is_long, ElementsAre(1, 2, 3, 4, 5, 6, 7));
@@ -2206,21 +2297,27 @@
     EXPECT_THAT(long_arr_is_long, ElementsAre(1, 2, 3, 4, 5, 6, 7));
   }
   {
-    NonTrivial long_arr_is_long[] = {1, 2, 3, 4, 5, 6, 7};
+    NonTrivial long_arr_is_long[] = {
+        NonTrivial(1), NonTrivial(2), NonTrivial(3), NonTrivial(4),
+        NonTrivial(5), NonTrivial(6), NonTrivial(7)};
     auto left = span<NonTrivial>(long_arr_is_long).first(5u);
     auto right = span<NonTrivial>(long_arr_is_long).last(5u);
     left.copy_from(right);
     EXPECT_THAT(long_arr_is_long, ElementsAre(3, 4, 5, 6, 7, 6, 7));
   }
   {
-    NonTrivial long_arr_is_long[] = {1, 2, 3, 4, 5, 6, 7};
+    NonTrivial long_arr_is_long[] = {
+        NonTrivial(1), NonTrivial(2), NonTrivial(3), NonTrivial(4),
+        NonTrivial(5), NonTrivial(6), NonTrivial(7)};
     auto left = span<NonTrivial>(long_arr_is_long).first(5u);
     auto right = span<NonTrivial>(long_arr_is_long).last(5u);
     right.copy_from(left);
     EXPECT_THAT(long_arr_is_long, ElementsAre(1, 2, 1, 2, 3, 4, 5));
   }
   {
-    NonTrivial long_arr_is_long[] = {1, 2, 3, 4, 5, 6, 7};
+    NonTrivial long_arr_is_long[] = {
+        NonTrivial(1), NonTrivial(2), NonTrivial(3), NonTrivial(4),
+        NonTrivial(5), NonTrivial(6), NonTrivial(7)};
     auto left = span<NonTrivial>(long_arr_is_long).first(5u);
     left.copy_from(left);
     EXPECT_THAT(long_arr_is_long, ElementsAre(1, 2, 3, 4, 5, 6, 7));
@@ -2517,6 +2614,92 @@
   EXPECT_CHECK_DEATH({ dynamic_span.split_at<4u>(); });
 }
 
+TEST(SpanTest, TakeFirst) {
+  {
+    span<int> empty;
+    auto first = empty.take_first(0u);
+    EXPECT_TRUE(first.empty());
+    EXPECT_TRUE(empty.empty());
+  }
+
+  {
+    std::vector<int> vec = {4, 5, 6};
+    span<int> dynamic_span = span(vec);
+    auto first = dynamic_span.take_first(0u);
+    EXPECT_TRUE(first.empty());
+    EXPECT_THAT(dynamic_span, ElementsAre(4, 5, 6));
+  }
+  {
+    std::vector<int> vec = {4, 5, 6};
+    span<int> dynamic_span = span(vec);
+    auto first = dynamic_span.take_first(1u);
+    EXPECT_THAT(first, ElementsAre(4));
+    EXPECT_THAT(dynamic_span, ElementsAre(5, 6));
+  }
+  {
+    std::vector<int> vec = {4, 5, 6};
+    span<int> dynamic_span = span(vec);
+    auto first = dynamic_span.take_first(3u);
+    EXPECT_THAT(first, ElementsAre(4, 5, 6));
+    EXPECT_TRUE(dynamic_span.empty());
+  }
+  {
+    std::vector<int> vec = {4, 5, 6};
+    span<int> dynamic_span = span(vec);
+    // Invalid take will fail at runtime.
+    EXPECT_CHECK_DEATH({ dynamic_span.take_first(4u); });
+  }
+
+  // Fixed-size takes.
+  {
+    std::vector<int> vec = {4, 5, 6};
+    span<int> dynamic_span = span(vec);
+    auto first = dynamic_span.take_first<0>();
+    static_assert(std::same_as<decltype(first), span<int, 0>>);
+    EXPECT_THAT(dynamic_span, ElementsAre(4, 5, 6));
+  }
+  {
+    std::vector<int> vec = {4, 5, 6};
+    span<int> dynamic_span = span(vec);
+    auto first = dynamic_span.take_first<1>();
+    static_assert(std::same_as<decltype(first), span<int, 1>>);
+    EXPECT_THAT(first, ElementsAre(4));
+    EXPECT_THAT(dynamic_span, ElementsAre(5, 6));
+  }
+  {
+    std::vector<int> vec = {4, 5, 6};
+    span<int> dynamic_span = span(vec);
+    auto first = dynamic_span.take_first<3>();
+    static_assert(std::same_as<decltype(first), span<int, 3>>);
+    EXPECT_THAT(first, ElementsAre(4, 5, 6));
+    EXPECT_TRUE(dynamic_span.empty());
+  }
+  {
+    std::vector<int> vec = {4, 5, 6};
+    span<int> dynamic_span = span(vec);
+    // Invalid fixed-size take will fail at runtime.
+    EXPECT_CHECK_DEATH({ dynamic_span.take_first<4>(); });
+  }
+}
+
+TEST(SpanTest, TakeFirstElem) {
+  {
+    span<int> empty;
+    // Invalid take will fail at runtime.
+    EXPECT_CHECK_DEATH({ empty.take_first_elem(); });
+  }
+
+  {
+    std::vector<int> vec = {4, 5, 6};
+    span<int> dynamic_span = span(vec);
+    auto first = dynamic_span.take_first_elem();
+    static_assert(std::same_as<decltype(first), int>);
+    EXPECT_EQ(first, 4);
+    EXPECT_EQ(dynamic_span.size(), 2u);
+    EXPECT_EQ(dynamic_span.front(), 5);
+  }
+}
+
 TEST(SpanTest, CompareEquality) {
   static_assert(std::equality_comparable<int>);
   int32_t arr2[] = {1, 2};
@@ -3023,21 +3206,15 @@
     uint8_t array1[12];
     uint8_t array2[16];
     uint64_t array3[2];
-    span(array1).first(4u).copy_from(span(array2).subspan(8u, 4u));
-    span(array1).subspan(4u).copy_from(as_byte_span(array3).first(8u));
+    base::span<uint8_t> span1(array1);
+    span1.take_first<4>().copy_from(base::span(array2).subspan<8, 4>());
+    span1.copy_from(base::as_byte_span(array3).first<8>());
 
     {
       // Use `split_at()` to ensure `array1` is fully written.
-      auto [from2, from3] = span(array1).split_at(4u);
-      from2.copy_from(span(array2).subspan(8u, 4u));
-      from3.copy_from(as_byte_span(array3).first(8u));
-    }
-    {
-      // This can even be ensured at compile time (if sizes and offsets are all
-      // constants).
-      auto [from2, from3] = span(array1).split_at<4u>();
-      from2.copy_from(span(array2).subspan<8u, 4u>());
-      from3.copy_from(as_byte_span(array3).first<8u>());
+      auto [from2, from3] = base::span(array1).split_at<4>();
+      from2.copy_from(base::span(array2).subspan<8, 4>());
+      from3.copy_from(base::as_byte_span(array3).first<8>());
     }
   }
 
@@ -3054,9 +3231,9 @@
     uint8_t array1[12];
     uint64_t array2[2];
     Object array3[4];
-    std::ranges::fill(array1, 0u);
-    std::ranges::fill(array2, 0u);
-    std::ranges::fill(as_writable_byte_span(array3), 0u);
+    std::ranges::fill(array1, 0);
+    std::ranges::fill(array2, 0);
+    std::ranges::fill(as_writable_byte_span(array3), 0);
   }
 
   UNSAFE_BUFFERS({
diff --git a/tot/base/containers/span_writer.h b/tot/base/containers/span_writer.h
index 8ad91fe..2f684b7 100644
--- a/tot/base/containers/span_writer.h
+++ b/tot/base/containers/span_writer.h
@@ -78,11 +78,36 @@
 
   // For a SpanWriter over bytes, we can write integer values directly to those
   // bytes as a memcpy. Returns true if there was room remaining and the bytes
-  // were written.
+  // were written. The macros below implement the following methods:
   //
-  // This provides big, little, and native endian writing orders. Note that
-  // "native" order is almost never what you want; it only makes sense for byte
-  // buffers that stay in memory and are never written to the disk or network.
+  // bool WriteU8BigEndian(uint8_t)
+  // bool WriteU16BigEndian(uint16_t)
+  // bool WriteU32BigEndian(uint32_t)
+  // bool WriteU64BigEndian(uint64_t)
+  // bool WriteU8LittleEndian(uint8_t)
+  // bool WriteU16LittleEndian(uint16_t)
+  // bool WriteU32LittleEndian(uint32_t)
+  // bool WriteU64LittleEndian(uint64_t)
+  // bool WriteU8NativeEndian(uint8_t)
+  // bool WriteU16NativeEndian(uint16_t)
+  // bool WriteU32NativeEndian(uint32_t)
+  // bool WriteU64NativeEndian(uint64_t)
+  // bool WriteI8BigEndian(int8_t)
+  // bool WriteI16BigEndian(int16_t)
+  // bool WriteI32BigEndian(int32_t)
+  // bool WriteI64BigEndian(int64_t)
+  // bool WriteI8LittleEndian(int8_t)
+  // bool WriteI16LittleEndian(int16_t)
+  // bool WriteI32LittleEndian(int32_t)
+  // bool WriteI64LittleEndian(int64_t)
+  // bool WriteI8NativeEndian(int8_t)
+  // bool WriteI16NativeEndian(int16_t)
+  // bool WriteI32NativeEndian(int32_t)
+  // bool WriteI64NativeEndian(int64_t)
+  //
+  // Note that "native" order is almost never what you want; it only makes sense
+  // for byte buffers that stay in memory and are never written to the disk or
+  // network.
 #define BASE_SPANWRITER_WRITE(signchar, bitsize, endian, typeprefix) \
   constexpr bool Write##signchar##bitsize##endian##Endian(           \
       typeprefix##int##bitsize##_t value)                            \
@@ -99,9 +124,9 @@
   BASE_SPANWRITER_WRITE_BOTH_SIGNS(32, endian)             \
   BASE_SPANWRITER_WRITE_BOTH_SIGNS(64, endian)
 
-BASE_SPANWRITER_WRITE_BOTH_SIGNS_ALL_SIZES(Big)
-BASE_SPANWRITER_WRITE_BOTH_SIGNS_ALL_SIZES(Little)
-BASE_SPANWRITER_WRITE_BOTH_SIGNS_ALL_SIZES(Native)
+  BASE_SPANWRITER_WRITE_BOTH_SIGNS_ALL_SIZES(Big)
+  BASE_SPANWRITER_WRITE_BOTH_SIGNS_ALL_SIZES(Little)
+  BASE_SPANWRITER_WRITE_BOTH_SIGNS_ALL_SIZES(Native)
 
 #undef BASE_SPANWRITER_WRITE_BOTH_SIGNS_ALL_SIZES
 #undef BASE_SPANWRITER_WRITE_BOTH_SIGNS
diff --git a/tot/base/containers/to_value_list.h b/tot/base/containers/to_value_list.h
index 0f2f23f..643ccd0 100644
--- a/tot/base/containers/to_value_list.h
+++ b/tot/base/containers/to_value_list.h
@@ -5,14 +5,14 @@
 #ifndef BASE_CONTAINERS_TO_VALUE_LIST_H_
 #define BASE_CONTAINERS_TO_VALUE_LIST_H_
 
+#include <algorithm>
 #include <concepts>
 #include <functional>
 #include <iterator>
+#include <ranges>
 #include <type_traits>
 #include <utility>
 
-#include "base/ranges/algorithm.h"
-#include "base/ranges/ranges.h"
 #include "base/values.h"
 
 namespace base {
@@ -27,13 +27,14 @@
 //
 // Complexity: Exactly `size(range)` applications of `proj`.
 template <typename Range, typename Proj = std::identity>
-  requires requires { typename internal::range_category_t<Range>; } &&
-           std::indirectly_unary_invocable<Proj, ranges::iterator_t<Range>> &&
+  requires std::ranges::sized_range<Range> && std::ranges::input_range<Range> &&
+           std::indirectly_unary_invocable<Proj,
+                                           std::ranges::iterator_t<Range>> &&
            internal::AppendableToValueList<
-               std::indirect_result_t<Proj, ranges::iterator_t<Range>>>
+               std::indirect_result_t<Proj, std::ranges::iterator_t<Range>>>
 Value::List ToValueList(Range&& range, Proj proj = {}) {
-  auto container = Value::List::with_capacity(std::size(range));
-  ranges::for_each(
+  auto container = Value::List::with_capacity(std::ranges::size(range));
+  std::ranges::for_each(
       std::forward<Range>(range),
       [&]<typename T>(T&& value) { container.Append(std::forward<T>(value)); },
       std::move(proj));
diff --git a/tot/base/containers/to_vector.h b/tot/base/containers/to_vector.h
index 6213ec5..4748c7b 100644
--- a/tot/base/containers/to_vector.h
+++ b/tot/base/containers/to_vector.h
@@ -5,15 +5,14 @@
 #ifndef BASE_CONTAINERS_TO_VECTOR_H_
 #define BASE_CONTAINERS_TO_VECTOR_H_
 
+#include <algorithm>
 #include <functional>
 #include <iterator>
+#include <ranges>
 #include <type_traits>
 #include <utility>
 #include <vector>
 
-#include "base/ranges/algorithm.h"
-#include "base/ranges/ranges.h"
-
 namespace base {
 
 // Maps a container to a std::vector<> with respect to the provided projection.
@@ -26,15 +25,15 @@
 //
 // Complexity: Exactly `size(range)` applications of `proj`.
 template <typename Range, typename Proj = std::identity>
-  requires requires { typename internal::range_category_t<Range>; } &&
-           std::indirectly_unary_invocable<Proj, ranges::iterator_t<Range>>
+  requires std::ranges::sized_range<Range> && std::ranges::input_range<Range> &&
+           std::indirectly_unary_invocable<Proj, std::ranges::iterator_t<Range>>
 auto ToVector(Range&& range, Proj proj = {}) {
   using ProjectedType =
-      std::projected<ranges::iterator_t<Range>, Proj>::value_type;
+      std::projected<std::ranges::iterator_t<Range>, Proj>::value_type;
   std::vector<ProjectedType> container;
-  container.reserve(std::size(range));
-  ranges::transform(std::forward<Range>(range), std::back_inserter(container),
-                    std::move(proj));
+  container.reserve(std::ranges::size(range));
+  std::ranges::transform(std::forward<Range>(range),
+                         std::back_inserter(container), std::move(proj));
   return container;
 }
 
diff --git a/tot/base/containers/to_vector_unittest.cc b/tot/base/containers/to_vector_unittest.cc
index 9657d33..a9fb719 100644
--- a/tot/base/containers/to_vector_unittest.cc
+++ b/tot/base/containers/to_vector_unittest.cc
@@ -4,10 +4,11 @@
 
 #include "base/containers/to_vector.h"
 
+#include <ranges>
 #include <set>
 
+#include "base/containers/adapters.h"
 #include "base/containers/flat_set.h"
-#include "base/ranges/ranges.h"
 #include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
@@ -42,20 +43,29 @@
 }
 
 TEST(ToVectorTest, MoveOnly) {
-  struct MoveOnly {
-    MoveOnly() = default;
+  std::vector<std::unique_ptr<int>> v;
+  v.push_back(std::make_unique<int>(1));
+  v.push_back(std::make_unique<int>(2));
+  v.push_back(std::make_unique<int>(3));
 
-    MoveOnly(const MoveOnly&) = delete;
-    MoveOnly& operator=(const MoveOnly&) = delete;
+  auto v2 = base::ToVector(base::RangeAsRvalues(std::move(v)));
+  EXPECT_THAT(v2, testing::ElementsAre(testing::Pointee(1), testing::Pointee(2),
+                                       testing::Pointee(3)));
 
-    MoveOnly(MoveOnly&&) = default;
-    MoveOnly& operator=(MoveOnly&&) = default;
-  };
+  // The old vector should be consumed. The standard guarantees that a
+  // moved-from std::unique_ptr will be null.
+  // NOLINT(bugprone-use-after-move)
+  EXPECT_THAT(v, testing::ElementsAre(testing::IsNull(), testing::IsNull(),
+                                      testing::IsNull()));
 
-  std::vector<MoveOnly> vec(/*size=*/10);
-  auto mapped_vec = ToVector(std::move(vec),
-                             [](MoveOnly& value) { return std::move(value); });
-  EXPECT_EQ(mapped_vec.size(), 10U);
+  // Another method which is more verbose so not preferable.
+  auto v3 = base::ToVector(
+      std::move(v2), [](std::unique_ptr<int>& p) { return std::move(p); });
+  EXPECT_THAT(v3, testing::ElementsAre(testing::Pointee(1), testing::Pointee(2),
+                                       testing::Pointee(3)));
+  // NOLINT(bugprone-use-after-move)
+  EXPECT_THAT(v2, testing::ElementsAre(testing::IsNull(), testing::IsNull(),
+                                       testing::IsNull()));
 }
 
 template <typename C, typename Proj, typename T>
diff --git a/tot/base/containers/unique_ptr_adapters.h b/tot/base/containers/unique_ptr_adapters.h
index 6c6d1fa..c960f7a 100644
--- a/tot/base/containers/unique_ptr_adapters.h
+++ b/tot/base/containers/unique_ptr_adapters.h
@@ -64,7 +64,7 @@
 // Example usage:
 //   std::vector<std::unique_ptr<Foo>> vector;
 //   Foo* element = ...
-//   auto iter = base::ranges::find_if(vector, MatchesUniquePtr(element));
+//   auto iter = std::ranges::find_if(vector, MatchesUniquePtr(element));
 //
 // Example of erasing from container:
 //   EraseIf(v, MatchesUniquePtr(element));
diff --git a/tot/base/containers/unique_ptr_adapters_unittest.cc b/tot/base/containers/unique_ptr_adapters_unittest.cc
index f8dfc05..3ede4e5 100644
--- a/tot/base/containers/unique_ptr_adapters_unittest.cc
+++ b/tot/base/containers/unique_ptr_adapters_unittest.cc
@@ -4,11 +4,11 @@
 
 #include "base/containers/unique_ptr_adapters.h"
 
+#include <algorithm>
 #include <memory>
 #include <vector>
 
 #include "base/memory/raw_ptr.h"
-#include "base/ranges/algorithm.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace base {
@@ -110,39 +110,44 @@
   raw_ptr<Foo, DisableDanglingPtrDetection> dangling_foo3 = foo3;
 
   {
-    auto iter = ranges::find_if(v, UniquePtrMatcher<Foo>(foo1));
+    auto iter = std::ranges::find_if(v, UniquePtrMatcher<Foo>(foo1));
     ASSERT_TRUE(iter != v.end());
     EXPECT_EQ(foo1, iter->get());
-    EXPECT_TRUE(ranges::find_if(v, UniquePtrMatcher<Foo>(raw_foo1)) == iter);
-    EXPECT_TRUE(ranges::find_if(v, UniquePtrMatcher<Foo>(dangling_foo1)) ==
+    EXPECT_TRUE(std::ranges::find_if(v, UniquePtrMatcher<Foo>(raw_foo1)) ==
+                iter);
+    EXPECT_TRUE(std::ranges::find_if(v, UniquePtrMatcher<Foo>(dangling_foo1)) ==
                 iter);
   }
 
   {
-    auto iter = ranges::find_if(v, UniquePtrMatcher<Foo>(foo2));
+    auto iter = std::ranges::find_if(v, UniquePtrMatcher<Foo>(foo2));
     ASSERT_TRUE(iter != v.end());
     EXPECT_EQ(foo2, iter->get());
-    EXPECT_TRUE(ranges::find_if(v, UniquePtrMatcher<Foo>(raw_foo2)) == iter);
-    EXPECT_TRUE(ranges::find_if(v, UniquePtrMatcher<Foo>(dangling_foo2)) ==
+    EXPECT_TRUE(std::ranges::find_if(v, UniquePtrMatcher<Foo>(raw_foo2)) ==
+                iter);
+    EXPECT_TRUE(std::ranges::find_if(v, UniquePtrMatcher<Foo>(dangling_foo2)) ==
                 iter);
   }
 
   {
-    auto iter = ranges::find_if(v, MatchesUniquePtr(foo2));
+    auto iter = std::ranges::find_if(v, MatchesUniquePtr(foo2));
     ASSERT_TRUE(iter != v.end());
     EXPECT_EQ(foo2, iter->get());
-    EXPECT_TRUE(ranges::find_if(v, MatchesUniquePtr(raw_foo2)) == iter);
-    EXPECT_TRUE(ranges::find_if(v, MatchesUniquePtr(dangling_foo2)) == iter);
+    EXPECT_TRUE(std::ranges::find_if(v, MatchesUniquePtr(raw_foo2)) == iter);
+    EXPECT_TRUE(std::ranges::find_if(v, MatchesUniquePtr(dangling_foo2)) ==
+                iter);
   }
 
-  EXPECT_TRUE(ranges::find_if(v, UniquePtrMatcher<Foo>(foo3)) == v.end());
-  EXPECT_TRUE(ranges::find_if(v, UniquePtrMatcher<Foo>(raw_foo3)) == v.end());
-  EXPECT_TRUE(ranges::find_if(v, UniquePtrMatcher<Foo>(dangling_foo3)) ==
+  EXPECT_TRUE(std::ranges::find_if(v, UniquePtrMatcher<Foo>(foo3)) == v.end());
+  EXPECT_TRUE(std::ranges::find_if(v, UniquePtrMatcher<Foo>(raw_foo3)) ==
+              v.end());
+  EXPECT_TRUE(std::ranges::find_if(v, UniquePtrMatcher<Foo>(dangling_foo3)) ==
               v.end());
 
-  EXPECT_TRUE(ranges::find_if(v, MatchesUniquePtr(foo3)) == v.end());
-  EXPECT_TRUE(ranges::find_if(v, MatchesUniquePtr(raw_foo3)) == v.end());
-  EXPECT_TRUE(ranges::find_if(v, MatchesUniquePtr(dangling_foo3)) == v.end());
+  EXPECT_TRUE(std::ranges::find_if(v, MatchesUniquePtr(foo3)) == v.end());
+  EXPECT_TRUE(std::ranges::find_if(v, MatchesUniquePtr(raw_foo3)) == v.end());
+  EXPECT_TRUE(std::ranges::find_if(v, MatchesUniquePtr(dangling_foo3)) ==
+              v.end());
 
   raw_foo1 = nullptr;
   raw_foo2 = nullptr;
@@ -176,48 +181,51 @@
   raw_ptr<Foo, DisableDanglingPtrDetection> dangling_foo3 = foo3;
 
   {
-    auto iter = ranges::find_if(v, UniquePtrMatcher<Foo, TestDeleter>(foo1));
+    auto iter =
+        std::ranges::find_if(v, UniquePtrMatcher<Foo, TestDeleter>(foo1));
     ASSERT_TRUE(iter != v.end());
     EXPECT_EQ(foo1, iter->get());
-    EXPECT_TRUE(ranges::find_if(
+    EXPECT_TRUE(std::ranges::find_if(
                     v, UniquePtrMatcher<Foo, TestDeleter>(raw_foo1)) == iter);
-    EXPECT_TRUE(ranges::find_if(v, UniquePtrMatcher<Foo, TestDeleter>(
-                                       dangling_foo1)) == iter);
+    EXPECT_TRUE(std::ranges::find_if(v, UniquePtrMatcher<Foo, TestDeleter>(
+                                            dangling_foo1)) == iter);
   }
 
   {
-    auto iter = ranges::find_if(v, UniquePtrMatcher<Foo, TestDeleter>(foo2));
+    auto iter =
+        std::ranges::find_if(v, UniquePtrMatcher<Foo, TestDeleter>(foo2));
     ASSERT_TRUE(iter != v.end());
     EXPECT_EQ(foo2, iter->get());
-    EXPECT_TRUE(ranges::find_if(
+    EXPECT_TRUE(std::ranges::find_if(
                     v, UniquePtrMatcher<Foo, TestDeleter>(raw_foo2)) == iter);
-    EXPECT_TRUE(ranges::find_if(v, UniquePtrMatcher<Foo, TestDeleter>(
-                                       dangling_foo2)) == iter);
+    EXPECT_TRUE(std::ranges::find_if(v, UniquePtrMatcher<Foo, TestDeleter>(
+                                            dangling_foo2)) == iter);
   }
 
   {
-    auto iter = ranges::find_if(v, MatchesUniquePtr<Foo, TestDeleter>(foo2));
+    auto iter =
+        std::ranges::find_if(v, MatchesUniquePtr<Foo, TestDeleter>(foo2));
     ASSERT_TRUE(iter != v.end());
     EXPECT_EQ(foo2, iter->get());
-    EXPECT_TRUE(ranges::find_if(
+    EXPECT_TRUE(std::ranges::find_if(
                     v, MatchesUniquePtr<Foo, TestDeleter>(raw_foo2)) == iter);
-    EXPECT_TRUE(ranges::find_if(v, MatchesUniquePtr<Foo, TestDeleter>(
-                                       dangling_foo2)) == iter);
+    EXPECT_TRUE(std::ranges::find_if(v, MatchesUniquePtr<Foo, TestDeleter>(
+                                            dangling_foo2)) == iter);
   }
 
-  EXPECT_TRUE(ranges::find_if(v, UniquePtrMatcher<Foo, TestDeleter>(foo3)) ==
-              v.end());
-  EXPECT_TRUE(ranges::find_if(
+  EXPECT_TRUE(std::ranges::find_if(
+                  v, UniquePtrMatcher<Foo, TestDeleter>(foo3)) == v.end());
+  EXPECT_TRUE(std::ranges::find_if(
                   v, UniquePtrMatcher<Foo, TestDeleter>(raw_foo3)) == v.end());
-  EXPECT_TRUE(ranges::find_if(v, UniquePtrMatcher<Foo, TestDeleter>(
-                                     dangling_foo3)) == v.end());
+  EXPECT_TRUE(std::ranges::find_if(v, UniquePtrMatcher<Foo, TestDeleter>(
+                                          dangling_foo3)) == v.end());
 
-  EXPECT_TRUE(ranges::find_if(v, MatchesUniquePtr<Foo, TestDeleter>(foo3)) ==
-              v.end());
-  EXPECT_TRUE(ranges::find_if(
+  EXPECT_TRUE(std::ranges::find_if(
+                  v, MatchesUniquePtr<Foo, TestDeleter>(foo3)) == v.end());
+  EXPECT_TRUE(std::ranges::find_if(
                   v, MatchesUniquePtr<Foo, TestDeleter>(raw_foo3)) == v.end());
-  EXPECT_TRUE(ranges::find_if(v, MatchesUniquePtr<Foo, TestDeleter>(
-                                     dangling_foo3)) == v.end());
+  EXPECT_TRUE(std::ranges::find_if(v, MatchesUniquePtr<Foo, TestDeleter>(
+                                          dangling_foo3)) == v.end());
 
   raw_foo1 = nullptr;
   raw_foo2 = nullptr;
diff --git a/tot/base/containers/vector_buffer.h b/tot/base/containers/vector_buffer.h
index 1304daa..24f2ca9 100644
--- a/tot/base/containers/vector_buffer.h
+++ b/tot/base/containers/vector_buffer.h
@@ -2,6 +2,11 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#ifdef UNSAFE_BUFFERS_BUILD
+// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
+#pragma allow_unsafe_libc_calls
+#endif
+
 #ifndef BASE_CONTAINERS_VECTOR_BUFFER_H_
 #define BASE_CONTAINERS_VECTOR_BUFFER_H_
 
diff --git a/tot/base/containers/vector_buffer_unittest.cc b/tot/base/containers/vector_buffer_unittest.cc
index 30c9c43..052a2d8 100644
--- a/tot/base/containers/vector_buffer_unittest.cc
+++ b/tot/base/containers/vector_buffer_unittest.cc
@@ -51,14 +51,16 @@
 TEST(VectorBuffer, DeletePOD) {
   constexpr int size = 10;
   VectorBuffer<int> buffer(size);
-  for (int i = 0; i < size; i++)
+  for (int i = 0; i < size; i++) {
     buffer[i] = i + 1;
+  }
 
   VectorBuffer<int>::DestructRange(buffer.as_span());
 
   // Delete should do nothing.
-  for (int i = 0; i < size; i++)
+  for (int i = 0; i < size; i++) {
     EXPECT_EQ(i + 1, buffer[i]);
+  }
 }
 
 TEST(VectorBuffer, DeleteMoveOnly) {
@@ -85,12 +87,14 @@
   VectorBuffer<int> dest(size);
 
   VectorBuffer<int> original(size);
-  for (int i = 0; i < size; i++)
+  for (int i = 0; i < size; i++) {
     original[i] = i + 1;
+  }
 
   VectorBuffer<int>::MoveConstructRange(original.as_span(), dest.as_span());
-  for (int i = 0; i < size; i++)
+  for (int i = 0; i < size; i++) {
     EXPECT_EQ(i + 1, dest[i]);
+  }
 }
 
 TEST(VectorBuffer, MovableMove) {
diff --git a/tot/base/cpu.cc b/tot/base/cpu.cc
index 4a85be7..de92343 100644
--- a/tot/base/cpu.cc
+++ b/tot/base/cpu.cc
@@ -21,9 +21,10 @@
 #include <asm/hwcap.h>
 #include <sys/auxv.h>
 
+#include <algorithm>
+
 #include "base/files/file_util.h"
 #include "base/numerics/checked_math.h"
-#include "base/ranges/algorithm.h"
 #include "base/strings/string_number_conversions.h"
 #include "base/strings/string_split.h"
 #include "base/strings/string_util.h"
@@ -38,8 +39,8 @@
 
 #if defined(ARCH_CPU_X86_FAMILY)
 #if defined(COMPILER_MSVC)
-#include <intrin.h>
 #include <immintrin.h>  // For _xgetbv()
+#include <intrin.h>
 #endif
 #endif
 
@@ -139,8 +140,7 @@
 #else
   uint32_t eax, edx;
 
-  __asm__ volatile (
-    "xgetbv" : "=a"(eax), "=d"(edx) : "c"(xcr));
+  __asm__ volatile("xgetbv" : "=a"(eax), "=d"(edx) : "c"(xcr));
   return (static_cast<uint64_t>(edx) << 32) | eax;
 #endif  // defined(COMPILER_MSVC)
 }
@@ -153,7 +153,7 @@
 
 void CPU::Initialize() {
 #if defined(ARCH_CPU_X86_FAMILY)
-  int cpu_info[4] = {-1};
+  int cpu_info[4] = {-1, 0, 0, 0};
 
   // __cpuid with an InfoType argument of 0 returns the number of
   // valid Ids in CPUInfo[0] and the CPU identification string in
@@ -173,8 +173,8 @@
 
   // Interpret CPU feature information.
   if (num_ids > 0) {
-    int cpu_info7[4] = {0};
-    int cpu_einfo7[4] = {0};
+    int cpu_info7[4] = {};
+    int cpu_einfo7[4] = {};
     __cpuid(cpu_info, 1);
     if (num_ids >= 7) {
       __cpuid(cpu_info7, 7);
@@ -191,10 +191,10 @@
     model_ = results.model;
     ext_family_ = results.ext_family;
     ext_model_ = results.ext_model;
-    has_mmx_ =   (cpu_info[3] & 0x00800000) != 0;
-    has_sse_ =   (cpu_info[3] & 0x02000000) != 0;
-    has_sse2_ =  (cpu_info[3] & 0x04000000) != 0;
-    has_sse3_ =  (cpu_info[2] & 0x00000001) != 0;
+    has_mmx_ = (cpu_info[3] & 0x00800000) != 0;
+    has_sse_ = (cpu_info[3] & 0x02000000) != 0;
+    has_sse2_ = (cpu_info[3] & 0x04000000) != 0;
+    has_sse3_ = (cpu_info[2] & 0x00000001) != 0;
     has_ssse3_ = (cpu_info[2] & 0x00000200) != 0;
     has_sse41_ = (cpu_info[2] & 0x00080000) != 0;
     has_sse42_ = (cpu_info[2] & 0x00100000) != 0;
@@ -217,11 +217,10 @@
     // even after following Intel's example code. (See crbug.com/375968.)
     // Because of that, we also test the XSAVE bit because its description in
     // the CPUID documentation suggests that it signals xgetbv support.
-    has_avx_ =
-        (cpu_info[2] & 0x10000000) != 0 &&
-        (cpu_info[2] & 0x04000000) != 0 /* XSAVE */ &&
-        (cpu_info[2] & 0x08000000) != 0 /* OSXSAVE */ &&
-        (xgetbv(0) & 6) == 6 /* XSAVE enabled by kernel */;
+    has_avx_ = (cpu_info[2] & 0x10000000) != 0 &&
+               (cpu_info[2] & 0x04000000) != 0 /* XSAVE */ &&
+               (cpu_info[2] & 0x08000000) != 0 /* OSXSAVE */ &&
+               (xgetbv(0) & 6) == 6 /* XSAVE enabled by kernel */;
     has_aesni_ = (cpu_info[2] & 0x02000000) != 0;
     has_fma3_ = (cpu_info[2] & 0x00001000) != 0;
     if (has_avx_) {
@@ -300,19 +299,45 @@
 
 #if defined(ARCH_CPU_X86_FAMILY)
 CPU::IntelMicroArchitecture CPU::GetIntelMicroArchitecture() const {
-  if (has_avx512_vnni()) return AVX512_VNNI;
-  if (has_avx512_bw()) return AVX512BW;
-  if (has_avx512_f()) return AVX512F;
-  if (has_avx_vnni()) return AVX_VNNI;
-  if (has_avx2()) return AVX2;
-  if (has_fma3()) return FMA3;
-  if (has_avx()) return AVX;
-  if (has_sse42()) return SSE42;
-  if (has_sse41()) return SSE41;
-  if (has_ssse3()) return SSSE3;
-  if (has_sse3()) return SSE3;
-  if (has_sse2()) return SSE2;
-  if (has_sse()) return SSE;
+  if (has_avx512_vnni()) {
+    return AVX512_VNNI;
+  }
+  if (has_avx512_bw()) {
+    return AVX512BW;
+  }
+  if (has_avx512_f()) {
+    return AVX512F;
+  }
+  if (has_avx_vnni()) {
+    return AVX_VNNI;
+  }
+  if (has_avx2()) {
+    return AVX2;
+  }
+  if (has_fma3()) {
+    return FMA3;
+  }
+  if (has_avx()) {
+    return AVX;
+  }
+  if (has_sse42()) {
+    return SSE42;
+  }
+  if (has_sse41()) {
+    return SSE41;
+  }
+  if (has_ssse3()) {
+    return SSSE3;
+  }
+  if (has_sse3()) {
+    return SSE3;
+  }
+  if (has_sse2()) {
+    return SSE2;
+  }
+  if (has_sse()) {
+    return SSE;
+  }
   return PENTIUM;
 }
 #endif
diff --git a/tot/base/cpu_reduction_experiment.cc b/tot/base/cpu_reduction_experiment.cc
deleted file mode 100644
index e22bc07..0000000
--- a/tot/base/cpu_reduction_experiment.cc
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2022 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/cpu_reduction_experiment.h"
-
-#include <atomic>
-
-#include "base/check.h"
-#include "base/dcheck_is_on.h"
-#include "base/feature_list.h"
-#include "base/rand_util.h"
-
-namespace base {
-
-namespace {
-
-// Whether to enable a series of optimizations that reduce total CPU
-// utilization.
-BASE_FEATURE(kReduceCpuUtilization,
-             "ReduceCpuUtilization2",
-             FEATURE_ENABLED_BY_DEFAULT);
-
-class CpuReductionExperimentSubSampler {
- public:
-  CpuReductionExperimentSubSampler() : counter_(base::RandUint64()) {}
-
-  bool ShouldLogHistograms() {
-    // Relaxed memory order since there is no dependent memory access.
-    uint64_t val = counter_.fetch_add(1, std::memory_order_relaxed);
-    return val % 1000 == 0;
-  }
-
- private:
-  std::atomic<uint64_t> counter_{0};
-};
-
-// Singleton instance of CpuReductionExperimentSubSampler. This is only set when
-// the ReduceCpuUtilization experiment is enabled -- as a result, it's ok to
-// assume that the experiment is disabled when this is not set.
-CpuReductionExperimentSubSampler* g_subsampler = nullptr;
-
-#if DCHECK_IS_ON()
-// Atomic to support concurrent writes from IsRunningCpuReductionExperiment().
-std::atomic_bool g_accessed_subsampler = false;
-#endif
-
-}  // namespace
-
-bool IsRunningCpuReductionExperiment() {
-#if DCHECK_IS_ON()
-  // Relaxed memory order since there is no dependent memory access.
-  g_accessed_subsampler.store(true, std::memory_order_relaxed);
-#endif
-  return !!g_subsampler;
-}
-
-void InitializeCpuReductionExperiment() {
-#if DCHECK_IS_ON()
-  // TSAN should generate an error if InitializeCpuReductionExperiment() races
-  // with IsRunningCpuReductionExperiment().
-  //
-  // Relaxed memory order since there is no dependent memory access.
-  DCHECK(!g_accessed_subsampler.load(std::memory_order_relaxed));
-#endif
-  if (FeatureList::IsEnabled(kReduceCpuUtilization)) {
-    g_subsampler = new CpuReductionExperimentSubSampler();
-  }
-}
-
-bool ShouldLogHistogramForCpuReductionExperiment() {
-  if (!IsRunningCpuReductionExperiment())
-    return true;
-  return g_subsampler->ShouldLogHistograms();
-}
-
-}  // namespace base
diff --git a/tot/base/cpu_reduction_experiment.h b/tot/base/cpu_reduction_experiment.h
deleted file mode 100644
index 0fdc8b7..0000000
--- a/tot/base/cpu_reduction_experiment.h
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2022 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_CPU_REDUCTION_EXPERIMENT_H_
-#define BASE_CPU_REDUCTION_EXPERIMENT_H_
-
-#include "base/base_export.h"
-
-namespace base {
-
-// Returns whether the cpu cycle reduction experiment is running.
-// The goal of this experiment is to better understand the relationship between
-// total CPU cycles used across the fleet and top-line chrome metrics.
-BASE_EXPORT bool IsRunningCpuReductionExperiment();
-
-// Must be called after FeatureList initialization and while chrome is still
-// single-threaded.
-BASE_EXPORT void InitializeCpuReductionExperiment();
-
-// Returns true if the next sample should be recorded to an histogram
-// sub-sampled under the CPU reduction experiment. Returns true randomly for
-// ~1/1000 calls when the experiment is enabled, or always returns true when the
-// experiment is disabled.
-BASE_EXPORT bool ShouldLogHistogramForCpuReductionExperiment();
-
-}  // namespace base
-
-#endif  // BASE_CPU_REDUCTION_EXPERIMENT_H_
diff --git a/tot/base/debug/alias.cc b/tot/base/debug/alias.cc
index 01c0e80..6d89d18 100644
--- a/tot/base/debug/alias.cc
+++ b/tot/base/debug/alias.cc
@@ -6,12 +6,10 @@
 
 #include "base/compiler_specific.h"
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
 // This file/function should be excluded from LTO/LTCG to ensure that the
 // compiler can't see this function's implementation when compiling calls to it.
 NOINLINE void Alias(const void* var) {}
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/alias.h b/tot/base/debug/alias.h
index e473f11..b072ed9 100644
--- a/tot/base/debug/alias.h
+++ b/tot/base/debug/alias.h
@@ -8,6 +8,7 @@
 #include <stddef.h>
 
 #include "base/base_export.h"
+#include "base/compiler_specific.h"
 
 namespace base {
 namespace debug {
@@ -88,19 +89,19 @@
 // Convenience macro that copies the null-terminated string from `c_str` into a
 // stack-allocated char array named `var_name` that holds up to `array_size - 1`
 // characters and should be preserved in memory dumps.
-#define DEBUG_ALIAS_FOR_CSTR(var_name, c_str, array_size)  \
-  char var_name[array_size] = {};                          \
-  ::base::strlcpy(var_name, (c_str), std::size(var_name)); \
+#define DEBUG_ALIAS_FOR_CSTR(var_name, c_str, array_size)               \
+  char var_name[array_size] = {};                                       \
+  UNSAFE_TODO(::base::strlcpy(var_name, (c_str), std::size(var_name))); \
   ::base::debug::Alias(var_name)
 
-#define DEBUG_ALIAS_FOR_U16CSTR(var_name, c_str, array_size)   \
-  char16_t var_name[array_size] = {};                          \
-  ::base::u16cstrlcpy(var_name, (c_str), std::size(var_name)); \
+#define DEBUG_ALIAS_FOR_U16CSTR(var_name, c_str, array_size)                \
+  char16_t var_name[array_size] = {};                                       \
+  UNSAFE_TODO(::base::u16cstrlcpy(var_name, (c_str), std::size(var_name))); \
   ::base::debug::Alias(var_name)
 
-#define DEBUG_ALIAS_FOR_WCHARCSTR(var_name, c_str, array_size) \
-  wchar_t var_name[array_size] = {};                           \
-  ::base::wcslcpy(var_name, (c_str), std::size(var_name));     \
+#define DEBUG_ALIAS_FOR_WCHARCSTR(var_name, c_str, array_size)          \
+  wchar_t var_name[array_size] = {};                                    \
+  UNSAFE_TODO(::base::wcslcpy(var_name, (c_str), std::size(var_name))); \
   ::base::debug::Alias(var_name)
 
 // Code folding is a linker optimization whereby the linker identifies functions
diff --git a/tot/base/debug/alias_unittest.cc b/tot/base/debug/alias_unittest.cc
index 8d26b83..32a8c38 100644
--- a/tot/base/debug/alias_unittest.cc
+++ b/tot/base/debug/alias_unittest.cc
@@ -2,12 +2,12 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "base/debug/alias.h"
+
 #include <algorithm>
 #include <memory>
 #include <string>
 
-#include "base/debug/alias.h"
-#include "base/ranges/algorithm.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 TEST(DebugAlias, Test) {
diff --git a/tot/base/debug/allocation_trace.cc b/tot/base/debug/allocation_trace.cc
index 2b2c931..721223c 100644
--- a/tot/base/debug/allocation_trace.cc
+++ b/tot/base/debug/allocation_trace.cc
@@ -105,4 +105,4 @@
 #endif
 }
 
-}  // namespace base::debug::tracer
\ No newline at end of file
+}  // namespace base::debug::tracer
diff --git a/tot/base/debug/allocation_trace_perftest.cc b/tot/base/debug/allocation_trace_perftest.cc
index f2753db..c2492ef 100644
--- a/tot/base/debug/allocation_trace_perftest.cc
+++ b/tot/base/debug/allocation_trace_perftest.cc
@@ -2,12 +2,13 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "base/debug/allocation_trace.h"
+
 #include <thread>
 #include <vector>
 
 #include "base/allocator/dispatcher/notification_data.h"
 #include "base/allocator/dispatcher/subsystem.h"
-#include "base/debug/allocation_trace.h"
 #include "base/strings/stringprintf.h"
 #include "base/timer/lap_timer.h"
 #include "testing/gtest/include/gtest/gtest.h"
diff --git a/tot/base/debug/allocation_trace_unittest.cc b/tot/base/debug/allocation_trace_unittest.cc
index c2a0027..45c69cb 100644
--- a/tot/base/debug/allocation_trace_unittest.cc
+++ b/tot/base/debug/allocation_trace_unittest.cc
@@ -131,8 +131,9 @@
       new (buffer->data.data()) AllocationTraceRecorder();
 
   static_assert(std::is_trivially_copyable_v<AllocationTraceRecorder>);
-  base::byte_span_from_ref(*buffered_recorder)
-      .copy_from(base::byte_span_from_ref(subject_under_test));
+  base::byte_span_from_ref(base::allow_nonunique_obj, *buffered_recorder)
+      .copy_from(base::byte_span_from_ref(base::allow_nonunique_obj,
+                                          subject_under_test));
 
   // Verify that the original recorder and the buffered recorder are equal.
   ASSERT_EQ(subject_under_test.size(), buffered_recorder->size());
diff --git a/tot/base/debug/asan_invalid_access.cc b/tot/base/debug/asan_invalid_access.cc
index ea56f9b..a615289 100644
--- a/tot/base/debug/asan_invalid_access.cc
+++ b/tot/base/debug/asan_invalid_access.cc
@@ -22,8 +22,7 @@
 #include <windows.h>
 #endif
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
 namespace {
 
@@ -41,7 +40,7 @@
   // This way the underflow won't be detected but the corruption will (as the
   // allocator will still be hooked).
   auto InterlockedIncrementFn =
-      reinterpret_cast<LONG (*)(LONG volatile * addend)>(
+      reinterpret_cast<LONG (*)(LONG volatile* addend)>(
           GetProcAddress(GetModuleHandle(L"kernel32"), "InterlockedIncrement"));
   CHECK(InterlockedIncrementFn);
 
@@ -107,5 +106,4 @@
 #endif  // BUILDFLAG(IS_WIN)
 #endif  // ADDRESS_SANITIZER
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/asan_service.cc b/tot/base/debug/asan_service.cc
index 9c90a44..6591e80 100644
--- a/tot/base/debug/asan_service.cc
+++ b/tot/base/debug/asan_service.cc
@@ -28,9 +28,9 @@
 // In component builds on Windows, weak function exported by ASan have the
 // `__dll` suffix. ASan itself uses the `alternatename` directive to account for
 // that.
-#pragma comment(linker,                                                \
-                    "/alternatename:__sanitizer_report_error_summary=" \
-                    "__sanitizer_report_error_summary__dll")
+#pragma comment(linker,                                            \
+                "/alternatename:__sanitizer_report_error_summary=" \
+                "__sanitizer_report_error_summary__dll")
 #pragma comment(linker,                                     \
                 "/alternatename:__sanitizer_set_report_fd=" \
                 "__sanitizer_set_report_fd__dll")
diff --git a/tot/base/debug/buffered_dwarf_reader.cc b/tot/base/debug/buffered_dwarf_reader.cc
index 7c7a055..96c1512 100644
--- a/tot/base/debug/buffered_dwarf_reader.cc
+++ b/tot/base/debug/buffered_dwarf_reader.cc
@@ -49,8 +49,9 @@
   uint8_t byte;
   int shift = 0;
   do {
-    if (!ReadInt8(byte))
+    if (!ReadInt8(byte)) {
       return false;
+    }
     value |= static_cast<uint64_t>(byte & 0x7F) << shift;
     shift += 7;
   } while (byte & 0x80);
@@ -63,8 +64,9 @@
   int shift = 0;
   bool sign_bit = false;
   do {
-    if (!ReadInt8(byte))
+    if (!ReadInt8(byte)) {
       return false;
+    }
     value |= static_cast<uint64_t>(byte & 0x7F) << shift;
     shift += 7;
     sign_bit = byte & 0x40;
@@ -125,22 +127,25 @@
   switch (address_size) {
     case 2: {
       uint16_t tmp;
-      if (!ReadInt16(tmp))
+      if (!ReadInt16(tmp)) {
         return false;
+      }
       address = tmp;
     } break;
 
     case 4: {
       uint32_t tmp;
-      if (!ReadInt32(tmp))
+      if (!ReadInt32(tmp)) {
         return false;
+      }
       address = tmp;
     } break;
 
     case 8: {
       uint64_t tmp;
-      if (!ReadInt64(tmp))
+      if (!ReadInt64(tmp)) {
         return false;
+      }
       address = tmp;
     } break;
 
@@ -181,8 +186,9 @@
   while (bytes_left > 0) {
     // Refresh the buffer.
     if (unconsumed_amount_ == 0) {
-      if (!base::IsValueInRangeForNumericType<size_t>(next_chunk_start_))
+      if (!base::IsValueInRangeForNumericType<size_t>(next_chunk_start_)) {
         return false;
+      }
       const ssize_t unconsumed_amount = google::ReadFromOffset(
           fd_, buf_, sizeof(buf_), static_cast<size_t>(next_chunk_start_));
       if (unconsumed_amount <= 0) {
diff --git a/tot/base/debug/crash_logging.cc b/tot/base/debug/crash_logging.cc
index 7ea15c2..c3932e2 100644
--- a/tot/base/debug/crash_logging.cc
+++ b/tot/base/debug/crash_logging.cc
@@ -19,12 +19,13 @@
 
 CrashKeyString* AllocateCrashKeyString(const char name[],
                                        CrashKeySize value_length) {
-  if (!g_crash_key_impl)
+  if (!g_crash_key_impl) {
     return nullptr;
+  }
 
-    // TODO(crbug.com/40850825): It would be great if the DCHECKs below
-    // could also be enabled on Android, but debugging tryjob failures was a bit
-    // difficult... :-/
+  // TODO(crbug.com/40850825): It would be great if the DCHECKs below
+  // could also be enabled on Android, but debugging tryjob failures was a bit
+  // difficult... :-/
 #if DCHECK_IS_ON() && !BUILDFLAG(IS_ANDROID)
   std::string_view name_piece = name;
 
@@ -44,22 +45,25 @@
 }
 
 void SetCrashKeyString(CrashKeyString* crash_key, std::string_view value) {
-  if (!g_crash_key_impl || !crash_key)
+  if (!g_crash_key_impl || !crash_key) {
     return;
+  }
 
   g_crash_key_impl->Set(crash_key, value);
 }
 
 void ClearCrashKeyString(CrashKeyString* crash_key) {
-  if (!g_crash_key_impl || !crash_key)
+  if (!g_crash_key_impl || !crash_key) {
     return;
+  }
 
   g_crash_key_impl->Clear(crash_key);
 }
 
 void OutputCrashKeysToStream(std::ostream& out) {
-  if (!g_crash_key_impl)
+  if (!g_crash_key_impl) {
     return;
+  }
 
   g_crash_key_impl->OutputCrashKeysToStream(out);
 }
diff --git a/tot/base/debug/crash_logging_unittest.cc b/tot/base/debug/crash_logging_unittest.cc
index f585bde..d6b90ac 100644
--- a/tot/base/debug/crash_logging_unittest.cc
+++ b/tot/base/debug/crash_logging_unittest.cc
@@ -17,8 +17,7 @@
 using ::testing::IsEmpty;
 using ::testing::Pair;
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
 namespace {
 
@@ -153,5 +152,4 @@
   EXPECT_EQ("Got 2 crash keys.", stream.str());
 }
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/debugger.cc b/tot/base/debug/debugger.cc
index 3ec076e..4d2232e 100644
--- a/tot/base/debug/debugger.cc
+++ b/tot/base/debug/debugger.cc
@@ -13,8 +13,7 @@
 #include "base/test/clang_profiling.h"
 #endif
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
 static bool is_debug_ui_suppressed = false;
 
@@ -27,8 +26,9 @@
 #endif
   for (int i = 0; i < wait_seconds * 10; ++i) {
     if (BeingDebugged()) {
-      if (!silent)
+      if (!silent) {
         BreakDebugger();
+      }
       return true;
     }
     PlatformThread::Sleep(Milliseconds(100));
@@ -52,5 +52,4 @@
   return is_debug_ui_suppressed;
 }
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/debugger_fuchsia.cc b/tot/base/debug/debugger_fuchsia.cc
index dcac5b9..2d0e5fd 100644
--- a/tot/base/debug/debugger_fuchsia.cc
+++ b/tot/base/debug/debugger_fuchsia.cc
@@ -19,8 +19,8 @@
   zx_info_process_t info = {};
   // Ignore failures. The 0-initialization above will result in "false" for
   // error cases.
-  zx::process::self()->get_info(ZX_INFO_PROCESS, &info, sizeof(info),
-                                nullptr, nullptr);
+  zx::process::self()->get_info(ZX_INFO_PROCESS, &info, sizeof(info), nullptr,
+                                nullptr);
   return (info.flags & ZX_INFO_PROCESS_FLAG_DEBUGGER_ATTACHED) != 0;
 }
 
diff --git a/tot/base/debug/debugger_posix.cc b/tot/base/debug/debugger_posix.cc
index f5bf9ca..eb3fcb4 100644
--- a/tot/base/debug/debugger_posix.cc
+++ b/tot/base/debug/debugger_posix.cc
@@ -60,8 +60,7 @@
 #include "base/third_party/symbolize/symbolize.h"  // nogncheck
 #endif
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
 #if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_BSD)
 
@@ -81,20 +80,20 @@
   static bool is_set = false;
   static bool being_debugged = false;
 
-  if (is_set)
+  if (is_set) {
     return being_debugged;
+  }
 
   // Initialize mib, which tells sysctl what info we want.  In this case,
   // we're looking for information about a specific process ID.
-  int mib[] = {
-    CTL_KERN,
-    KERN_PROC,
-    KERN_PROC_PID,
-    getpid()
+  int mib[] = {CTL_KERN,
+               KERN_PROC,
+               KERN_PROC_PID,
+               getpid()
 #if BUILDFLAG(IS_OPENBSD)
-        ,
-    sizeof(struct kinfo_proc),
-    0
+                   ,
+               sizeof(struct kinfo_proc),
+               0
 #endif
   };
 
@@ -104,8 +103,9 @@
   size_t info_size = sizeof(info);
 
 #if BUILDFLAG(IS_OPENBSD)
-  if (sysctl(mib, std::size(mib), NULL, &info_size, NULL, 0) < 0)
+  if (sysctl(mib, std::size(mib), NULL, &info_size, NULL, 0) < 0) {
     return -1;
+  }
 
   mib[5] = (info_size / sizeof(struct kinfo_proc));
 #endif
@@ -132,10 +132,12 @@
 
 void VerifyDebugger() {
 #if BUILDFLAG(ENABLE_LLDBINIT_WARNING)
-  if (Environment::Create()->HasVar("CHROMIUM_LLDBINIT_SOURCED"))
+  if (Environment::Create()->HasVar("CHROMIUM_LLDBINIT_SOURCED")) {
     return;
-  if (!BeingDebugged())
+  }
+  if (!BeingDebugged()) {
     return;
+  }
   DCHECK(false)
       << "Detected lldb without sourcing //tools/lldb/lldbinit.py. lldb may "
          "not be able to find debug symbols. Please see debug instructions for "
@@ -160,8 +162,9 @@
   // stack dumping signal handler). NO malloc or stdio is allowed here.
 
   int status_fd = open("/proc/self/status", O_RDONLY);
-  if (status_fd == -1)
+  if (status_fd == -1) {
     return Process();
+  }
 
   // We assume our line will be in the first 1024 characters and that we can
   // read this much all at once.  In practice this will generally be true.
@@ -169,11 +172,13 @@
   char buf[1024];
 
   ssize_t num_read = HANDLE_EINTR(read(status_fd, buf, sizeof(buf)));
-  if (IGNORE_EINTR(close(status_fd)) < 0)
+  if (IGNORE_EINTR(close(status_fd)) < 0) {
     return Process();
+  }
 
-  if (num_read <= 0)
+  if (num_read <= 0) {
     return Process();
+  }
 
   std::string_view status(buf, static_cast<size_t>(num_read));
   std::string_view tracer("TracerPid:\t");
@@ -190,8 +195,9 @@
 
   std::string_view pid_str(buf + pid_index, pid_end_index - pid_index);
   int pid = 0;
-  if (!StringToInt(pid_str, &pid))
+  if (!StringToInt(pid_str, &pid)) {
     return Process();
+  }
 
   return Process(pid);
 }
@@ -203,18 +209,21 @@
 void VerifyDebugger() {
 #if BUILDFLAG(ENABLE_GDBINIT_WARNING)
   // Quick check before potentially slower GetDebuggerProcess().
-  if (Environment::Create()->HasVar("CHROMIUM_GDBINIT_SOURCED"))
+  if (Environment::Create()->HasVar("CHROMIUM_GDBINIT_SOURCED")) {
     return;
+  }
 
   Process proc = GetDebuggerProcess();
-  if (!proc.IsValid())
+  if (!proc.IsValid()) {
     return;
+  }
 
   FilePath cmdline_file =
       FilePath("/proc").Append(NumberToString(proc.Handle())).Append("cmdline");
   std::string cmdline;
-  if (!ReadFileToString(cmdline_file, &cmdline))
+  if (!ReadFileToString(cmdline_file, &cmdline)) {
     return;
+  }
 
   // /proc/*/cmdline separates arguments with null bytes, but we only care about
   // the executable name, so interpret |cmdline| as a null-terminated C string
@@ -297,8 +306,9 @@
     DEBUG_BREAK_ASM();
 #else
     volatile int go = 0;
-    while (!go)
+    while (!go) {
       PlatformThread::Sleep(Milliseconds(100));
+    }
 #endif
   }
 }
@@ -339,5 +349,4 @@
 #endif
 }
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/debugger_unittest.cc b/tot/base/debug/debugger_unittest.cc
index 1b7fd92..70208ea 100644
--- a/tot/base/debug/debugger_unittest.cc
+++ b/tot/base/debug/debugger_unittest.cc
@@ -3,6 +3,7 @@
 // found in the LICENSE file.
 
 #include "base/debug/debugger.h"
+
 #include "build/build_config.h"
 
 #if BUILDFLAG(IS_WIN)
@@ -42,6 +43,5 @@
 #endif  // BUILDFLAG(IS_WIN)
 
 #else   // defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID)
-TEST(Debugger, NoTest) {
-}
+TEST(Debugger, NoTest) {}
 #endif  // defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID)
diff --git a/tot/base/debug/debugger_win.cc b/tot/base/debug/debugger_win.cc
index c62c3be..f8e41e0 100644
--- a/tot/base/debug/debugger_win.cc
+++ b/tot/base/debug/debugger_win.cc
@@ -16,8 +16,9 @@
 }
 
 void BreakDebuggerAsyncSafe() {
-  if (IsDebugUISuppressed())
+  if (IsDebugUISuppressed()) {
     _exit(1);
+  }
 
   __debugbreak();
 }
diff --git a/tot/base/debug/dump_without_crashing.cc b/tot/base/debug/dump_without_crashing.cc
index 44ff212..7862bc1 100644
--- a/tot/base/debug/dump_without_crashing.cc
+++ b/tot/base/debug/dump_without_crashing.cc
@@ -46,16 +46,6 @@
   return *location_to_timestamp;
 }
 
-// Map used to store the most recent time a pair of location and
-// unique_identifier called ShouldDumpWithoutCrashWithLocationAndUniqueId.
-std::map<std::pair<base::Location, size_t>, base::TimeTicks>&
-LocationAndUniqueIdentifierToTimestampMap() {
-  static base::NoDestructor<
-      std::map<std::pair<base::Location, size_t>, base::TimeTicks>>
-      location_and_unique_identifier_to_timestamp;
-  return *location_and_unique_identifier_to_timestamp;
-}
-
 // This function takes `location` and `time_between_dumps` as an input
 // and checks if DumpWithoutCrashing() meets the requirements to take the dump
 // or not.
@@ -64,32 +54,9 @@
   return ShouldDump(LocationToTimestampMap(), location, time_between_dumps);
 }
 
-// Pair of `location` and `unique_identifier` creates a unique key and checks
-// if DumpWithoutCrashingWithUniqueId() meets the requirements to take dump or
-// not.
-bool ShouldDumpWithoutCrashWithLocationAndUniqueId(
-    size_t unique_identifier,
-    const base::Location& location,
-    base::TimeDelta time_between_dumps) {
-  std::pair<base::Location, size_t> key(location, unique_identifier);
-  return ShouldDump(LocationAndUniqueIdentifierToTimestampMap(), key,
-                    time_between_dumps);
-}
-
 }  // namespace
 
-namespace base {
-
-namespace debug {
-
-bool DumpWithoutCrashingUnthrottled() {
-  TRACE_EVENT0("base", "DumpWithoutCrashingUnthrottled");
-  if (dump_without_crashing_function_) {
-    (*dump_without_crashing_function_)();
-    return true;
-  }
-  return false;
-}
+namespace base::debug {
 
 bool DumpWithoutCrashing(const base::Location& location,
                          base::TimeDelta time_between_dumps) {
@@ -115,23 +82,6 @@
   return false;
 }
 
-bool DumpWithoutCrashingWithUniqueId(size_t unique_identifier,
-                                     const base::Location& location,
-                                     base::TimeDelta time_between_dumps) {
-  TRACE_EVENT0("base", "DumpWithoutCrashingWithUniqueId");
-  if (dump_without_crashing_function_ &&
-      ShouldDumpWithoutCrashWithLocationAndUniqueId(unique_identifier, location,
-                                                    time_between_dumps)) {
-    (*dump_without_crashing_function_)();
-    base::UmaHistogramEnumeration("Stability.DumpWithoutCrashingStatus",
-                                  DumpWithoutCrashingStatus::kUploaded);
-    return true;
-  }
-  base::UmaHistogramEnumeration("Stability.DumpWithoutCrashingStatus",
-                                DumpWithoutCrashingStatus::kThrottled);
-  return false;
-}
-
 void SetDumpWithoutCrashingFunction(void (*function)()) {
 #if !defined(COMPONENT_BUILD)
   // In component builds, the same base is shared between modules
@@ -142,10 +92,8 @@
   dump_without_crashing_function_ = function;
 }
 
-void ClearMapsForTesting() {
+void ResetDumpWithoutCrashingThrottlingForTesting() {
   LocationToTimestampMap().clear();
-  LocationAndUniqueIdentifierToTimestampMap().clear();
 }
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/dump_without_crashing.h b/tot/base/debug/dump_without_crashing.h
index 5c97a83..ef4a5c7 100644
--- a/tot/base/debug/dump_without_crashing.h
+++ b/tot/base/debug/dump_without_crashing.h
@@ -38,11 +38,6 @@
 // This function must not be called with a tail call because that would cause
 // the caller to be omitted from the call stack in the crash dump, and that is
 // confusing and omits what is likely the most important context.
-//
-// Note: Calls to this function will not be throttled. To avoid performance
-// problems if this is called many times in quick succession, prefer using one
-// of the below variants.
-NOT_TAIL_CALLED BASE_EXPORT bool DumpWithoutCrashingUnthrottled();
 
 // Handler to silently dump the current process without crashing, that keeps
 // track of call location so some throttling can be applied to avoid very
@@ -53,35 +48,13 @@
     const base::Location& location = base::Location::Current(),
     base::TimeDelta time_between_dumps = base::Days(1));
 
-// Handler to silently dump the current process without crashing that takes a
-// location and unique id to keep a track and apply throttling. This function
-// should be used when a domain wishes to capture dumps for multiple, unique
-// reasons from a single location. An example would be unique bad mojo
-// messages, or a value outside an expected range and the value should be
-// considered interesting in the dump. The goal is to allow a single call to
-// generate multiple dumps as needed and throttle future instances of the same
-// identifiers for a short period of time.
-// `unique_identifier` Hash to uniquely identify the function call. Consider
-// using base::FastHash to generate the hash.
-// `location` Location of the file from where the function is called.
-// `time_between_dumps` Time until the next dump should be captured.
-// Note:
-// - The unique identifier, as of now, is not comparable across different
-//   runs or builds and is stable only for a process lifetime.
-// - The unique identifier is not recorded in the crash report. See
-//   crash_logging.h for such a purpose.
-NOT_TAIL_CALLED BASE_EXPORT bool DumpWithoutCrashingWithUniqueId(
-    size_t unique_identifier,
-    const base::Location& location = base::Location::Current(),
-    base::TimeDelta time_between_dumps = base::Days(1));
-
 // Sets a function that'll be invoked to dump the current process when
 // DumpWithoutCrashing* is called. May be called with null to remove a
 // previously set function.
 BASE_EXPORT void SetDumpWithoutCrashingFunction(void (*function)());
 
-// Clear both maps used to throttle calls to DumpWithoutCrashing for testing.
-BASE_EXPORT void ClearMapsForTesting();
+// Reset DumpWithoutCrashing throttling for testing.
+BASE_EXPORT void ResetDumpWithoutCrashingThrottlingForTesting();
 
 }  // namespace debug
 }  // namespace base
diff --git a/tot/base/debug/dump_without_crashing_unittest.cc b/tot/base/debug/dump_without_crashing_unittest.cc
index 96973c2..4dacfc0 100644
--- a/tot/base/debug/dump_without_crashing_unittest.cc
+++ b/tot/base/debug/dump_without_crashing_unittest.cc
@@ -11,8 +11,7 @@
 #include "build/build_config.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
 class DumpWithoutCrashingTest : public testing::Test {
  public:
@@ -29,7 +28,7 @@
 
   void TearDown() override {
     SetDumpWithoutCrashingFunction(nullptr);
-    ClearMapsForTesting();
+    ResetDumpWithoutCrashingThrottlingForTesting();
   }
 
   // Set override.
@@ -94,55 +93,4 @@
                                       DumpWithoutCrashingStatus::kUploaded, 3);
 }
 
-TEST_F(DumpWithoutCrashingTest, DumpWithoutCrashingWithLocationAndUniqueId) {
-  EXPECT_EQ(0, DumpWithoutCrashingTest::number_of_dump_calls());
-
-  histogram_tester_.ExpectBucketCount("Stability.DumpWithoutCrashingStatus",
-                                      DumpWithoutCrashingStatus::kThrottled, 0);
-  histogram_tester_.ExpectBucketCount("Stability.DumpWithoutCrashingStatus",
-                                      DumpWithoutCrashingStatus::kUploaded, 0);
-
-  // Test the variant of DumpWithoutCrashingWithUniqueId where the function
-  // takes a location and unique id.
-  EXPECT_TRUE(DumpWithoutCrashingWithUniqueId(unique_identifier1_, location1_,
-                                              base::Seconds(1)));
-  EXPECT_EQ(1, DumpWithoutCrashingTest::number_of_dump_calls());
-
-  histogram_tester_.ExpectBucketCount("Stability.DumpWithoutCrashingStatus",
-                                      DumpWithoutCrashingStatus::kThrottled, 0);
-  histogram_tester_.ExpectBucketCount("Stability.DumpWithoutCrashingStatus",
-                                      DumpWithoutCrashingStatus::kUploaded, 1);
-
-  // If DumpWithoutCrashingWithUniqueId called within 1 second, expected result
-  // is false.
-  EXPECT_FALSE(DumpWithoutCrashingWithUniqueId(unique_identifier1_, location1_,
-                                               base::Seconds(1)));
-  EXPECT_EQ(1, DumpWithoutCrashingTest::number_of_dump_calls());
-
-  // For testing, the time for capturing dump again is 1 second and if the
-  // function is called after 1 second, it will return true.
-  clock_.Advance(Seconds(2));
-
-  EXPECT_TRUE(DumpWithoutCrashingWithUniqueId(unique_identifier1_, location1_,
-                                              base::Seconds(1)));
-  EXPECT_EQ(2, DumpWithoutCrashingTest::number_of_dump_calls());
-
-  histogram_tester_.ExpectBucketCount("Stability.DumpWithoutCrashingStatus",
-                                      DumpWithoutCrashingStatus::kThrottled, 1);
-  histogram_tester_.ExpectBucketCount("Stability.DumpWithoutCrashingStatus",
-                                      DumpWithoutCrashingStatus::kUploaded, 2);
-
-  EXPECT_TRUE(DumpWithoutCrashingWithUniqueId(unique_identifier2_, location2_,
-                                              base::Seconds(1)));
-  EXPECT_EQ(3, DumpWithoutCrashingTest::number_of_dump_calls());
-  EXPECT_FALSE(DumpWithoutCrashingWithUniqueId(unique_identifier2_, location2_,
-                                               base::Seconds(1)));
-  EXPECT_EQ(3, DumpWithoutCrashingTest::number_of_dump_calls());
-  histogram_tester_.ExpectBucketCount("Stability.DumpWithoutCrashingStatus",
-                                      DumpWithoutCrashingStatus::kThrottled, 2);
-  histogram_tester_.ExpectBucketCount("Stability.DumpWithoutCrashingStatus",
-                                      DumpWithoutCrashingStatus::kUploaded, 3);
-}
-
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/dwarf_line_no.cc b/tot/base/debug/dwarf_line_no.cc
index f61791c..ecbc2af 100644
--- a/tot/base/debug/dwarf_line_no.cc
+++ b/tot/base/debug/dwarf_line_no.cc
@@ -9,24 +9,25 @@
 
 #include "base/debug/dwarf_line_no.h"
 
-#include "partition_alloc/pointers/raw_ref.h"
 
 #ifdef USE_SYMBOLIZE
-#include <algorithm>
-#include <charconv>
-#include <cstdint>
-#include <limits>
-
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
 
+#include <algorithm>
+#include <array>
+#include <charconv>
+#include <cstdint>
+#include <limits>
+#include <system_error>
+
 #include "base/debug/buffered_dwarf_reader.h"
 #include "base/third_party/symbolize/symbolize.h"
 #include "partition_alloc/pointers/raw_ptr.h"
+#include "partition_alloc/pointers/raw_ref.h"
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
 namespace {
 
@@ -218,8 +219,9 @@
 
       // If module_relative_pc is out of range, skip.
       if (module_relative_pc < registers->last_address ||
-          module_relative_pc >= registers->address)
+          module_relative_pc >= registers->address) {
         return;
+      }
 
       if (registers->last_file < program_info->num_filenames) {
         info->line = registers->last_line;
@@ -256,8 +258,9 @@
   // advance) + opcode_base.
   uint8_t opcode;
   while (reader.position() < program_info.end_offset && info->line == 0) {
-    if (!reader.ReadInt8(opcode))
+    if (!reader.ReadInt8(opcode)) {
       return;
+    }
 
     // It's SPECIAL OPCODE TIME!. They're so special that they make up the
     // vast majority of the opcodes and are the first thing described in the
@@ -271,8 +274,9 @@
       const int line_adjust =
           program_info.line_base + (adjusted_opcode % program_info.line_range);
       if (line_adjust < 0) {
-        if (static_cast<uint64_t>(-line_adjust) > registers.line)
+        if (static_cast<uint64_t>(-line_adjust) > registers.line) {
           return;
+        }
         registers.line -= static_cast<uint64_t>(-line_adjust);
       } else {
         registers.line += static_cast<uint64_t>(line_adjust);
@@ -289,11 +293,13 @@
           // Extended opcode.
           uint64_t extended_opcode;
           uint64_t extended_opcode_length;
-          if (!reader.ReadLeb128(extended_opcode_length))
+          if (!reader.ReadLeb128(extended_opcode_length)) {
             return;
+          }
           uint64_t next_opcode = reader.position() + extended_opcode_length;
-          if (!reader.ReadLeb128(extended_opcode))
+          if (!reader.ReadLeb128(extended_opcode)) {
             return;
+          }
           switch (extended_opcode) {
             case 1: {
               // DW_LNE_end_sequence
@@ -306,8 +312,9 @@
             case 2: {
               // DW_LNE_set_address
               uint32_t value;
-              if (!reader.ReadInt32(value))
+              if (!reader.ReadInt32(value)) {
                 return;
+              }
               registers.address = value;
               registers.op_index = 0;
               break;
@@ -323,8 +330,9 @@
 
               // dir index
               uint64_t value;
-              if (!reader.ReadLeb128(value))
+              if (!reader.ReadLeb128(value)) {
                 return;
+              }
               size_t cur_filename = program_info.num_filenames;
               if (cur_filename < kMaxFilenames && value < kMaxDirectories) {
                 ++program_info.num_filenames;
@@ -336,20 +344,23 @@
               }
 
               // modification time
-              if (!reader.ReadLeb128(value))
+              if (!reader.ReadLeb128(value)) {
                 return;
+              }
 
               // source file length
-              if (!reader.ReadLeb128(value))
+              if (!reader.ReadLeb128(value)) {
                 return;
+              }
               break;
             }
 
             case 4: {
               // DW_LNE_set_discriminator
               uint64_t value;
-              if (!reader.ReadLeb128(value))
+              if (!reader.ReadLeb128(value)) {
                 return;
+              }
               registers.discriminator = value;
               break;
             }
@@ -376,8 +387,9 @@
         case 2: {
           // DW_LNS_advance_pc
           uint64_t op_advance;
-          if (!reader.ReadLeb128(op_advance))
+          if (!reader.ReadLeb128(op_advance)) {
             return;
+          }
           registers.OpAdvance(&program_info, op_advance);
           break;
         }
@@ -385,11 +397,13 @@
         case 3: {
           // DW_LNS_advance_line
           int64_t line_advance;
-          if (!reader.ReadLeb128(line_advance))
+          if (!reader.ReadLeb128(line_advance)) {
             return;
+          }
           if (line_advance < 0) {
-            if (static_cast<uint64_t>(-line_advance) > registers.line)
+            if (static_cast<uint64_t>(-line_advance) > registers.line) {
               return;
+            }
             registers.line -= static_cast<uint64_t>(-line_advance);
           } else {
             registers.line += static_cast<uint64_t>(line_advance);
@@ -400,8 +414,9 @@
         case 4: {
           // DW_LNS_set_file
           uint64_t value;
-          if (!reader.ReadLeb128(value))
+          if (!reader.ReadLeb128(value)) {
             return;
+          }
           registers.file = value;
           break;
         }
@@ -409,8 +424,9 @@
         case 5: {
           // DW_LNS_set_column
           uint64_t value;
-          if (!reader.ReadLeb128(value))
+          if (!reader.ReadLeb128(value)) {
             return;
+          }
           registers.column = value;
           break;
         }
@@ -435,8 +451,9 @@
         case 9: {
           // DW_LNS_fixed_advance_pc
           uint16_t value;
-          if (!reader.ReadInt16(value))
+          if (!reader.ReadInt16(value)) {
             return;
+          }
           registers.address += value;
           registers.op_index = 0;
           break;
@@ -455,8 +472,9 @@
         case 12: {
           // DW_LNS_set_isa
           uint64_t value;
-          if (!reader.ReadLeb128(value))
+          if (!reader.ReadLeb128(value)) {
             return;
+          }
           registers.isa = value;
           break;
         }
@@ -474,8 +492,9 @@
                             bool is_64bit,
                             uint64_t cu_name_offset,
                             ProgramInfo* program_info) {
-  if (!reader->ReadOffset(is_64bit, program_info->header_length))
+  if (!reader->ReadOffset(is_64bit, program_info->header_length)) {
     return false;
+  }
   program_info->start_offset = reader->position() + program_info->header_length;
 
   if (!reader->ReadInt8(program_info->minimum_instruction_length) ||
@@ -488,8 +507,9 @@
   }
 
   for (int i = 0; i < (program_info->opcode_base - 1); i++) {
-    if (!reader->ReadInt8(program_info->standard_opcode_lengths[i]))
+    if (!reader->ReadInt8(program_info->standard_opcode_lengths[i])) {
       return false;
+    }
   }
 
   // Table ends with a single null line. This basically means search for 2
@@ -498,8 +518,9 @@
   for (;;) {
     // Read a byte.
     last = cur;
-    if (!reader->ReadInt8(cur))
+    if (!reader->ReadInt8(cur)) {
       return false;
+    }
 
     if (last == 0 && cur == 0) {
       // We're at the last entry where it's a double null.
@@ -515,10 +536,12 @@
       program_info->directory_sizes[cur_dir] = 1;
     }
     do {
-      if (!reader->ReadInt8(cur))
+      if (!reader->ReadInt8(cur)) {
         return false;
-      if (cur_dir < kMaxDirectories)
+      }
+      if (cur_dir < kMaxDirectories) {
         ++program_info->directory_sizes[cur_dir];
+      }
     } while (cur != '\0');
   }
 
@@ -528,8 +551,9 @@
   for (;;) {
     // Read a byte.
     last = cur;
-    if (!reader->ReadInt8(cur))
+    if (!reader->ReadInt8(cur)) {
       return false;
+    }
 
     if (last == 0 && cur == 0) {
       // We're at the last entry where it's a double null.
@@ -540,15 +564,17 @@
     // first byte of the filename above.
     uint64_t filename_offset = reader->position() - 1;
     do {
-      if (!reader->ReadInt8(cur))
+      if (!reader->ReadInt8(cur)) {
         return false;
+      }
     } while (cur != '\0');
 
     uint64_t value;
 
     // Dir index
-    if (!reader->ReadLeb128(value))
+    if (!reader->ReadLeb128(value)) {
       return false;
+    }
     size_t cur_filename = program_info->num_filenames;
     if (cur_filename < kMaxFilenames && value < kMaxDirectories) {
       ++program_info->num_filenames;
@@ -557,12 +583,14 @@
     }
 
     // Modification time
-    if (!reader->ReadLeb128(value))
+    if (!reader->ReadLeb128(value)) {
       return false;
+    }
 
     // Bytes in file.
-    if (!reader->ReadLeb128(value))
+    if (!reader->ReadLeb128(value)) {
       return false;
+    }
   }
 
   // Set up the 0th filename.
@@ -1311,7 +1339,7 @@
                                 uint64_t* cu_offsets,
                                 size_t num_frames) {
   // LINT.IfChange(max_stack_frames)
-  FrameInfo frame_info[250] = {};
+  std::array<FrameInfo, 250> frame_info = {};
   // LINT.ThenChange(stack_trace.h:max_stack_frames)
   for (size_t i = 0; i < num_frames; i++) {
     // The `cu_offset` also encodes the original sort order.
@@ -1354,8 +1382,7 @@
   }
 }
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
 
 #else  // USE_SYMBOLIZE
 
diff --git a/tot/base/debug/elf_reader.cc b/tot/base/debug/elf_reader.cc
index 19587ff..2d4cf7f 100644
--- a/tot/base/debug/elf_reader.cc
+++ b/tot/base/debug/elf_reader.cc
@@ -26,8 +26,7 @@
 // must avoid dynamic memory allocation or using data structures which rely on
 // dynamic allocation.
 
-namespace base {
-namespace debug {
+namespace base::debug {
 namespace {
 
 // See https://refspecs.linuxbase.org/elf/elf.pdf for the ELF specification.
@@ -55,8 +54,9 @@
 // pointer to the start of the ELF image.
 const Ehdr* GetElfHeader(const void* elf_mapped_base) {
   if (strncmp(reinterpret_cast<const char*>(elf_mapped_base), ELFMAG,
-              SELFMAG) != 0)
+              SELFMAG) != 0) {
     return nullptr;
+  }
 
   return reinterpret_cast<const Ehdr*>(elf_mapped_base);
 }
@@ -69,13 +69,15 @@
   // NOTE: Function should use async signal safe calls only.
 
   const Ehdr* elf_header = GetElfHeader(elf_mapped_base);
-  if (!elf_header)
+  if (!elf_header) {
     return 0;
+  }
 
   const size_t relocation_offset = GetRelocationOffset(elf_mapped_base);
   for (const Phdr& header : GetElfProgramHeaders(elf_mapped_base)) {
-    if (header.p_type != PT_NOTE)
+    if (header.p_type != PT_NOTE) {
       continue;
+    }
 
     // Look for a NT_GNU_BUILD_ID note with name == "GNU".
     const char* current_section =
@@ -99,18 +101,21 @@
           bits::AlignUp(current_note->n_namesz, static_cast<Word>(4)) +
           bits::AlignUp(current_note->n_descsz, static_cast<Word>(4)) +
           sizeof(Nhdr);
-      if (section_size > static_cast<size_t>(section_end - current_section))
+      if (section_size > static_cast<size_t>(section_end - current_section)) {
         return 0;
+      }
       current_section += section_size;
     }
 
-    if (!found)
+    if (!found) {
       continue;
+    }
 
     // Validate that the serialized build ID will fit inside |build_id|.
     size_t note_size = current_note->n_descsz;
-    if ((note_size * 2) > kMaxBuildIdStringLength)
+    if ((note_size * 2) > kMaxBuildIdStringLength) {
       continue;
+    }
 
     // Write out the build ID as a null-terminated hex string.
     const uint8_t* build_id_raw =
@@ -135,13 +140,15 @@
   // NOTE: Function should use async signal safe calls only.
 
   const Ehdr* elf_header = GetElfHeader(elf_mapped_base);
-  if (!elf_header)
+  if (!elf_header) {
     return {};
+  }
 
   const size_t relocation_offset = GetRelocationOffset(elf_mapped_base);
   for (const Phdr& header : GetElfProgramHeaders(elf_mapped_base)) {
-    if (header.p_type != PT_DYNAMIC)
+    if (header.p_type != PT_DYNAMIC) {
       continue;
+    }
 
     // Read through the ELF dynamic sections to find the string table and
     // SONAME offsets, which are used to compute the offset of the library
@@ -151,7 +158,7 @@
     const Dyn* dynamic_end = reinterpret_cast<const Dyn*>(
         header.p_vaddr + relocation_offset + header.p_memsz);
     Xword soname_strtab_offset = 0;
-    const char* strtab_addr = 0;
+    const char* strtab_addr = nullptr;
     for (const Dyn* dynamic_iter = dynamic_start; dynamic_iter < dynamic_end;
          ++dynamic_iter) {
       if (dynamic_iter->d_tag == DT_STRTAB) {
@@ -168,8 +175,9 @@
         soname_strtab_offset = static_cast<Xword>(dynamic_iter->d_un.d_val);
       }
     }
-    if (soname_strtab_offset && strtab_addr)
+    if (soname_strtab_offset && strtab_addr) {
       return std::string_view(strtab_addr + soname_strtab_offset);
+    }
   }
 
   return std::nullopt;
@@ -179,8 +187,9 @@
   // NOTE: Function should use async signal safe calls only.
 
   const Ehdr* elf_header = GetElfHeader(elf_mapped_base);
-  if (!elf_header)
+  if (!elf_header) {
     return {};
+  }
 
   const char* phdr_start =
       reinterpret_cast<const char*>(elf_header) + elf_header->e_phoff;
@@ -209,5 +218,4 @@
                              reinterpret_cast<uintptr_t>(nullptr));
 }
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/elf_reader_unittest.cc b/tot/base/debug/elf_reader_unittest.cc
index 3ddda76..3b0c2a6 100644
--- a/tot/base/debug/elf_reader_unittest.cc
+++ b/tot/base/debug/elf_reader_unittest.cc
@@ -24,8 +24,7 @@
 
 extern char __executable_start;
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
 namespace {
 constexpr uint8_t kBuildIdBytes[] = {0xab, 0xcd, 0x12, 0x34};
@@ -236,5 +235,4 @@
 #endif
 }
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/gdi_debug_util_win.cc b/tot/base/debug/gdi_debug_util_win.cc
index 437cd52..047717e 100644
--- a/tot/base/debug/gdi_debug_util_win.cc
+++ b/tot/base/debug/gdi_debug_util_win.cc
@@ -4,11 +4,11 @@
 #include "base/debug/gdi_debug_util_win.h"
 
 #include <windows.h>
+#include <winternl.h>
 
 #include <TlHelp32.h>
 #include <psapi.h>
 #include <stddef.h>
-#include <winternl.h>
 
 #include <algorithm>
 #include <cmath>
@@ -18,6 +18,7 @@
 #include "base/logging.h"
 #include "base/notreached.h"
 #include "base/process/process.h"
+#include "base/win/scoped_gdi_object.h"
 #include "base/win/scoped_handle.h"
 #include "base/win/win_util.h"
 #include "base/win/windows_version.h"
@@ -179,8 +180,9 @@
   using GdiTableEntryVector =
       std::vector<GdiTableEntry<typename ProcessType::NativePointerType>>;
   HMODULE ntdll = GetModuleHandle(L"ntdll.dll");
-  if (!ntdll)
+  if (!ntdll) {
     return GdiTableEntryVector();
+  }
 
   static auto query_information_process_func =
       reinterpret_cast<typename ProcessType::QueryInformationProcessFunc*>(
@@ -227,7 +229,8 @@
   // Entry Count
   // 32-bit: 65792
   // 64-bit: 65706ish
-  // So we'll take a look at 65536 entries since that's the maximum handle count.
+  // So we'll take a look at 65536 entries since that's the maximum handle
+  // count.
   constexpr int kGdiTableEntryCount = 65536;
   GdiTableEntryVector entries;
   entries.resize(kGdiTableEntryCount);
@@ -252,8 +255,9 @@
     const std::vector<GdiTableEntry<PointerType>>& gdi_table) {
   base::debug::GdiHandleCounts counts{};
   for (const auto& entry : gdi_table) {
-    if (entry.wProcessId != pid)
+    if (entry.wProcessId != pid) {
       continue;
+    }
 
     switch (entry.wType & 0x7F) {
       case GdiHandleType::kDC:
@@ -292,8 +296,9 @@
 std::optional<base::debug::GdiHandleCounts> CollectGdiHandleCountsImpl(
     DWORD pid) {
   base::Process process = base::Process::OpenWithExtraPrivileges(pid);
-  if (!process.IsValid())
+  if (!process.IsValid()) {
     return std::nullopt;
+  }
 
   std::vector<GdiTableEntry<typename ProcessType::NativePointerType>>
       gdi_entries = GetGdiTableEntries<ProcessType>(process);
@@ -351,11 +356,10 @@
   base::debug::Alias(&small_data);
   header->biWidth = 5;
   header->biHeight = -5;
-  HBITMAP small_bitmap =
+  base::win::ScopedGDIObject<HBITMAP> small_bitmap(
       CreateDIBSection(nullptr, reinterpret_cast<BITMAPINFO*>(&header), 0,
-                       &small_data, shared_section, 0);
-  CHECK(small_bitmap != nullptr);
-  DeleteObject(small_bitmap);
+                       &small_data, shared_section, 0));
+  CHECK(small_bitmap.is_valid());
 }
 
 NOINLINE void GetProcessMemoryInfo(PROCESS_MEMORY_COUNTERS_EX* pmc) {
@@ -400,12 +404,11 @@
   GetFirstProcess(snapshot, &proc_entry);
 
   do {
-    base::win::ScopedHandle process(
-        OpenProcess(PROCESS_QUERY_INFORMATION,
-                    FALSE,
-                    proc_entry.th32ProcessID));
-    if (!process.is_valid())
+    base::win::ScopedHandle process(OpenProcess(
+        PROCESS_QUERY_INFORMATION, FALSE, proc_entry.th32ProcessID));
+    if (!process.is_valid()) {
       continue;
+    }
 
     DWORD num_gdi_handles = GetGuiResources(process.get(), GR_GDIOBJECTS);
     DWORD num_user_handles = GetGuiResources(process.get(), GR_USEROBJECTS);
@@ -416,8 +419,9 @@
     total_gdi_count += num_gdi_handles;
     total_peak_gdi_count = std::max(total_peak_gdi_count, num_gdi_handles);
 
-    if (parent_pid != proc_entry.th32ParentProcessID)
+    if (parent_pid != proc_entry.th32ParentProcessID) {
       continue;
+    }
 
     // Compute sum and peak counts for child processes.
     ++child_count;
diff --git a/tot/base/debug/handle_hooks_win.cc b/tot/base/debug/handle_hooks_win.cc
index 9bb8907..eb07225 100644
--- a/tot/base/debug/handle_hooks_win.cc
+++ b/tot/base/debug/handle_hooks_win.cc
@@ -89,16 +89,18 @@
 
   // Change the page protection so that we can write.
   MEMORY_BASIC_INFORMATION memory_info;
-  if (!VirtualQuery(address, &memory_info, sizeof(memory_info)))
+  if (!VirtualQuery(address, &memory_info, sizeof(memory_info))) {
     return false;
+  }
 
   DWORD is_executable = (PAGE_EXECUTE | PAGE_EXECUTE_READ |
                          PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY) &
                         memory_info.Protect;
 
   DWORD protect = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
-  if (!VirtualProtect(address, bytes, protect, &old_protect_))
+  if (!VirtualProtect(address, bytes, protect, &old_protect_)) {
     return false;
+  }
 
   changed_ = true;
   address_ = address;
@@ -107,8 +109,9 @@
 }
 
 void AutoProtectMemory::RevertProtection() {
-  if (!changed_)
+  if (!changed_) {
     return;
+  }
 
   DCHECK(address_);
   DCHECK(bytes_);
@@ -126,23 +129,28 @@
               const char* function_name,
               void* new_function,
               void** old_function) {
-  if (!module)
+  if (!module) {
     return;
+  }
 
   base::win::PEImage pe(module);
-  if (!pe.VerifyMagic())
+  if (!pe.VerifyMagic()) {
     return;
+  }
 
   DWORD* eat_entry = pe.GetExportEntry(function_name);
-  if (!eat_entry)
+  if (!eat_entry) {
     return;
+  }
 
-  if (!(*old_function))
+  if (!(*old_function)) {
     *old_function = pe.RVAToAddr(*eat_entry);
+  }
 
   AutoProtectMemory memory;
-  if (!memory.ChangeProtection(eat_entry, sizeof(DWORD)))
+  if (!memory.ChangeProtection(eat_entry, sizeof(DWORD))) {
     return;
+  }
 
   // Perform the patch.
   *eat_entry =
@@ -156,8 +164,9 @@
                                                       const char* function_name,
                                                       void* new_function,
                                                       void** old_function) {
-  if (!module)
+  if (!module) {
     return nullptr;
+  }
 
   auto patch = std::make_unique<base::win::IATPatchFunction>();
   __try {
@@ -188,22 +197,25 @@
 
 // static
 void HandleHooks::AddIATPatch(HMODULE module) {
-  if (!module)
+  if (!module) {
     return;
+  }
 
   auto close_handle_patch =
       IATPatch(module, "CloseHandle", reinterpret_cast<void*>(&CloseHandleHook),
                reinterpret_cast<void**>(&g_close_function));
-  if (!close_handle_patch)
+  if (!close_handle_patch) {
     return;
+  }
   // This is intentionally leaked.
   std::ignore = close_handle_patch.release();
 
   auto duplicate_handle_patch = IATPatch(
       module, "DuplicateHandle", reinterpret_cast<void*>(&DuplicateHandleHook),
       reinterpret_cast<void**>(&g_duplicate_function));
-  if (!duplicate_handle_patch)
+  if (!duplicate_handle_patch) {
     return;
+  }
   // This is intentionally leaked.
   std::ignore = duplicate_handle_patch.release();
 }
diff --git a/tot/base/debug/leak_annotations.h b/tot/base/debug/leak_annotations.h
index 506e1e0..3ac742d 100644
--- a/tot/base/debug/leak_annotations.h
+++ b/tot/base/debug/leak_annotations.h
@@ -33,8 +33,9 @@
   ~ScopedLeakSanitizerDisabler() { __lsan_enable(); }
 };
 
-#define ANNOTATE_SCOPED_MEMORY_LEAK \
-    ScopedLeakSanitizerDisabler leak_sanitizer_disabler; static_cast<void>(0)
+#define ANNOTATE_SCOPED_MEMORY_LEAK                    \
+  ScopedLeakSanitizerDisabler leak_sanitizer_disabler; \
+  static_cast<void>(0)
 
 #define ANNOTATE_LEAKING_OBJECT_PTR(X) __lsan_ignore_object(X);
 
diff --git a/tot/base/debug/proc_maps_linux.cc b/tot/base/debug/proc_maps_linux.cc
index c14f985..ea6f59a 100644
--- a/tot/base/debug/proc_maps_linux.cc
+++ b/tot/base/debug/proc_maps_linux.cc
@@ -12,6 +12,8 @@
 #include <fcntl.h>
 #include <stddef.h>
 
+#include <unordered_map>
+
 #include "base/files/file_util.h"
 #include "base/files/scoped_file.h"
 #include "base/format_macros.h"
@@ -29,6 +31,10 @@
 MappedMemoryRegion::MappedMemoryRegion() = default;
 MappedMemoryRegion::MappedMemoryRegion(const MappedMemoryRegion&) = default;
 MappedMemoryRegion::MappedMemoryRegion(MappedMemoryRegion&&) noexcept = default;
+MappedMemoryRegion& MappedMemoryRegion::operator=(MappedMemoryRegion&) =
+    default;
+MappedMemoryRegion& MappedMemoryRegion::operator=(
+    MappedMemoryRegion&&) noexcept = default;
 
 // Scans |proc_maps| starting from |pos| returning true if the gate VMA was
 // found, otherwise returns false.
@@ -75,8 +81,9 @@
     // ... and don't forget to trim off excess bytes.
     proc_maps->resize(pos + static_cast<size_t>(bytes_read));
 
-    if (bytes_read == 0)
+    if (bytes_read == 0) {
       break;
+    }
 
     // The gate VMA is handled as a special case after seq_file has finished
     // iterating through all entries in the virtual memory table.
@@ -86,8 +93,9 @@
     // entries including the gate VMA again.
     //
     // Avoid this by searching for the gate VMA and breaking early.
-    if (ContainsGateVMA(proc_maps, pos))
+    if (ContainsGateVMA(proc_maps, pos)) {
       break;
+    }
   }
 
   return true;
@@ -100,8 +108,8 @@
 
   // This isn't async safe nor terribly efficient, but it doesn't need to be at
   // this point in time.
-  std::vector<std::string> lines = SplitString(
-      input, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
+  std::vector<std::string> lines =
+      SplitString(input, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
 
   for (size_t i = 0; i < lines.size(); ++i) {
     // Due to splitting on '\n' the last line should be empty.
@@ -115,7 +123,7 @@
 
     MappedMemoryRegion region;
     const char* line = lines[i].c_str();
-    char permissions[5] = {'\0'};  // Ensure NUL-terminated string.
+    char permissions[5] = {};  // Ensure NUL-terminated string.
     uint8_t dev_major = 0;
     uint8_t dev_minor = 0;
     long inode = 0;
@@ -142,25 +150,30 @@
 
     region.permissions = 0;
 
-    if (permissions[0] == 'r')
+    if (permissions[0] == 'r') {
       region.permissions |= MappedMemoryRegion::READ;
-    else if (permissions[0] != '-')
+    } else if (permissions[0] != '-') {
       return false;
+    }
 
-    if (permissions[1] == 'w')
+    if (permissions[1] == 'w') {
       region.permissions |= MappedMemoryRegion::WRITE;
-    else if (permissions[1] != '-')
+    } else if (permissions[1] != '-') {
       return false;
+    }
 
-    if (permissions[2] == 'x')
+    if (permissions[2] == 'x') {
       region.permissions |= MappedMemoryRegion::EXECUTE;
-    else if (permissions[2] != '-')
+    } else if (permissions[2] != '-') {
       return false;
+    }
 
-    if (permissions[3] == 'p')
+    if (permissions[3] == 'p') {
       region.permissions |= MappedMemoryRegion::PRIVATE;
-    else if (permissions[3] != 's' && permissions[3] != 'S')  // Shared memory.
+    } else if (permissions[3] != 's' &&
+               permissions[3] != 'S') {  // Shared memory.
       return false;
+    }
 
     // Pushing then assigning saves us a string copy.
     regions.push_back(region);
diff --git a/tot/base/debug/proc_maps_linux.h b/tot/base/debug/proc_maps_linux.h
index 2fb43c7..700db87 100644
--- a/tot/base/debug/proc_maps_linux.h
+++ b/tot/base/debug/proc_maps_linux.h
@@ -27,6 +27,8 @@
   MappedMemoryRegion();
   MappedMemoryRegion(const MappedMemoryRegion&);
   MappedMemoryRegion(MappedMemoryRegion&&) noexcept;
+  MappedMemoryRegion& operator=(MappedMemoryRegion&);
+  MappedMemoryRegion& operator=(MappedMemoryRegion&&) noexcept;
 
   // The address range [start,end) of mapped memory.
   uintptr_t start;
diff --git a/tot/base/debug/proc_maps_linux_unittest.cc b/tot/base/debug/proc_maps_linux_unittest.cc
index ba0658c..3676210 100644
--- a/tot/base/debug/proc_maps_linux_unittest.cc
+++ b/tot/base/debug/proc_maps_linux_unittest.cc
@@ -3,8 +3,8 @@
 // found in the LICENSE file.
 
 #ifdef UNSAFE_BUFFERS_BUILD
-// TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
-#pragma allow_unsafe_buffers
+// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
+#pragma allow_unsafe_libc_calls
 #endif
 
 #include "base/debug/proc_maps_linux.h"
@@ -13,6 +13,8 @@
 #include <stdint.h>
 #include <sys/utsname.h>
 
+#include <array>
+
 #include "base/files/file_path.h"
 #include "base/path_service.h"
 #include "base/strings/stringprintf.h"
@@ -93,8 +95,7 @@
 }
 
 TEST(ProcMapsTest, NoPath) {
-  static const char kNoPath[] =
-      "00400000-0040b000 rw-p 00000000 00:00 0 \n";
+  static const char kNoPath[] = "00400000-0040b000 rw-p 00000000 00:00 0 \n";
 
   std::vector<MappedMemoryRegion> regions;
   ASSERT_TRUE(ParseProcMaps(kNoPath, &regions));
@@ -177,33 +178,34 @@
 }
 
 TEST(ProcMapsTest, Permissions) {
-  static struct {
+  struct TestCases {
     const char* input;
     uint8_t permissions;
-  } kTestCases[] = {
-    {"00400000-0040b000 ---s 00000000 fc:00 794418 /bin/cat\n", 0},
-    {"00400000-0040b000 ---S 00000000 fc:00 794418 /bin/cat\n", 0},
-    {"00400000-0040b000 r--s 00000000 fc:00 794418 /bin/cat\n",
-     MappedMemoryRegion::READ},
-    {"00400000-0040b000 -w-s 00000000 fc:00 794418 /bin/cat\n",
-     MappedMemoryRegion::WRITE},
-    {"00400000-0040b000 --xs 00000000 fc:00 794418 /bin/cat\n",
-     MappedMemoryRegion::EXECUTE},
-    {"00400000-0040b000 rwxs 00000000 fc:00 794418 /bin/cat\n",
-     MappedMemoryRegion::READ | MappedMemoryRegion::WRITE |
-         MappedMemoryRegion::EXECUTE},
-    {"00400000-0040b000 ---p 00000000 fc:00 794418 /bin/cat\n",
-     MappedMemoryRegion::PRIVATE},
-    {"00400000-0040b000 r--p 00000000 fc:00 794418 /bin/cat\n",
-     MappedMemoryRegion::READ | MappedMemoryRegion::PRIVATE},
-    {"00400000-0040b000 -w-p 00000000 fc:00 794418 /bin/cat\n",
-     MappedMemoryRegion::WRITE | MappedMemoryRegion::PRIVATE},
-    {"00400000-0040b000 --xp 00000000 fc:00 794418 /bin/cat\n",
-     MappedMemoryRegion::EXECUTE | MappedMemoryRegion::PRIVATE},
-    {"00400000-0040b000 rwxp 00000000 fc:00 794418 /bin/cat\n",
-     MappedMemoryRegion::READ | MappedMemoryRegion::WRITE |
-         MappedMemoryRegion::EXECUTE | MappedMemoryRegion::PRIVATE},
   };
+  static auto kTestCases = std::to_array<TestCases>({
+      {"00400000-0040b000 ---s 00000000 fc:00 794418 /bin/cat\n", 0},
+      {"00400000-0040b000 ---S 00000000 fc:00 794418 /bin/cat\n", 0},
+      {"00400000-0040b000 r--s 00000000 fc:00 794418 /bin/cat\n",
+       MappedMemoryRegion::READ},
+      {"00400000-0040b000 -w-s 00000000 fc:00 794418 /bin/cat\n",
+       MappedMemoryRegion::WRITE},
+      {"00400000-0040b000 --xs 00000000 fc:00 794418 /bin/cat\n",
+       MappedMemoryRegion::EXECUTE},
+      {"00400000-0040b000 rwxs 00000000 fc:00 794418 /bin/cat\n",
+       MappedMemoryRegion::READ | MappedMemoryRegion::WRITE |
+           MappedMemoryRegion::EXECUTE},
+      {"00400000-0040b000 ---p 00000000 fc:00 794418 /bin/cat\n",
+       MappedMemoryRegion::PRIVATE},
+      {"00400000-0040b000 r--p 00000000 fc:00 794418 /bin/cat\n",
+       MappedMemoryRegion::READ | MappedMemoryRegion::PRIVATE},
+      {"00400000-0040b000 -w-p 00000000 fc:00 794418 /bin/cat\n",
+       MappedMemoryRegion::WRITE | MappedMemoryRegion::PRIVATE},
+      {"00400000-0040b000 --xp 00000000 fc:00 794418 /bin/cat\n",
+       MappedMemoryRegion::EXECUTE | MappedMemoryRegion::PRIVATE},
+      {"00400000-0040b000 rwxp 00000000 fc:00 794418 /bin/cat\n",
+       MappedMemoryRegion::READ | MappedMemoryRegion::WRITE |
+           MappedMemoryRegion::EXECUTE | MappedMemoryRegion::PRIVATE},
+  });
 
   for (size_t i = 0; i < std::size(kTestCases); ++i) {
     SCOPED_TRACE(
@@ -212,8 +214,9 @@
     std::vector<MappedMemoryRegion> regions;
     EXPECT_TRUE(ParseProcMaps(kTestCases[i].input, &regions));
     EXPECT_EQ(1u, regions.size());
-    if (regions.empty())
+    if (regions.empty()) {
       continue;
+    }
     EXPECT_EQ(kTestCases[i].permissions, regions[0].permissions);
   }
 }
@@ -288,19 +291,19 @@
 }
 
 TEST(ProcMapsTest, MissingFields) {
-  static const char* const kTestCases[] = {
-    "00400000\n",                               // Missing end + beyond.
-    "00400000-0040b000\n",                      // Missing perms + beyond.
-    "00400000-0040b000 r-xp\n",                 // Missing offset + beyond.
-    "00400000-0040b000 r-xp 00000000\n",        // Missing device + beyond.
-    "00400000-0040b000 r-xp 00000000 fc:00\n",  // Missing inode + beyond.
-    "00400000-0040b000 00000000 fc:00 794418 /bin/cat\n",  // Missing perms.
-    "00400000-0040b000 r-xp fc:00 794418 /bin/cat\n",      // Missing offset.
-    "00400000-0040b000 r-xp 00000000 fc:00 /bin/cat\n",    // Missing inode.
-    "00400000 r-xp 00000000 fc:00 794418 /bin/cat\n",      // Missing end.
-    "-0040b000 r-xp 00000000 fc:00 794418 /bin/cat\n",     // Missing start.
-    "00400000-0040b000 r-xp 00000000 794418 /bin/cat\n",   // Missing device.
-  };
+  static const auto kTestCases = std::to_array<const char*>({
+      "00400000\n",                               // Missing end + beyond.
+      "00400000-0040b000\n",                      // Missing perms + beyond.
+      "00400000-0040b000 r-xp\n",                 // Missing offset + beyond.
+      "00400000-0040b000 r-xp 00000000\n",        // Missing device + beyond.
+      "00400000-0040b000 r-xp 00000000 fc:00\n",  // Missing inode + beyond.
+      "00400000-0040b000 00000000 fc:00 794418 /bin/cat\n",  // Missing perms.
+      "00400000-0040b000 r-xp fc:00 794418 /bin/cat\n",      // Missing offset.
+      "00400000-0040b000 r-xp 00000000 fc:00 /bin/cat\n",    // Missing inode.
+      "00400000 r-xp 00000000 fc:00 794418 /bin/cat\n",      // Missing end.
+      "-0040b000 r-xp 00000000 fc:00 794418 /bin/cat\n",     // Missing start.
+      "00400000-0040b000 r-xp 00000000 794418 /bin/cat\n",   // Missing device.
+  });
 
   for (size_t i = 0; i < std::size(kTestCases); ++i) {
     SCOPED_TRACE(base::StringPrintf("kTestCases[%zu] = %s", i, kTestCases[i]));
@@ -310,14 +313,14 @@
 }
 
 TEST(ProcMapsTest, InvalidInput) {
-  static const char* const kTestCases[] = {
-    "thisisal-0040b000 rwxp 00000000 fc:00 794418 /bin/cat\n",
-    "0040000d-linvalid rwxp 00000000 fc:00 794418 /bin/cat\n",
-    "00400000-0040b000 inpu 00000000 fc:00 794418 /bin/cat\n",
-    "00400000-0040b000 rwxp tforproc fc:00 794418 /bin/cat\n",
-    "00400000-0040b000 rwxp 00000000 ma:ps 794418 /bin/cat\n",
-    "00400000-0040b000 rwxp 00000000 fc:00 parse! /bin/cat\n",
-  };
+  static const auto kTestCases = std::to_array<const char*>({
+      "thisisal-0040b000 rwxp 00000000 fc:00 794418 /bin/cat\n",
+      "0040000d-linvalid rwxp 00000000 fc:00 794418 /bin/cat\n",
+      "00400000-0040b000 inpu 00000000 fc:00 794418 /bin/cat\n",
+      "00400000-0040b000 rwxp tforproc fc:00 794418 /bin/cat\n",
+      "00400000-0040b000 rwxp 00000000 ma:ps 794418 /bin/cat\n",
+      "00400000-0040b000 rwxp 00000000 fc:00 parse! /bin/cat\n",
+  });
 
   for (size_t i = 0; i < std::size(kTestCases); ++i) {
     SCOPED_TRACE(base::StringPrintf("kTestCases[%zu] = %s", i, kTestCases[i]));
@@ -339,15 +342,15 @@
 TEST(ProcMapsTest, ParseProcMapsWeirdCorrectInput) {
   std::vector<MappedMemoryRegion> regions;
   const std::string kContents =
-    "00400000-0040b000 r-xp 00000000 fc:00 2106562 "
+      "00400000-0040b000 r-xp 00000000 fc:00 2106562 "
       "               /bin/cat\r\n"
-    "7f53b7dad000-7f53b7f62000 r-xp 00000000 fc:00 263011 "
+      "7f53b7dad000-7f53b7f62000 r-xp 00000000 fc:00 263011 "
       "       /lib/x86_64-linux-gnu/libc-2.15.so\n\r"
-    "7f53b816d000-7f53b818f000 r-xp 00000000 fc:00 264284 "
+      "7f53b816d000-7f53b818f000 r-xp 00000000 fc:00 264284 "
       "        /lib/x86_64-linux-gnu/ld-2.15.so\n"
-    "7fff9c7ff000-7fff9c800000 r-xp 00000000 00:00 0 "
+      "7fff9c7ff000-7fff9c800000 r-xp 00000000 00:00 0 "
       "               \"vd so\"\n"
-    "ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 "
+      "ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 "
       "               [vsys call]\n";
   EXPECT_TRUE(ParseProcMaps(kContents, &regions));
   EXPECT_EQ(5ULL, regions.size());
diff --git a/tot/base/debug/profiler.cc b/tot/base/debug/profiler.cc
index 1f4eded..7a0f4e2 100644
--- a/tot/base/debug/profiler.cc
+++ b/tot/base/debug/profiler.cc
@@ -14,24 +14,19 @@
 #include "base/win/pe_image.h"
 #endif  // BUILDFLAG(IS_WIN)
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
-void StartProfiling(const std::string& name) {
-}
+void StartProfiling(const std::string& name) {}
 
-void StopProfiling() {
-}
+void StopProfiling() {}
 
-void FlushProfiling() {
-}
+void FlushProfiling() {}
 
 bool BeingProfiled() {
   return false;
 }
 
-void RestartProfilingAfterFork() {
-}
+void RestartProfilingAfterFork() {}
 
 bool IsProfilingSupported() {
   return false;
@@ -61,10 +56,11 @@
 };
 
 // Callback function to PEImage::EnumImportChunks.
-bool FindResolutionFunctionInImports(
-    const base::win::PEImage &image, const char* module_name,
-    PIMAGE_THUNK_DATA unused_name_table, PIMAGE_THUNK_DATA import_address_table,
-    PVOID cookie) {
+bool FindResolutionFunctionInImports(const base::win::PEImage& image,
+                                     const char* module_name,
+                                     PIMAGE_THUNK_DATA unused_name_table,
+                                     PIMAGE_THUNK_DATA import_address_table,
+                                     PVOID cookie) {
   FunctionSearchContext* context =
       reinterpret_cast<FunctionSearchContext*>(cookie);
 
@@ -102,7 +98,7 @@
 FunctionType FindFunctionInImports(const char* function_name) {
   base::win::PEImage image(CURRENT_MODULE());
 
-  FunctionSearchContext ctx = { function_name, NULL };
+  FunctionSearchContext ctx = {function_name, NULL};
   image.EnumImportChunks(FindResolutionFunctionInImports, &ctx, nullptr);
 
   return reinterpret_cast<FunctionType>(ctx.function);
@@ -116,16 +112,13 @@
 }
 
 AddDynamicSymbol GetProfilerAddDynamicSymbolFunc() {
-  return FindFunctionInImports<AddDynamicSymbol>(
-      "AddDynamicSymbol");
+  return FindFunctionInImports<AddDynamicSymbol>("AddDynamicSymbol");
 }
 
 MoveDynamicSymbol GetProfilerMoveDynamicSymbolFunc() {
-  return FindFunctionInImports<MoveDynamicSymbol>(
-      "MoveDynamicSymbol");
+  return FindFunctionInImports<MoveDynamicSymbol>("MoveDynamicSymbol");
 }
 
 #endif  // BUILDFLAG(IS_WIN)
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/profiler.h b/tot/base/debug/profiler.h
index 035affc..53a0888 100644
--- a/tot/base/debug/profiler.h
+++ b/tot/base/debug/profiler.h
@@ -63,7 +63,6 @@
                                  size_t name_len);
 typedef void (*MoveDynamicSymbol)(const void* address, const void* new_address);
 
-
 // If this binary is instrumented and the instrumentation supplies a function
 // for each of those purposes, find and return the function in question.
 // Otherwise returns NULL.
diff --git a/tot/base/debug/stack_trace.cc b/tot/base/debug/stack_trace.cc
index 6226b3b..fe2c83a 100644
--- a/tot/base/debug/stack_trace.cc
+++ b/tot/base/debug/stack_trace.cc
@@ -35,8 +35,7 @@
 
 #endif  // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
 namespace {
 
@@ -95,20 +94,30 @@
 bool IsStackFrameValid(uintptr_t fp, uintptr_t prev_fp, uintptr_t stack_end) {
   // With the stack growing downwards, older stack frame must be
   // at a greater address that the current one.
-  if (fp <= prev_fp) return false;
+  if (fp <= prev_fp) {
+    return false;
+  }
 
   // Assume huge stack frames are bogus.
-  if (fp - prev_fp > 100000) return false;
+  if (fp - prev_fp > 100000) {
+    return false;
+  }
 
   // Check alignment.
-  if (fp & (sizeof(uintptr_t) - 1)) return false;
+  if (fp & (sizeof(uintptr_t) - 1)) {
+    return false;
+  }
 
   if (stack_end) {
     // Both fp[0] and fp[1] must be within the stack.
-    if (fp > stack_end - 2 * sizeof(uintptr_t)) return false;
+    if (fp > stack_end - 2 * sizeof(uintptr_t)) {
+      return false;
+    }
 
     // Additional check to filter out false positives.
-    if (GetStackFramePC(fp) < 32768) return false;
+    if (GetStackFramePC(fp) < 32768) {
+      return false;
+    }
   }
 
   return true;
@@ -141,9 +150,9 @@
   }
 
   fp += sizeof(uintptr_t);  // current frame is known to be invalid
-  uintptr_t last_fp_to_scan = std::min(fp + kMaxStackScanArea, stack_end) -
-                                  sizeof(uintptr_t);
-  for (;fp <= last_fp_to_scan; fp += sizeof(uintptr_t)) {
+  uintptr_t last_fp_to_scan =
+      std::min(fp + kMaxStackScanArea, stack_end) - sizeof(uintptr_t);
+  for (; fp <= last_fp_to_scan; fp += sizeof(uintptr_t)) {
     uintptr_t next_fp = GetNextStackFrame(fp);
     if (IsStackFrameValid(next_fp, fp, stack_end)) {
       // Check two frames deep. Since stack frame is just a pointer to
@@ -197,7 +206,7 @@
   // values from its pthread_t argument.
   static uintptr_t main_stack_end = 0;
 
-  bool is_main_thread = GetCurrentProcId() == PlatformThread::CurrentId();
+  bool is_main_thread = GetCurrentProcId() == PlatformThread::CurrentId().raw();
   if (is_main_thread && main_stack_end) {
     return main_stack_end;
   }
@@ -225,7 +234,8 @@
 #else
 
 #if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(__GLIBC__)
-  if (GetCurrentProcId() == PlatformThread::CurrentId()) {
+  static_assert(std::is_same_v<ProcessId, PlatformThreadId::UnderlyingType>);
+  if (GetCurrentProcId() == PlatformThread::CurrentId().raw()) {
     // For the main thread we have a shortcut.
     return reinterpret_cast<uintptr_t>(__libc_stack_end);
   }
@@ -436,5 +446,4 @@
 
 #endif  // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/stack_trace_android.cc b/tot/base/debug/stack_trace_android.cc
index 7537726..a184a51 100644
--- a/tot/base/debug/stack_trace_android.cc
+++ b/tot/base/debug/stack_trace_android.cc
@@ -11,6 +11,7 @@
 #include <algorithm>
 #include <ostream>
 
+#include "base/compiler_specific.h"
 #include "base/debug/proc_maps_linux.h"
 #include "base/memory/raw_ptr.h"
 #include "base/strings/strcat.h"
@@ -18,9 +19,9 @@
 #include "base/threading/thread_restrictions.h"
 
 #ifdef __LP64__
-#define FMT_ADDR  "0x%016lx"
+#define FMT_ADDR "0x%016lx"
 #else
-#define FMT_ADDR  "0x%08x"
+#define FMT_ADDR "0x%08x"
 #endif
 
 namespace {
@@ -49,8 +50,9 @@
   }
 
   state->frames[state->frame_count++] = ip;
-  if (state->frame_count >= state->max_depth)
+  if (state->frame_count >= state->max_depth) {
     return _URC_END_OF_STACK;
+  }
   return _URC_NO_REASON;
 }
 
@@ -70,7 +72,7 @@
   // with SIGPIPE ignored as well.
   // TODO(phajdan.jr): De-duplicate this SIGPIPE code.
   struct sigaction action;
-  memset(&action, 0, sizeof(action));
+  UNSAFE_TODO(memset(&action, 0, sizeof(action)));
   action.sa_handler = SIG_IGN;
   sigemptyset(&action.sa_mask);
   return (sigaction(SIGPIPE, &action, NULL) == 0);
@@ -114,11 +116,11 @@
   // UI thread.
   base::ScopedAllowBlocking scoped_allow_blocking;
   if (!ReadProcMaps(&proc_maps)) {
-    __android_log_write(
-        ANDROID_LOG_ERROR, "chromium", "Failed to read /proc/self/maps");
+    __android_log_write(ANDROID_LOG_ERROR, "chromium",
+                        "Failed to read /proc/self/maps");
   } else if (!ParseProcMaps(proc_maps, &regions)) {
-    __android_log_write(
-        ANDROID_LOG_ERROR, "chromium", "Failed to parse /proc/self/maps");
+    __android_log_write(ANDROID_LOG_ERROR, "chromium",
+                        "Failed to parse /proc/self/maps");
   }
 
   for (size_t i = 0; i < count_; ++i) {
diff --git a/tot/base/debug/stack_trace_fuchsia.cc b/tot/base/debug/stack_trace_fuchsia.cc
index 59f4ba2..629eaf6 100644
--- a/tot/base/debug/stack_trace_fuchsia.cc
+++ b/tot/base/debug/stack_trace_fuchsia.cc
@@ -9,8 +9,6 @@
 #pragma allow_unsafe_buffers
 #endif
 
-#include "base/debug/stack_trace.h"
-
 #include <elf.h>
 #include <link.h>
 #include <stddef.h>
@@ -30,6 +28,7 @@
 
 #include "base/atomic_sequence_num.h"
 #include "base/debug/elf_reader.h"
+#include "base/debug/stack_trace.h"
 #include "base/logging.h"
 
 namespace base {
@@ -48,8 +47,9 @@
   uintptr_t pc = _Unwind_GetIP(context);
   data->trace_array[*data->count] = reinterpret_cast<void*>(pc);
   *data->count += 1;
-  if (*data->count == data->max)
+  if (*data->count == data->max) {
     return _URC_END_OF_STACK;
+  }
   return _URC_NO_REASON;
 }
 
@@ -59,14 +59,17 @@
 const char* PermissionFlagsToString(int flags, char permission_buf[4]) {
   char* permission = permission_buf;
 
-  if (flags & PF_R)
+  if (flags & PF_R) {
     (*permission++) = 'r';
+  }
 
-  if (flags & PF_W)
+  if (flags & PF_W) {
     (*permission++) = 'w';
+  }
 
-  if (flags & PF_X)
+  if (flags & PF_X) {
     (*permission++) = 'x';
+  }
 
   *permission = '\0';
 
@@ -91,8 +94,8 @@
     raw_ptr<const void> addr = nullptr;
     std::array<Segment, kMaxSegmentCount> segments;
     size_t segment_count = 0;
-    char name[ZX_MAX_NAME_LEN + 1] = {0};
-    char build_id[kMaxBuildIdStringLength + 1] = {0};
+    char name[ZX_MAX_NAME_LEN + 1] = {};
+    char build_id[kMaxBuildIdStringLength + 1] = {};
   };
 
   SymbolMap();
@@ -145,8 +148,9 @@
 
   // Populate ELF binary metadata into |modules_|.
   while (lmap != nullptr) {
-    if (count_ >= kMaxMapEntries)
+    if (count_ >= kMaxMapEntries) {
       break;
+    }
 
     SymbolMap::Module& next_entry = modules_[count_];
     ++count_;
@@ -157,8 +161,9 @@
     // Each Segment corresponds to a "mmap" line in the output.
     next_entry.segment_count = 0;
     for (const Elf64_Phdr& phdr : GetElfProgramHeaders(next_entry.addr)) {
-      if (phdr.p_type != PT_LOAD)
+      if (phdr.p_type != PT_LOAD) {
         continue;
+      }
 
       if (next_entry.segment_count > Module::kMaxSegmentCount) {
         LOG(WARNING) << "Exceeded the maximum number of segments.";
@@ -284,15 +289,16 @@
           << std::dec << ":load:" << module_id << ":"
           << PermissionFlagsToString(segment.permission_flags,
                                      permission_string)
-          << ":"
-          << "0x" << std::hex << segment.relative_addr << std::dec << "}}}\n";
+          << ":" << "0x" << std::hex << segment.relative_addr << std::dec
+          << "}}}\n";
     }
 
     ++module_id;
   }
 
-  for (size_t i = 0; i < count_; ++i)
+  for (size_t i = 0; i < count_; ++i) {
     *os << "{{{bt:" << i << ":" << trace_[i] << "}}}\n";
+  }
 
   *os << "{{{reset}}}\n";
 }
diff --git a/tot/base/debug/stack_trace_perftest.cc b/tot/base/debug/stack_trace_perftest.cc
index 7cf2b7f..d971189 100644
--- a/tot/base/debug/stack_trace_perftest.cc
+++ b/tot/base/debug/stack_trace_perftest.cc
@@ -2,18 +2,18 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "base/debug/stack_trace.h"
+
 #include <vector>
 
 #include "base/containers/span.h"
-#include "base/debug/stack_trace.h"
 #include "base/logging.h"
 #include "base/strings/stringprintf.h"
 #include "base/timer/lap_timer.h"
 #include "testing/gtest/include/gtest/gtest.h"
 #include "testing/perf/perf_result_reporter.h"
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
 // Change kTimeLimit to something higher if you need more time to capture a
 // trace.
@@ -33,7 +33,7 @@
 
 class StackTracer {
  public:
-  StackTracer(size_t trace_count) : trace_count_(trace_count) {}
+  explicit StackTracer(size_t trace_count) : trace_count_(trace_count) {}
   void Trace() {
     StackTrace st(trace_count_);
     span<const void* const> addresses = st.addresses();
@@ -67,8 +67,9 @@
   timer.Start();
   do {
     (*it)->Trace();
-    if (++it == tracers.end())
+    if (++it == tracers.end()) {
       it = tracers.begin();
+    }
     timer.NextLap();
   } while (!timer.HasTimeLimitExpired());
   reporter.AddResult(kMetricStackTraceDuration, timer.TimePerLap());
@@ -86,5 +87,4 @@
   MultiObjTest(parm);
 }
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/stack_trace_posix.cc b/tot/base/debug/stack_trace_posix.cc
index 7db911e..f7f019b 100644
--- a/tot/base/debug/stack_trace_posix.cc
+++ b/tot/base/debug/stack_trace_posix.cc
@@ -2,6 +2,11 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#ifdef UNSAFE_BUFFERS_BUILD
+// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
+#pragma allow_unsafe_libc_calls
+#endif
+
 #include "base/debug/stack_trace.h"
 
 #include <errno.h>
@@ -171,7 +176,7 @@
 void OutputPointer(const void* pointer, BacktraceOutputHandler* handler) {
   // This should be more than enough to store a 64-bit number in hex:
   // 16 hex digits + 1 for null-terminator.
-  char buf[17] = { '\0' };
+  char buf[17] = {'\0'};
   handler->HandleOutput("0x");
   internal::itoa_r(reinterpret_cast<intptr_t>(pointer), 16, 12, buf);
   handler->HandleOutput(buf);
@@ -182,7 +187,7 @@
   // Max unsigned 64-bit number in decimal has 20 digits (18446744073709551615).
   // Hence, 30 digits should be more than enough to represent it in decimal
   // (including the null-terminator).
-  char buf[30] = { '\0' };
+  char buf[30] = {'\0'};
   internal::itoa_r(static_cast<intptr_t>(value), 10, 1, buf);
   handler->HandleOutput(buf);
 }
@@ -211,8 +216,9 @@
 #endif
 
   for (size_t i = 0; i < traces.size(); ++i) {
-    if (!prefix_string.empty())
+    if (!prefix_string.empty()) {
       handler->HandleOutput(prefix_string.c_str());
+    }
 
     OutputFrameId(i, handler);
     handler->HandleOutput(" ");
@@ -294,8 +300,9 @@
       for (char* s : trace_symbols) {
         auto trace_symbol = std::string(s);
         DemangleSymbols(&trace_symbol);
-        if (!prefix_string.empty())
+        if (!prefix_string.empty()) {
           handler->HandleOutput(prefix_string.c_str());
+        }
         handler->HandleOutput(trace_symbol.c_str());
         handler->HandleOutput("\n");
       }
@@ -382,73 +389,80 @@
   in_signal_handler = 1;
 #endif
 
-  if (BeingDebugged())
+  if (BeingDebugged()) {
     BreakDebugger();
+  }
 
   PrintToStderr("Received signal ");
-  char buf[1024] = { 0 };
+  char buf[1024] = {0};
   internal::itoa_r(signal, 10, 0, buf);
   PrintToStderr(buf);
   if (signal == SIGBUS) {
-    if (info->si_code == BUS_ADRALN)
+    if (info->si_code == BUS_ADRALN) {
       PrintToStderr(" BUS_ADRALN ");
-    else if (info->si_code == BUS_ADRERR)
+    } else if (info->si_code == BUS_ADRERR) {
       PrintToStderr(" BUS_ADRERR ");
-    else if (info->si_code == BUS_OBJERR)
+    } else if (info->si_code == BUS_OBJERR) {
       PrintToStderr(" BUS_OBJERR ");
-    else
+    } else {
       PrintToStderr(" <unknown> ");
+    }
   } else if (signal == SIGFPE) {
-    if (info->si_code == FPE_FLTDIV)
+    if (info->si_code == FPE_FLTDIV) {
       PrintToStderr(" FPE_FLTDIV ");
-    else if (info->si_code == FPE_FLTINV)
+    } else if (info->si_code == FPE_FLTINV) {
       PrintToStderr(" FPE_FLTINV ");
-    else if (info->si_code == FPE_FLTOVF)
+    } else if (info->si_code == FPE_FLTOVF) {
       PrintToStderr(" FPE_FLTOVF ");
-    else if (info->si_code == FPE_FLTRES)
+    } else if (info->si_code == FPE_FLTRES) {
       PrintToStderr(" FPE_FLTRES ");
-    else if (info->si_code == FPE_FLTSUB)
+    } else if (info->si_code == FPE_FLTSUB) {
       PrintToStderr(" FPE_FLTSUB ");
-    else if (info->si_code == FPE_FLTUND)
+    } else if (info->si_code == FPE_FLTUND) {
       PrintToStderr(" FPE_FLTUND ");
-    else if (info->si_code == FPE_INTDIV)
+    } else if (info->si_code == FPE_INTDIV) {
       PrintToStderr(" FPE_INTDIV ");
-    else if (info->si_code == FPE_INTOVF)
+    } else if (info->si_code == FPE_INTOVF) {
       PrintToStderr(" FPE_INTOVF ");
-    else
+    } else {
       PrintToStderr(" <unknown> ");
+    }
   } else if (signal == SIGILL) {
-    if (info->si_code == ILL_BADSTK)
+    if (info->si_code == ILL_BADSTK) {
       PrintToStderr(" ILL_BADSTK ");
-    else if (info->si_code == ILL_COPROC)
+    } else if (info->si_code == ILL_COPROC) {
       PrintToStderr(" ILL_COPROC ");
-    else if (info->si_code == ILL_ILLOPN)
+    } else if (info->si_code == ILL_ILLOPN) {
       PrintToStderr(" ILL_ILLOPN ");
-    else if (info->si_code == ILL_ILLADR)
+    } else if (info->si_code == ILL_ILLADR) {
       PrintToStderr(" ILL_ILLADR ");
-    else if (info->si_code == ILL_ILLTRP)
+    } else if (info->si_code == ILL_ILLTRP) {
       PrintToStderr(" ILL_ILLTRP ");
-    else if (info->si_code == ILL_PRVOPC)
+    } else if (info->si_code == ILL_PRVOPC) {
       PrintToStderr(" ILL_PRVOPC ");
-    else if (info->si_code == ILL_PRVREG)
+    } else if (info->si_code == ILL_PRVREG) {
       PrintToStderr(" ILL_PRVREG ");
-    else
+    } else {
       PrintToStderr(" <unknown> ");
+    }
   } else if (signal == SIGSEGV) {
-    if (info->si_code == SEGV_MAPERR)
+    if (info->si_code == SEGV_MAPERR) {
       PrintToStderr(" SEGV_MAPERR ");
-    else if (info->si_code == SEGV_ACCERR)
+    } else if (info->si_code == SEGV_ACCERR) {
       PrintToStderr(" SEGV_ACCERR ");
+    }
 #if defined(ARCH_CPU_X86_64) && \
     (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS))
-    else if (info->si_code == SI_KERNEL)
+    else if (info->si_code == SI_KERNEL) {
       PrintToStderr(" SI_KERNEL");
+    }
 #endif
-    else
+    else {
       PrintToStderr(" <unknown> ");
+    }
   }
-  if (signal == SIGBUS || signal == SIGFPE ||
-      signal == SIGILL || signal == SIGSEGV) {
+  if (signal == SIGBUS || signal == SIGFPE || signal == SIGILL ||
+      signal == SIGSEGV) {
     internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr), 16, 12, buf);
     PrintToStderr(buf);
   }
@@ -524,8 +538,9 @@
     internal::itoa_r(registers[i].value, 16, kRegisterPadding, buf);
     PrintToStderr(buf);
 
-    if ((i + 1) % 4 == 0)
+    if ((i + 1) % 4 == 0) {
       PrintToStderr("\n");
+    }
   }
   PrintToStderr("\n");
 #endif  // ARCH_CPU_X86_FAMILY
@@ -607,8 +622,7 @@
 
 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
  public:
-  explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {
-  }
+  explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {}
 
   StreamBacktraceOutputHandler(const StreamBacktraceOutputHandler&) = delete;
   StreamBacktraceOutputHandler& operator=(const StreamBacktraceOutputHandler&) =
@@ -678,10 +692,7 @@
  private:
   friend struct DefaultSingletonTraits<SandboxSymbolizeHelper>;
 
-  SandboxSymbolizeHelper()
-      : is_initialized_(false) {
-    Init();
-  }
+  SandboxSymbolizeHelper() { Init(); }
 
   ~SandboxSymbolizeHelper() {
     UnregisterCallback();
@@ -957,7 +968,7 @@
   }
 
   // Set to true upon successful initialization.
-  bool is_initialized_;
+  bool is_initialized_ = false;
 
 #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
   // Mapping from file name to file descriptor.  Includes file descriptors
@@ -1124,8 +1135,9 @@
     }
     j /= static_cast<uintptr_t>(base);
 
-    if (padding > 0)
+    if (padding > 0) {
       padding--;
+    }
   } while (j > 0 || padding > 0);
 
   // Terminate the output with a NUL character.
diff --git a/tot/base/debug/stack_trace_unittest.cc b/tot/base/debug/stack_trace_unittest.cc
index 4e1547d..b2b4105 100644
--- a/tot/base/debug/stack_trace_unittest.cc
+++ b/tot/base/debug/stack_trace_unittest.cc
@@ -33,8 +33,7 @@
 #include "base/test/multiprocess_test.h"
 #endif
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
 #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
 typedef MultiProcessTest StackTraceTest;
@@ -73,8 +72,9 @@
   ASSERT_GT(addresses.size(), 5u) << "Too few frames found.";
   ASSERT_NE(nullptr, addresses[0]);
 
-  if (!StackTrace::WillSymbolizeToStreamForTesting())
+  if (!StackTrace::WillSymbolizeToStreamForTesting()) {
     return;
+  }
 
   // Check if the output has symbol initialization warning.  If it does, fail.
   ASSERT_EQ(backtrace_message.find("Dumping unresolved backtrace"),
@@ -456,5 +456,4 @@
 
 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID)
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/stack_trace_win.cc b/tot/base/debug/stack_trace_win.cc
index b4eb21d..1a5e3d6 100644
--- a/tot/base/debug/stack_trace_win.cc
+++ b/tot/base/debug/stack_trace_win.cc
@@ -17,7 +17,6 @@
 #include "base/files/file_path.h"
 #include "base/logging.h"
 #include "base/memory/singleton.h"
-#include "base/ranges/algorithm.h"
 #include "base/strings/strcat_win.h"
 #include "base/strings/string_util.h"
 #include "base/synchronization/lock.h"
@@ -112,8 +111,9 @@
   std::cerr << "\n";
 
   debug::StackTrace(info).Print();
-  if (g_previous_filter)
+  if (g_previous_filter) {
     return g_previous_filter(info);
+  }
   return EXCEPTION_CONTINUE_SEARCH;
 }
 
@@ -132,12 +132,14 @@
 // See crbug.com/1339753
 bool SymInitializeWrapper(HANDLE handle, BOOL invade_process) {
   for (size_t i = 0; i < kSymInitializeRetryCount; ++i) {
-    if (SymInitialize(handle, nullptr, invade_process))
+    if (SymInitialize(handle, nullptr, invade_process)) {
       return true;
+    }
 
     g_init_error = GetLastError();
-    if (g_init_error != g_status_info_length_mismatch)
+    if (g_init_error != g_status_info_length_mismatch) {
       return false;
+    }
   }
   DLOG(ERROR) << "SymInitialize failed repeatedly.";
   return false;
@@ -145,13 +147,15 @@
 
 bool SymInitializeCurrentProc() {
   const HANDLE current_process = GetCurrentProcess();
-  if (SymInitializeWrapper(current_process, TRUE))
+  if (SymInitializeWrapper(current_process, TRUE)) {
     return true;
+  }
 
   // g_init_error is updated by SymInitializeWrapper.
   // No need to do "g_init_error = GetLastError()" here.
-  if (g_init_error != ERROR_INVALID_PARAMETER)
+  if (g_init_error != ERROR_INVALID_PARAMETER) {
     return false;
+  }
 
   // SymInitialize() can fail with ERROR_INVALID_PARAMETER when something has
   // already called SymInitialize() in this process. For example, when absl
@@ -159,8 +163,9 @@
   // almost immediately after startup. In such a case, try to reinit to see if
   // that succeeds.
   SymCleanup(current_process);
-  if (SymInitializeWrapper(current_process, TRUE))
+  if (SymInitializeWrapper(current_process, TRUE)) {
     return true;
+  }
 
   return false;
 }
@@ -175,9 +180,7 @@
   g_initialized_symbols = true;
   // Defer symbol load until they're needed, use undecorated names, and get line
   // numbers.
-  SymSetOptions(SYMOPT_DEFERRED_LOADS |
-                SYMOPT_UNDNAME |
-                SYMOPT_LOAD_LINES);
+  SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME | SYMOPT_LOAD_LINES);
   if (!SymInitializeCurrentProc()) {
     // When it fails, we should not call debugbreak since it kills the current
     // process (prevents future tests from running or kills the browser
@@ -234,8 +237,7 @@
   static SymbolContext* GetInstance() {
     // We use a leaky singleton because code may call this during process
     // termination.
-    return
-      Singleton<SymbolContext, LeakySingletonTraits<SymbolContext> >::get();
+    return Singleton<SymbolContext, LeakySingletonTraits<SymbolContext>>::get();
   }
 
   SymbolContext(const SymbolContext&) = delete;
@@ -261,11 +263,9 @@
 
       // Code adapted from MSDN example:
       // http://msdn.microsoft.com/en-us/library/ms680578(VS.85).aspx
-      ULONG64 buffer[
-        (sizeof(SYMBOL_INFO) +
-          kMaxNameLength * sizeof(wchar_t) +
-          sizeof(ULONG64) - 1) /
-        sizeof(ULONG64)];
+      ULONG64 buffer[(sizeof(SYMBOL_INFO) + kMaxNameLength * sizeof(wchar_t) +
+                      sizeof(ULONG64) - 1) /
+                     sizeof(ULONG64)];
       memset(buffer, 0, sizeof(buffer));
 
       // Initialize symbol information retrieval structures.
@@ -273,8 +273,8 @@
       PSYMBOL_INFO symbol = reinterpret_cast<PSYMBOL_INFO>(&buffer[0]);
       symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
       symbol->MaxNameLen = kMaxNameLength - 1;
-      BOOL has_symbol = SymFromAddr(GetCurrentProcess(), frame,
-                                    &sym_displacement, symbol);
+      BOOL has_symbol =
+          SymFromAddr(GetCurrentProcess(), frame, &sym_displacement, symbol);
 
       // Attempt to retrieve line number information.
       DWORD line_displacement = 0;
@@ -302,9 +302,7 @@
  private:
   friend struct DefaultSingletonTraits<SymbolContext>;
 
-  SymbolContext() {
-    InitializeSymbols();
-  }
+  SymbolContext() { InitializeSymbols(); }
 
   Lock lock_;
 };
@@ -339,7 +337,7 @@
 void StackTrace::InitTrace(const CONTEXT* context_record) {
   if (ShouldSuppressOutput()) {
     CHECK_EQ(count_, 0U);
-    base::ranges::fill(trace_, nullptr);
+    std::ranges::fill(trace_, nullptr);
     return;
   }
 
@@ -384,7 +382,7 @@
     trace_[count_++] = reinterpret_cast<void*>(stack_frame.AddrPC.Offset);
   }
 
-  base::ranges::fill(span(trace_).last(trace_.size() - count_), nullptr);
+  std::ranges::fill(span(trace_).last(trace_.size() - count_), nullptr);
 }
 
 // static
diff --git a/tot/base/debug/task_trace.cc b/tot/base/debug/task_trace.cc
index 9bbac86..eda255e 100644
--- a/tot/base/debug/task_trace.cc
+++ b/tot/base/debug/task_trace.cc
@@ -9,7 +9,6 @@
 #include <sstream>
 
 #include "base/pending_task.h"
-#include "base/ranges/algorithm.h"
 #include "base/task/common/task_annotator.h"
 #include "build/build_config.h"
 
@@ -19,8 +18,7 @@
 #include "base/no_destructor.h"
 #endif  // BUILDFLAG(IS_ANDROID)
 
-namespace base {
-namespace debug {
+namespace base::debug {
 namespace {
 #if BUILDFLAG(IS_ANDROID)
 // Android sends stdout and stderr to /dev/null; logging should be done through
@@ -49,16 +47,19 @@
 
 TaskTrace::TaskTrace() {
   const PendingTask* current_task = TaskAnnotator::CurrentTaskForThread();
-  if (!current_task)
+  if (!current_task) {
     return;
+  }
   std::array<const void*, PendingTask::kTaskBacktraceLength + 1> task_trace;
   task_trace[0] = current_task->posted_from.program_counter();
-  ranges::copy(current_task->task_backtrace, task_trace.begin() + 1);
+  std::ranges::copy(current_task->task_backtrace, task_trace.begin() + 1);
   size_t length = 0;
-  while (length < task_trace.size() && task_trace[length])
+  while (length < task_trace.size() && task_trace[length]) {
     ++length;
-  if (length == 0)
+  }
+  if (length == 0) {
     return;
+  }
   stack_trace_.emplace(span(task_trace).first(length));
   trace_overflow_ = current_task->task_backtrace_overflow;
 }
@@ -97,9 +98,10 @@
     return count;
   }
   span<const void* const> current_addresses = stack_trace_->addresses();
-  ranges::copy_n(current_addresses.begin(),
-                 std::min(current_addresses.size(), addresses.size()),
-                 addresses.begin());
+  std::ranges::copy_n(current_addresses.begin(),
+                      static_cast<ptrdiff_t>(
+                          std::min(current_addresses.size(), addresses.size())),
+                      addresses.begin());
   return current_addresses.size();
 }
 
@@ -108,5 +110,4 @@
   return os;
 }
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/task_trace_unittest.cc b/tot/base/debug/task_trace_unittest.cc
index 57d6aa2..82d13f1 100644
--- a/tot/base/debug/task_trace_unittest.cc
+++ b/tot/base/debug/task_trace_unittest.cc
@@ -14,8 +14,7 @@
 #include "base/test/task_environment.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
-namespace base {
-namespace debug {
+namespace base::debug {
 
 TEST(TaskTraceTest, NoTask) {
   TaskTrace task_trace;
@@ -77,5 +76,4 @@
   ThreeTasksTest().Run();
 }
 
-}  // namespace debug
-}  // namespace base
+}  // namespace base::debug
diff --git a/tot/base/debug/test_elf_image_builder.cc b/tot/base/debug/test_elf_image_builder.cc
index 05b16d9..f9b8a93 100644
--- a/tot/base/debug/test_elf_image_builder.cc
+++ b/tot/base/debug/test_elf_image_builder.cc
@@ -131,10 +131,12 @@
   ImageMeasures measures;
 
   measures.phdrs_required = 1 + load_segments_.size();
-  if (!note_contents_.empty())
+  if (!note_contents_.empty()) {
     ++measures.phdrs_required;
-  if (soname_.has_value())
+  }
+  if (soname_.has_value()) {
     ++measures.phdrs_required;
+  }
 
   // The current offset into the image, where the next bytes are to be written.
   // Starts after the ELF header.
@@ -146,10 +148,12 @@
 
   // Add space for the notes.
   measures.note_start = offset;
-  if (!note_contents_.empty())
+  if (!note_contents_.empty()) {
     offset = bits::AlignUp(offset, kNoteAlign);
-  for (const std::vector<uint8_t>& contents : note_contents_)
+  }
+  for (const std::vector<uint8_t>& contents : note_contents_) {
     offset += contents.size();
+  }
   measures.note_size = offset - measures.note_start;
 
   // Add space for the load segments.
@@ -172,8 +176,9 @@
 
   // Add space for the string table.
   ++offset;  // The first string table byte holds a null character.
-  if (soname_)
+  if (soname_) {
     offset += soname_->size() + 1;
+  }
 
   measures.total_size = offset;
 
@@ -209,8 +214,9 @@
     size_t size = load_segment.size;
     // The first non PT_PHDR program header is expected to be a PT_LOAD and
     // encompass all the preceding headers.
-    if (i == 0)
+    if (i == 0) {
       size += loc - elf_start;
+    }
     loc = AppendHdr(CreatePhdr(PT_LOAD, load_segment.flags, kLoadAlign,
                                measures.load_segment_start[i],
                                GetVirtualAddressForOffset(
@@ -243,8 +249,9 @@
 
   // Add the load segments.
   for (auto it = load_segments_.begin(); it != load_segments_.end(); ++it) {
-    if (it != load_segments_.begin())
+    if (it != load_segments_.begin()) {
       loc = bits::AlignUp(loc, kLoadAlign);
+    }
     memset(loc, 0, it->size);
     loc += it->size;
   }
diff --git a/tot/base/environment.cc b/tot/base/environment.cc
index 77db49c..6ff5802 100644
--- a/tot/base/environment.cc
+++ b/tot/base/environment.cc
@@ -6,14 +6,16 @@
 
 #include <array>
 #include <string_view>
+#include <utility>
 
 #include "base/memory/ptr_util.h"
 #include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversions.h"
 #include "build/build_config.h"
 
 #if BUILDFLAG(IS_WIN)
 #include <windows.h>
+
+#include "base/strings/utf_string_conversions.h"
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
 #include <stdlib.h>
 #endif
@@ -24,9 +26,11 @@
 
 class EnvironmentImpl : public Environment {
  public:
-  bool GetVar(std::string_view variable_name, std::string* result) override {
-    if (GetVarImpl(variable_name, result))
-      return true;
+  std::optional<std::string> GetVar(std::string_view variable_name) override {
+    auto result = GetVarImpl(variable_name);
+    if (result.has_value()) {
+      return result;
+    }
 
     // Some commonly used variable names are uppercase while others
     // are lowercase, which is inconsistent. Let's try to be helpful
@@ -34,13 +38,14 @@
     // I.e. HTTP_PROXY may be http_proxy for some users/systems.
     char first_char = variable_name[0];
     std::string alternate_case_var;
-    if (IsAsciiLower(first_char))
+    if (IsAsciiLower(first_char)) {
       alternate_case_var = ToUpperASCII(variable_name);
-    else if (IsAsciiUpper(first_char))
+    } else if (IsAsciiUpper(first_char)) {
       alternate_case_var = ToLowerASCII(variable_name);
-    else
-      return false;
-    return GetVarImpl(alternate_case_var, result);
+    } else {
+      return std::nullopt;
+    }
+    return GetVarImpl(alternate_case_var);
   }
 
   bool SetVar(std::string_view variable_name,
@@ -53,31 +58,26 @@
   }
 
  private:
-  bool GetVarImpl(std::string_view variable_name, std::string* result) {
+  std::optional<std::string> GetVarImpl(std::string_view variable_name) {
 #if BUILDFLAG(IS_WIN)
     std::wstring wide_name = UTF8ToWide(variable_name);
-    if (!result) {
-      return ::GetEnvironmentVariable(wide_name.c_str(), nullptr, 0) != 0;
-    }
     // Documented to be the maximum environment variable size.
     std::array<wchar_t, 32767> value;
     DWORD value_length =
         ::GetEnvironmentVariable(wide_name.c_str(), value.data(), value.size());
     if (value_length == 0) {
-      return false;
+      return std::nullopt;
     }
+
     CHECK_LE(value_length, value.size() - 1)
         << "value should fit in the buffer (including the null terminator)";
-    WideToUTF8(value.data(), value_length, result);
-    return true;
+    return WideToUTF8(std::wstring_view(value.data(), value_length));
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
     const char* env_value = getenv(std::string(variable_name).c_str());
-    if (!env_value)
-      return false;
-    // Note that the variable may be defined but empty.
-    if (result)
-      *result = env_value;
-    return true;
+    if (!env_value) {
+      return std::nullopt;
+    }
+    return std::string(env_value);
 #endif
   }
 
@@ -123,8 +123,18 @@
   return std::make_unique<EnvironmentImpl>();
 }
 
+bool Environment::GetVar(std::string_view variable_name, std::string* result) {
+  std::optional<std::string> actual_result = GetVar(variable_name);
+  if (!actual_result.has_value()) {
+    return false;
+  }
+
+  *result = std::move(actual_result.value());
+  return true;
+}
+
 bool Environment::HasVar(std::string_view variable_name) {
-  return GetVar(variable_name, nullptr);
+  return GetVar(variable_name).has_value();
 }
 
 }  // namespace base
diff --git a/tot/base/environment.h b/tot/base/environment.h
index 14fdf2e..d911b33 100644
--- a/tot/base/environment.h
+++ b/tot/base/environment.h
@@ -7,6 +7,7 @@
 
 #include <map>
 #include <memory>
+#include <optional>
 #include <string>
 #include <string_view>
 
@@ -30,12 +31,18 @@
   // Returns the appropriate platform-specific instance.
   static std::unique_ptr<Environment> Create();
 
+  // Returns an environment variable's value.
+  // Returns std::nullopt if the key is unset.
+  // Note that the variable may be set to an empty string.
+  virtual std::optional<std::string> GetVar(std::string_view variable_name) = 0;
+
+  // DEPRECATED. Prefer GetVar() overload above.
   // Gets an environment variable's value and stores it in |result|.
   // Returns false if the key is unset.
-  virtual bool GetVar(std::string_view variable_name, std::string* result) = 0;
+  bool GetVar(std::string_view variable_name, std::string* result);
 
-  // Syntactic sugar for GetVar(variable_name, nullptr);
-  virtual bool HasVar(std::string_view variable_name);
+  // Syntactic sugar for GetVar(variable_name).has_value();
+  bool HasVar(std::string_view variable_name);
 
   // Returns true on success, otherwise returns false. This method should not
   // be called in a multi-threaded process.
diff --git a/tot/base/feature_list.cc b/tot/base/feature_list.cc
index a928fe6..12fb9f0 100644
--- a/tot/base/feature_list.cc
+++ b/tot/base/feature_list.cc
@@ -38,7 +38,6 @@
 #include "base/strings/string_util.h"
 #include "base/strings/stringprintf.h"
 #include "build/build_config.h"
-#include "build/chromeos_buildflags.h"
 
 namespace base {
 
@@ -353,8 +352,9 @@
 
     std::string_view feature_name;
     std::string_view trial_name;
-    if (!entry->GetFeatureAndTrialName(&feature_name, &trial_name))
+    if (!entry->GetFeatureAndTrialName(&feature_name, &trial_name)) {
       continue;
+    }
 
     FieldTrial* trial = FieldTrialList::Find(trial_name);
     RegisterOverride(feature_name, override_state, trial);
@@ -429,13 +429,15 @@
   for (const auto& override : overrides_) {
     Pickle pickle;
     pickle.WriteString(override.first);
-    if (override.second.field_trial)
+    if (override.second.field_trial) {
       pickle.WriteString(override.second.field_trial->trial_name());
+    }
 
     size_t total_size = sizeof(FeatureEntry) + pickle.size();
     FeatureEntry* entry = allocator->New<FeatureEntry>(total_size);
-    if (!entry)
+    if (!entry) {
       return;
+    }
 
     entry->override_state = override.second.overridden_state;
     entry->pickle_size = pickle.size();
@@ -516,18 +518,21 @@
   // First, check whether ":" is present. If true, feature parameters were
   // set for this feature.
   std::string feature_params;
-  if (!SplitIntoTwo(enable_feature, ":", &first, &feature_params))
+  if (!SplitIntoTwo(enable_feature, ":", &first, &feature_params)) {
     return false;
+  }
   // Then, check whether "." is present. If true, a group was specified for
   // this feature.
   std::string group;
-  if (!SplitIntoTwo(first, ".", &first, &group))
+  if (!SplitIntoTwo(first, ".", &first, &group)) {
     return false;
+  }
   // Finally, check whether "<" is present. If true, a study was specified for
   // this feature.
   std::string study;
-  if (!SplitIntoTwo(first, "<", &first, &study))
+  if (!SplitIntoTwo(first, "<", &first, &study)) {
     return false;
+  }
 
   std::string enable_feature_name(first);
   // If feature params were set but group and study weren't, associate the
@@ -571,8 +576,9 @@
   EarlyFeatureAccessTracker::GetInstance()->AssertNoAccess();
   bool instance_existed_before = false;
   if (g_feature_list_instance) {
-    if (g_feature_list_instance->initialized_from_command_line_)
+    if (g_feature_list_instance->initialized_from_command_line_) {
       return false;
+    }
 
     delete g_feature_list_instance;
     g_feature_list_instance = nullptr;
@@ -686,8 +692,8 @@
 // static
 void FeatureList::VisitFeaturesAndParams(FeatureVisitor& visitor,
                                          std::string_view filter_prefix) {
-  // If there is no feature list, there are no overrides. This should only happen
-  // in tests.
+  // If there is no feature list, there are no overrides. This should only
+  // happen in tests.
   // TODO(leszeks): Add a CHECK_IS_TEST() to verify the above.
   if (!g_feature_list_instance) {
     return;
@@ -745,8 +751,9 @@
   OverrideState overridden_state = GetOverrideState(feature);
 
   // If marked as OVERRIDE_USE_DEFAULT, simply return the default state below.
-  if (overridden_state != OVERRIDE_USE_DEFAULT)
+  if (overridden_state != OVERRIDE_USE_DEFAULT) {
     return overridden_state == OVERRIDE_ENABLE_FEATURE;
+  }
 
   return feature.default_state == FEATURE_ENABLED_BY_DEFAULT;
 }
@@ -756,8 +763,9 @@
   OverrideState overridden_state = GetOverrideState(feature);
 
   // If marked as OVERRIDE_USE_DEFAULT, fall through to returning empty.
-  if (overridden_state != OVERRIDE_USE_DEFAULT)
+  if (overridden_state != OVERRIDE_USE_DEFAULT) {
     return overridden_state == OVERRIDE_ENABLE_FEATURE;
+  }
 
   return std::nullopt;
 }
@@ -778,8 +786,9 @@
 
   auto unpacked = UnpackFeatureCache(current_cache_value);
 
-  if (unpacked.second == caching_context_)
+  if (unpacked.second == caching_context_) {
     return unpacked.first;
+  }
 
   OverrideState state = GetOverrideStateByFeatureName(feature.name);
   uint32_t new_cache_value = PackFeatureCache(state, caching_context_);
@@ -947,8 +956,9 @@
   // active one. If not, it likely indicates that this FeatureList has override
   // entries from a freed FieldTrial, which may be caused by an incorrect test
   // set up.
-  if (field_trial_list_)
+  if (field_trial_list_) {
     DCHECK_EQ(field_trial_list_, FieldTrialList::GetInstance());
+  }
 
   enable_overrides->clear();
   disable_overrides->clear();
@@ -974,10 +984,12 @@
         break;
     }
 
-    if (!target_list->empty())
+    if (!target_list->empty()) {
       target_list->push_back(',');
-    if (entry.second.overridden_state == OVERRIDE_USE_DEFAULT)
+    }
+    if (entry.second.overridden_state == OVERRIDE_USE_DEFAULT) {
       target_list->push_back('*');
+    }
     target_list->append(entry.first);
     if (entry.second.field_trial) {
       auto* const field_trial = entry.second.field_trial.get();
diff --git a/tot/base/feature_list.h b/tot/base/feature_list.h
index 7f1bcdf..85df4b7 100644
--- a/tot/base/feature_list.h
+++ b/tot/base/feature_list.h
@@ -95,14 +95,12 @@
 // Provides a definition for `feature_object_name` with `T`, `feature`, `name`
 // and `default_value`, with an internal parsed value cache, e.g.
 //
-//   BASE_FEATURE_PARAM(int, kMyFeatureParam, kMyFeature, "MyFeatureParam", 0);
+//   BASE_FEATURE_PARAM(int, kMyFeatureParam, kMyFeature, "my_feature_param",
+//                      0);
 //
 // `T` is a parameter type, one of bool, int, size_t, double, std::string, and
 // base::TimeDelta. Enum types are not supported for now.
 //
-// For now, ScopedFeatureList doesn't work to change the value dynamically when
-// the cache is used with this macro.
-//
 // It should *not* be defined in header files; do not use this macro in header
 // files.
 #define BASE_FEATURE_PARAM(T, feature_object_name, feature, name,       \
@@ -502,7 +500,7 @@
       std::string_view input);
 
   // Checks and parses the |enable_feature| (e.g.
-  // FeatureName<Study.Group:Param1/value1/) obtained by applying
+  // FeatureName<Study.Group:param1/value1/) obtained by applying
   // SplitFeatureListString() to the |enable_features| flag, and sets
   // |feature_name| to be the feature's name, |study_name| and |group_name| to
   // be the field trial name and its group name if the field trial is specified
diff --git a/tot/base/feature_list_unittest.cc b/tot/base/feature_list_unittest.cc
index 652911f..d086773 100644
--- a/tot/base/feature_list_unittest.cc
+++ b/tot/base/feature_list_unittest.cc
@@ -2,15 +2,12 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifdef UNSAFE_BUFFERS_BUILD
-// TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
-#pragma allow_unsafe_buffers
-#endif
-
 #include "base/feature_list.h"
 
 #include <stddef.h>
 
+#include <algorithm>
+#include <array>
 #include <ostream>
 #include <set>
 #include <string>
@@ -25,12 +22,10 @@
 #include "base/metrics/field_trial.h"
 #include "base/metrics/field_trial_param_associator.h"
 #include "base/metrics/persistent_memory_allocator.h"
-#include "base/ranges/algorithm.h"
 #include "base/strings/strcat.h"
 #include "base/strings/string_util.h"
 #include "base/strings/stringprintf.h"
 #include "base/test/scoped_feature_list.h"
-#include "build/chromeos_buildflags.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace base {
@@ -50,7 +45,7 @@
 std::string SortFeatureListString(const std::string& feature_list) {
   std::vector<std::string_view> features =
       FeatureList::SplitFeatureListString(feature_list);
-  ranges::sort(features);
+  std::ranges::sort(features);
   return JoinString(features, ",");
 }
 
@@ -76,12 +71,13 @@
 }
 
 TEST_F(FeatureListTest, InitFromCommandLine) {
-  struct {
+  struct TestCases {
     const char* enable_features;
     const char* disable_features;
     bool expected_feature_on_state;
     bool expected_feature_off_state;
-  } test_cases[] = {
+  };
+  auto test_cases = std::to_array<TestCases>({
       {"", "", true, false},
       {"OffByDefault", "", true, true},
       {"OffByDefault", "OnByDefault", false, true},
@@ -89,7 +85,7 @@
       {"", "OnByDefault,OffByDefault", false, false},
       // In the case an entry is both, disable takes precedence.
       {"OnByDefault", "OnByDefault,OffByDefault", false, false},
-  };
+  });
 
   for (size_t i = 0; i < std::size(test_cases); ++i) {
     const auto& test_case = test_cases[i];
@@ -181,19 +177,20 @@
 }
 
 TEST_F(FeatureListTest, FieldTrialOverrides) {
-  struct {
+  struct TestCases {
     FeatureList::OverrideState trial1_state;
     FeatureList::OverrideState trial2_state;
-  } test_cases[] = {
-      {FeatureList::OVERRIDE_DISABLE_FEATURE,
-       FeatureList::OVERRIDE_DISABLE_FEATURE},
-      {FeatureList::OVERRIDE_DISABLE_FEATURE,
-       FeatureList::OVERRIDE_ENABLE_FEATURE},
-      {FeatureList::OVERRIDE_ENABLE_FEATURE,
-       FeatureList::OVERRIDE_DISABLE_FEATURE},
-      {FeatureList::OVERRIDE_ENABLE_FEATURE,
-       FeatureList::OVERRIDE_ENABLE_FEATURE},
   };
+  auto test_cases = std::to_array<TestCases>({
+      {FeatureList::OVERRIDE_DISABLE_FEATURE,
+       FeatureList::OVERRIDE_DISABLE_FEATURE},
+      {FeatureList::OVERRIDE_DISABLE_FEATURE,
+       FeatureList::OVERRIDE_ENABLE_FEATURE},
+      {FeatureList::OVERRIDE_ENABLE_FEATURE,
+       FeatureList::OVERRIDE_DISABLE_FEATURE},
+      {FeatureList::OVERRIDE_ENABLE_FEATURE,
+       FeatureList::OVERRIDE_ENABLE_FEATURE},
+  });
 
   FieldTrial::ActiveGroup active_group;
   for (size_t i = 0; i < std::size(test_cases); ++i) {
@@ -397,19 +394,20 @@
 }
 
 TEST_F(FeatureListTest, AssociateReportingFieldTrial) {
-  struct {
+  struct TestCases {
     const char* enable_features;
     const char* disable_features;
     bool expected_enable_trial_created;
     bool expected_disable_trial_created;
-  } test_cases[] = {
+  };
+  auto test_cases = std::to_array<TestCases>({
       // If no enable/disable flags are specified, no trials should be created.
       {"", "", false, false},
       // Enabling the feature should result in the enable trial created.
       {kFeatureOffByDefaultName, "", true, false},
       // Disabling the feature should result in the disable trial created.
       {"", kFeatureOffByDefaultName, false, true},
-  };
+  });
 
   const char kTrialName[] = "ForcingTrial";
   const char kForcedOnGroupName[] = "ForcedOn";
@@ -554,9 +552,8 @@
   feature_list->RegisterExtraFeatureOverrides(std::move(overrides));
 
   FieldTrial* trial = FieldTrialList::CreateFieldTrial("Trial", "Group");
-  feature_list->RegisterFieldTrialOverride(kFeatureOffByDefaultName,
-                                           FeatureList::OVERRIDE_ENABLE_FEATURE,
-                                           trial);
+  feature_list->RegisterFieldTrialOverride(
+      kFeatureOffByDefaultName, FeatureList::OVERRIDE_ENABLE_FEATURE, trial);
 
   test::ScopedFeatureList scoped_feature_list;
   scoped_feature_list.InitWithFeatureList(std::move(feature_list));
@@ -666,8 +663,9 @@
   EXPECT_EQ(nullptr, FeatureList::GetInstance());
   EXPECT_FALSE(FeatureList::IsEnabled(kFeatureOffByDefault));
 
-  if (original_feature_list)
+  if (original_feature_list) {
     FeatureList::RestoreInstanceForTesting(std::move(original_feature_list));
+  }
 }
 
 TEST_F(FeatureListTest, StoreAndRetrieveFeaturesFromSharedMemory) {
@@ -801,12 +799,13 @@
 }
 
 TEST(FeatureListAccessorTest, InitFromCommandLine) {
-  struct {
+  struct TestCases {
     const char* enable_features;
     const char* disable_features;
     FeatureList::OverrideState expected_feature_on_state;
     FeatureList::OverrideState expected_feature_off_state;
-  } test_cases[] = {
+  };
+  auto test_cases = std::to_array<TestCases>({
       {"", "", FeatureList::OVERRIDE_USE_DEFAULT,
        FeatureList::OVERRIDE_USE_DEFAULT},
       {"OffByDefault", "", FeatureList::OVERRIDE_USE_DEFAULT,
@@ -821,7 +820,7 @@
       {"OnByDefault", "OnByDefault,OffByDefault",
        FeatureList::OVERRIDE_DISABLE_FEATURE,
        FeatureList::OVERRIDE_DISABLE_FEATURE},
-  };
+  });
 
   for (size_t i = 0; i < std::size(test_cases); ++i) {
     const auto& test_case = test_cases[i];
@@ -848,13 +847,14 @@
 }
 
 TEST(FeatureListAccessorTest, InitFromCommandLineWithFeatureParams) {
-  struct {
+  struct TestCases {
     const std::string enable_features;
     const std::map<std::string, std::string> expected_feature_params;
-  } test_cases[] = {
+  };
+  auto test_cases = std::to_array<TestCases>({
       {"Feature:x/100/y/test", {{"x", "100"}, {"y", "test"}}},
       {"Feature<Trial:asdf/ghjkl/y/123", {{"asdf", "ghjkl"}, {"y", "123"}}},
-  };
+  });
 
   // Clear global state so that repeated runs of this test don't flake.
   // When https://crrev.com/c/3694674 is submitted, we should be able to remove
@@ -993,8 +993,8 @@
   base::test::ScopedFeatureList initialized_feature_list;
 
   initialized_feature_list.InitFromCommandLine(
-      /*enabled_features=*/"TestFeature<foo.bar:k1/v1/k2/v2",
-      /*disabled_features=*/"");
+      /*enable_features=*/"TestFeature<foo.bar:k1/v1/k2/v2",
+      /*disable_features=*/"");
 
   TestFeatureVisitor visitor;
   base::FeatureList::VisitFeaturesAndParams(visitor);
diff --git a/tot/base/features.cc b/tot/base/features.cc
index 2002373..86f8ac7 100644
--- a/tot/base/features.cc
+++ b/tot/base/features.cc
@@ -4,9 +4,9 @@
 
 #include "base/features.h"
 
-#include "base/cpu_reduction_experiment.h"
 #include "base/task/sequence_manager/sequence_manager_impl.h"
 #include "base/threading/platform_thread.h"
+#include "build/blink_buildflags.h"
 #include "build/buildflag.h"
 
 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
@@ -16,8 +16,12 @@
 #if BUILDFLAG(IS_APPLE)
 #include "base/files/file.h"
 #include "base/message_loop/message_pump_apple.h"
-#include "base/message_loop/message_pump_kqueue.h"
 #include "base/synchronization/condition_variable.h"
+
+#if !BUILDFLAG(IS_IOS) || !BUILDFLAG(USE_BLINK)
+#include "base/message_loop/message_pump_kqueue.h"
+#endif
+
 #endif
 
 #if BUILDFLAG(IS_ANDROID)
@@ -26,39 +30,38 @@
 
 #if BUILDFLAG(IS_WIN)
 #include "base/task/sequence_manager/thread_controller_power_monitor.h"
-#include "base/threading/platform_thread_win.h"
 #endif
 
 namespace base::features {
 
 // Alphabetical:
 
-// Activate base::FeatureParamWithCache internal cache.
-// TODO(https://crbug.com/340824113): Remove the feature flag below.
+// Controls caching within BASE_FEATURE_PARAM(). This is feature-controlled
+// so that ScopedFeatureList can disable it to turn off caching.
 BASE_FEATURE(kFeatureParamWithCache,
              "FeatureParamWithCache",
              FEATURE_ENABLED_BY_DEFAULT);
 
-// Use the Rust JSON parser. Enabled everywhere except Android, where the switch
-// from using the C++ parser in-thread to using the Rust parser in a thread-pool
-// introduces too much latency.
+// Use the Rust JSON parser. Enabled everywhere.
 BASE_FEATURE(kUseRustJsonParser,
              "UseRustJsonParser",
-#if BUILDFLAG(IS_ANDROID)
-             FEATURE_DISABLED_BY_DEFAULT
-#else
-             FEATURE_ENABLED_BY_DEFAULT
-#endif  // BUILDFLAG(IS_ANDROID)
-);
+             FEATURE_ENABLED_BY_DEFAULT);
 
 // If true, use the Rust JSON parser in-thread; otherwise, it runs in a thread
 // pool.
-const base::FeatureParam<bool> kUseRustJsonParserInCurrentSequence{
-    &kUseRustJsonParser, "UseRustJsonParserInCurrentSequence", false};
+BASE_FEATURE_PARAM(bool,
+                   kUseRustJsonParserInCurrentSequence,
+                   &kUseRustJsonParser,
+                   "UseRustJsonParserInCurrentSequence",
+                   true);
 
 // Use non default low memory device threshold.
 // Value should be given via |LowMemoryDeviceThresholdMB|.
-#if BUILDFLAG(IS_IOS)
+#if BUILDFLAG(IS_ANDROID)
+// LINT.IfChange
+#define LOW_MEMORY_DEVICE_THRESHOLD_MB 1024
+// LINT.ThenChange(//base/android/java/src/org/chromium/base/SysUtils.java)
+#elif BUILDFLAG(IS_IOS)
 // For M99, 45% of devices have 2GB of RAM, and 55% have more.
 #define LOW_MEMORY_DEVICE_THRESHOLD_MB 1024
 #else
@@ -68,9 +71,11 @@
 BASE_FEATURE(kLowEndMemoryExperiment,
              "LowEndMemoryExperiment",
              FEATURE_DISABLED_BY_DEFAULT);
-const base::FeatureParam<int> kLowMemoryDeviceThresholdMB{
-    &kLowEndMemoryExperiment, "LowMemoryDeviceThresholdMB",
-    LOW_MEMORY_DEVICE_THRESHOLD_MB};
+BASE_FEATURE_PARAM(size_t,
+                   kLowMemoryDeviceThresholdMB,
+                   &kLowEndMemoryExperiment,
+                   "LowMemoryDeviceThresholdMB",
+                   LOW_MEMORY_DEVICE_THRESHOLD_MB);
 
 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
 // Force to enable LowEndDeviceMode partially on Android 3Gb devices.
@@ -117,7 +122,6 @@
 
 void Init(EmitThreadControllerProfilerMetadata
               emit_thread_controller_profiler_metadata) {
-  InitializeCpuReductionExperiment();
   sequence_manager::internal::SequenceManagerImpl::InitializeFeatures();
   sequence_manager::internal::ThreadController::InitializeFeatures(
       emit_thread_controller_profiler_metadata);
@@ -131,12 +135,16 @@
 #endif
 
 #if BUILDFLAG(IS_APPLE)
-  ConditionVariable::InitializeFeatures();
   File::InitializeFeatures();
   MessagePumpCFRunLoopBase::InitializeFeatures();
+
+// Kqueue is not used for ios blink.
+#if !BUILDFLAG(IS_IOS) || !BUILDFLAG(USE_BLINK)
   MessagePumpKqueue::InitializeFeatures();
 #endif
 
+#endif
+
 #if BUILDFLAG(IS_ANDROID)
   android::InputHintChecker::InitializeFeatures();
 #endif
@@ -144,7 +152,6 @@
 #if BUILDFLAG(IS_WIN)
   sequence_manager::internal::ThreadControllerPowerMonitor::
       InitializeFeatures();
-  InitializePlatformThreadFeatures();
 #endif
 }
 
diff --git a/tot/base/features.h b/tot/base/features.h
index c2bf772..7b68c70 100644
--- a/tot/base/features.h
+++ b/tot/base/features.h
@@ -19,12 +19,12 @@
 
 BASE_EXPORT BASE_DECLARE_FEATURE(kUseRustJsonParser);
 
-BASE_EXPORT extern const base::FeatureParam<bool>
-    kUseRustJsonParserInCurrentSequence;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(bool,
+                                       kUseRustJsonParserInCurrentSequence);
 
 BASE_EXPORT BASE_DECLARE_FEATURE(kLowEndMemoryExperiment);
 
-BASE_EXPORT extern const base::FeatureParam<int> kLowMemoryDeviceThresholdMB;
+BASE_EXPORT BASE_DECLARE_FEATURE_PARAM(size_t, kLowMemoryDeviceThresholdMB);
 
 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
 BASE_EXPORT BASE_DECLARE_FEATURE(kPartialLowEndModeOn3GbDevices);
diff --git a/tot/base/file_descriptor_posix.cc b/tot/base/file_descriptor_posix.cc
index 30c83c4..991a84c 100644
--- a/tot/base/file_descriptor_posix.cc
+++ b/tot/base/file_descriptor_posix.cc
@@ -31,4 +31,4 @@
   return other.fd < fd;
 }
 
-}  // namespace base
\ No newline at end of file
+}  // namespace base
diff --git a/tot/base/file_descriptor_store.cc b/tot/base/file_descriptor_store.cc
index 032ebfc..6fda246 100644
--- a/tot/base/file_descriptor_store.cc
+++ b/tot/base/file_descriptor_store.cc
@@ -38,8 +38,9 @@
     const std::string& key,
     base::MemoryMappedFile::Region* region) {
   base::ScopedFD fd = MaybeTakeFD(key, region);
-  if (!fd.is_valid())
+  if (!fd.is_valid()) {
     DLOG(FATAL) << "Unknown global descriptor: " << key;
+  }
   return fd;
 }
 
@@ -47,8 +48,9 @@
     const std::string& key,
     base::MemoryMappedFile::Region* region) {
   auto iter = descriptors_.find(key);
-  if (iter == descriptors_.end())
+  if (iter == descriptors_.end()) {
     return base::ScopedFD();
+  }
   *region = iter->second.region;
   base::ScopedFD result = std::move(iter->second.fd);
   descriptors_.erase(iter);
diff --git a/tot/base/file_version_info.h b/tot/base/file_version_info.h
index ecea99f..8893012 100644
--- a/tot/base/file_version_info.h
+++ b/tot/base/file_version_info.h
@@ -8,8 +8,8 @@
 #include <memory>
 #include <string>
 
-#include "build/build_config.h"
 #include "base/base_export.h"
+#include "build/build_config.h"
 
 #if BUILDFLAG(IS_WIN)
 #include <windows.h>
diff --git a/tot/base/file_version_info_apple.h b/tot/base/file_version_info_apple.h
index 7b3041a..a1d59c22 100644
--- a/tot/base/file_version_info_apple.h
+++ b/tot/base/file_version_info_apple.h
@@ -5,12 +5,12 @@
 #ifndef BASE_FILE_VERSION_INFO_APPLE_H_
 #define BASE_FILE_VERSION_INFO_APPLE_H_
 
-#include "base/file_version_info.h"
-
 #include <CoreFoundation/CoreFoundation.h>
 
 #include <string>
 
+#include "base/file_version_info.h"
+
 @class NSBundle;
 
 class FileVersionInfoApple : public FileVersionInfo {
diff --git a/tot/base/file_version_info_win.cc b/tot/base/file_version_info_win.cc
index 6813ec4..8a2b942 100644
--- a/tot/base/file_version_info_win.cc
+++ b/tot/base/file_version_info_win.cc
@@ -30,8 +30,9 @@
   static constexpr wchar_t kTranslation[] = L"\\VarFileInfo\\Translation";
   LPVOID translate = nullptr;
   UINT dummy_size;
-  if (::VerQueryValue(data, kTranslation, &translate, &dummy_size))
+  if (::VerQueryValue(data, kTranslation, &translate, &dummy_size)) {
     return static_cast<LanguageAndCodePage*>(translate);
+  }
   return nullptr;
 }
 
@@ -54,12 +55,14 @@
   size_t version_info_length;
   const bool has_version_resource = base::win::GetResourceFromModule(
       module, VS_VERSION_INFO, RT_VERSION, &data, &version_info_length);
-  if (!has_version_resource)
+  if (!has_version_resource) {
     return nullptr;
+  }
 
   const LanguageAndCodePage* translate = GetTranslate(data);
-  if (!translate)
+  if (!translate) {
     return nullptr;
+  }
 
   return base::WrapUnique(
       new FileVersionInfoWin(data, translate->language, translate->code_page));
@@ -80,17 +83,20 @@
   DWORD dummy;
   const wchar_t* path = file_path.value().c_str();
   const DWORD length = ::GetFileVersionInfoSize(path, &dummy);
-  if (length == 0)
+  if (length == 0) {
     return nullptr;
+  }
 
   std::vector<uint8_t> data(length, 0);
 
-  if (!::GetFileVersionInfo(path, dummy, length, data.data()))
+  if (!::GetFileVersionInfo(path, dummy, length, data.data())) {
     return nullptr;
+  }
 
   const LanguageAndCodePage* translate = GetTranslate(data.data());
-  if (!translate)
+  if (!translate) {
     return nullptr;
+  }
 
   return base::WrapUnique(new FileVersionInfoWin(
       std::move(data), translate->language, translate->code_page));
diff --git a/tot/base/files/dir_reader_fallback.h b/tot/base/files/dir_reader_fallback.h
index d4f90a6..d565a90 100644
--- a/tot/base/files/dir_reader_fallback.h
+++ b/tot/base/files/dir_reader_fallback.h
@@ -21,7 +21,7 @@
   bool Next() { return false; }
 
   // Return the name of the current directory entry.
-  const char* name() { return nullptr;}
+  const char* name() { return nullptr; }
 
   // Return the file descriptor which is being used.
   int fd() const { return -1; }
diff --git a/tot/base/files/dir_reader_linux.h b/tot/base/files/dir_reader_linux.h
index 2bd9c45..a279721 100644
--- a/tot/base/files/dir_reader_linux.h
+++ b/tot/base/files/dir_reader_linux.h
@@ -26,11 +26,11 @@
 namespace base {
 
 struct linux_dirent {
-  uint64_t        d_ino;
-  int64_t         d_off;
-  unsigned short  d_reclen;
-  unsigned char   d_type;
-  char            d_name[0];
+  uint64_t d_ino;
+  int64_t d_off;
+  unsigned short d_reclen;
+  unsigned char d_type;
+  char d_name[0];
 };
 
 class DirReaderLinux {
@@ -47,14 +47,13 @@
 
   ~DirReaderLinux() {
     if (fd_ >= 0) {
-      if (IGNORE_EINTR(close(fd_)))
+      if (IGNORE_EINTR(close(fd_))) {
         RAW_LOG(ERROR, "Failed to close directory handle");
+      }
     }
   }
 
-  bool IsValid() const {
-    return fd_ >= 0;
-  }
+  bool IsValid() const { return fd_ >= 0; }
 
   // Move to the next entry returning false if the iteration is complete.
   bool Next() {
@@ -63,12 +62,14 @@
       offset_ += dirent->d_reclen;
     }
 
-    if (offset_ != size_)
+    if (offset_ != size_) {
       return true;
+    }
 
     const long r = syscall(__NR_getdents64, fd_, buf_, sizeof(buf_));
-    if (r == 0)
+    if (r == 0) {
       return false;
+    }
     if (r < 0) {
       if (errno != ENOENT) {
         DPLOG(FATAL) << "getdents64 failed";
@@ -81,21 +82,18 @@
   }
 
   const char* name() const {
-    if (!size_)
+    if (!size_) {
       return nullptr;
+    }
 
     const linux_dirent* dirent =
         reinterpret_cast<const linux_dirent*>(&buf_[offset_]);
     return dirent->d_name;
   }
 
-  int fd() const {
-    return fd_;
-  }
+  int fd() const { return fd_; }
 
-  static bool IsFallback() {
-    return false;
-  }
+  static bool IsFallback() { return false; }
 
  private:
   const int fd_;
diff --git a/tot/base/files/dir_reader_posix_unittest.cc b/tot/base/files/dir_reader_posix_unittest.cc
index 1f8903b..ef00acf 100644
--- a/tot/base/files/dir_reader_posix_unittest.cc
+++ b/tot/base/files/dir_reader_posix_unittest.cc
@@ -2,6 +2,11 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#ifdef UNSAFE_BUFFERS_BUILD
+// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
+#pragma allow_unsafe_libc_calls
+#endif
+
 #include "base/files/dir_reader_posix.h"
 
 #include <fcntl.h>
@@ -25,8 +30,9 @@
 TEST(DirReaderPosixUnittest, Read) {
   static const unsigned kNumFiles = 100;
 
-  if (DirReaderPosix::IsFallback())
+  if (DirReaderPosix::IsFallback()) {
     return;
+  }
 
   base::ScopedTempDir temp_dir;
   ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
@@ -51,12 +57,13 @@
   DirReaderPosix reader(dir);
   EXPECT_TRUE(reader.IsValid());
 
-  if (!reader.IsValid())
+  if (!reader.IsValid()) {
     return;
+  }
 
   bool seen_dot = false, seen_dotdot = false;
 
-  for (; reader.Next(); ) {
+  for (; reader.Next();) {
     if (strcmp(reader.name(), ".") == 0) {
       seen_dot = true;
       continue;
@@ -68,7 +75,7 @@
 
     SCOPED_TRACE(testing::Message() << "reader.name(): " << reader.name());
 
-    char *endptr;
+    char* endptr;
     const unsigned long value = strtoul(reader.name(), &endptr, 10);
 
     EXPECT_FALSE(*endptr);
diff --git a/tot/base/files/drive_info.h b/tot/base/files/drive_info.h
index 89643b4..75f4661 100644
--- a/tot/base/files/drive_info.h
+++ b/tot/base/files/drive_info.h
@@ -5,6 +5,9 @@
 #ifndef BASE_FILES_DRIVE_INFO_H_
 #define BASE_FILES_DRIVE_INFO_H_
 
+#include <stdint.h>
+#include <time.h>
+
 #include <optional>
 #include <string>
 #include <string_view>
diff --git a/tot/base/files/drive_info_posix.cc b/tot/base/files/drive_info_posix.cc
index 63c989e..17aaa60 100644
--- a/tot/base/files/drive_info_posix.cc
+++ b/tot/base/files/drive_info_posix.cc
@@ -12,6 +12,7 @@
 #include "base/files/file_util.h"
 #include "base/files/scoped_file.h"
 #include "base/strings/string_number_conversions.h"
+#include "base/strings/string_util.h"
 #include "base/strings/stringprintf.h"
 #include "build/build_config.h"
 
@@ -30,6 +31,7 @@
   constexpr char kRotationalFormat[] =
       "/sys/dev/block/%lu:%lu/queue/rotational";
   constexpr char kRemovableFormat[] = "/sys/dev/block/%lu:%lu/removable";
+  constexpr char kDeviceFormat[] = "/sys/dev/block/%lu:%lu";
   constexpr char kSizeFormat[] = "/sys/dev/block/%lu:%lu/size";
   File file(file_path, File::FLAG_OPEN | File::FLAG_READ);
   if (!file.IsValid()) {
@@ -49,22 +51,48 @@
   std::string size_path = StringPrintf(kSizeFormat, MAJOR(path_stat.st_dev),
                                        MINOR(path_stat.st_dev));
 
+  // Depending on the device, partitions may not expose the desired info. In the
+  // case when reading the device returned by Fstat() fails in both the
+  // rotational and removable attributes, attempt to crawl up one directory in
+  // the sysfs absolute path for the partition which was queried, which should
+  // give the device which contains this partition, and which should contain the
+  // desired info in the case where that info is not exposed for the partition
+  // itself.
   std::string rotates;
-  if (ReadFileToString(base::FilePath(rotational_path), &rotates) &&
-      rotates.length() == 1 && (rotates[0] == '0' || rotates[0] == '1')) {
-    drive_info.has_seek_penalty = rotates[0] == '1';
+  std::string removable;
+  bool rotates_read = ReadFileToString(FilePath(rotational_path), &rotates);
+  bool removable_read = ReadFileToString(FilePath(removable_path), &removable);
+
+  if (!rotates_read && !removable_read) {
+    std::string device_path = StringPrintf(
+        kDeviceFormat, MAJOR(path_stat.st_dev), MINOR(path_stat.st_dev));
+    FilePath parent_device_path =
+        MakeAbsoluteFilePath(FilePath(device_path)).DirName();
+    rotates_read = ReadFileToString(
+        parent_device_path.Append("queue/rotational"), &rotates);
+    removable_read =
+        ReadFileToString(parent_device_path.Append("removable"), &removable);
   }
 
-  std::string removable;
-  if (ReadFileToString(base::FilePath(removable_path), &removable) &&
-      removable.length() == 1 && (removable[0] == '0' || removable[0] == '1')) {
-    drive_info.is_removable = removable[0] == '1';
+  if (rotates_read) {
+    rotates = TrimString(rotates, "\n", TrimPositions::TRIM_TRAILING);
+    if (rotates.length() == 1 && (rotates[0] == '0' || rotates[0] == '1')) {
+      drive_info.has_seek_penalty = rotates[0] == '1';
+    }
+  }
+  if (removable_read) {
+    removable = TrimString(removable, "\n", TrimPositions::TRIM_TRAILING);
+    if (removable.length() == 1 &&
+        (removable[0] == '0' || removable[0] == '1')) {
+      drive_info.is_removable = removable[0] == '1';
+    }
   }
 
   std::string size;
   uint64_t bytes;
   if (ReadFileToString(FilePath(size_path), &size) &&
-      StringToUint64(size, &bytes)) {
+      StringToUint64(TrimString(size, "\n", TrimPositions::TRIM_TRAILING),
+                     &bytes)) {
     drive_info.size_bytes = bytes;
   }
 
diff --git a/tot/base/files/file.cc b/tot/base/files/file.cc
index ce9a664..3847acd 100644
--- a/tot/base/files/file.cc
+++ b/tot/base/files/file.cc
@@ -47,9 +47,7 @@
 }
 
 File::File(PlatformFile platform_file, bool async)
-    : file_(platform_file),
-      error_details_(FILE_OK),
-      async_(async) {
+    : file_(platform_file), error_details_(FILE_OK), async_(async) {
 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
   DCHECK_GE(platform_file, -1);
 #endif
diff --git a/tot/base/files/file.h b/tot/base/files/file.h
index 4192094..e666c56 100644
--- a/tot/base/files/file.h
+++ b/tot/base/files/file.h
@@ -109,11 +109,7 @@
   };
 
   // This explicit mapping matches both FILE_ on Windows and SEEK_ on Linux.
-  enum Whence {
-    FROM_BEGIN   = 0,
-    FROM_CURRENT = 1,
-    FROM_END     = 2
-  };
+  enum Whence { FROM_BEGIN = 0, FROM_CURRENT = 1, FROM_END = 2 };
 
   // Used to hold information about a given file.
   // If you add more fields to this structure (platform-specific fields are OK),
diff --git a/tot/base/files/file_descriptor_watcher_posix.cc b/tot/base/files/file_descriptor_watcher_posix.cc
index fee08f8..4a37caf 100644
--- a/tot/base/files/file_descriptor_watcher_posix.cc
+++ b/tot/base/files/file_descriptor_watcher_posix.cc
@@ -182,8 +182,9 @@
 
   if (io_thread_task_runner_->BelongsToCurrentThread()) {
     // If the MessagePumpForIO and the Controller live on the same thread.
-    if (watcher_)
+    if (watcher_) {
       delete watcher_;
+    }
   } else {
     // Synchronously wait until |watcher_| is deleted on the MessagePumpForIO
     // thread. This ensures that the file descriptor is never accessed after
@@ -244,8 +245,9 @@
   callback_copy.Run();
 
   // If |this| wasn't deleted, re-enable the watch.
-  if (weak_this)
+  if (weak_this) {
     StartWatching();
+  }
 }
 
 FileDescriptorWatcher::FileDescriptorWatcher(
diff --git a/tot/base/files/file_enumerator_posix.cc b/tot/base/files/file_enumerator_posix.cc
index 1a22b15..76a84bf 100644
--- a/tot/base/files/file_enumerator_posix.cc
+++ b/tot/base/files/file_enumerator_posix.cc
@@ -2,6 +2,11 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#ifdef UNSAFE_BUFFERS_BUILD
+// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
+#pragma allow_unsafe_libc_calls
+#endif
+
 #include "base/files/file_enumerator.h"
 
 #include <dirent.h>
@@ -180,8 +185,9 @@
 
   // While we've exhausted the entries in the current directory, do the next
   while (current_directory_entry_ >= directory_entries_.size()) {
-    if (pending_paths_.empty())
+    if (pending_paths_.empty()) {
       return FilePath();
+    }
 
     root_path_ = pending_paths_.top();
     root_path_ = root_path_.StripTrailingSeparators();
@@ -212,8 +218,9 @@
 
     DIR* dir = opendir(root_path_.value().c_str());
     if (!dir) {
-      if (errno == 0 || error_policy_ == ErrorPolicy::IGNORE_ERRORS)
+      if (errno == 0 || error_policy_ == ErrorPolicy::IGNORE_ERRORS) {
         continue;
+      }
       error_ = File::OSErrorToFileError(errno);
       return FilePath();
     }
@@ -245,23 +252,26 @@
       FileInfo info;
       info.filename_ = FilePath(dent->d_name);
 
-      if (ShouldSkip(info.filename_))
+      if (ShouldSkip(info.filename_)) {
         continue;
+      }
 
       const bool is_pattern_matched = IsPatternMatched(info.filename_);
 
       // MATCH_ONLY policy enumerates files and directories which matching
       // pattern only. So we can early skip further checks.
       if (folder_search_policy_ == FolderSearchPolicy::MATCH_ONLY &&
-          !is_pattern_matched)
+          !is_pattern_matched) {
         continue;
+      }
 
       // Do not call OS stat/lstat if there is no sense to do it. If pattern is
       // not matched (file will not appear in results) and search is not
       // recursive (possible directory will not be added to pending paths) -
       // there is no sense to obtain item below.
-      if (!recursive_ && !is_pattern_matched)
+      if (!recursive_ && !is_pattern_matched) {
         continue;
+      }
 
       // If the caller only wants the names of files and directories, then
       // continue without populating `info` further.
@@ -285,8 +295,9 @@
         pending_paths_.push(std::move(full_path));
       }
 
-      if (is_pattern_matched && IsTypeMatched(is_dir))
+      if (is_pattern_matched && IsTypeMatched(is_dir)) {
         directory_entries_.push_back(std::move(info));
+      }
     }
     int readdir_errno = errno;
     closedir(dir);
@@ -297,8 +308,9 @@
 
     // MATCH_ONLY policy enumerates files in matched subfolders by "*" pattern.
     // ALL policy enumerates files in all subfolders by origin pattern.
-    if (folder_search_policy_ == FolderSearchPolicy::MATCH_ONLY)
+    if (folder_search_policy_ == FolderSearchPolicy::MATCH_ONLY) {
       pattern_.clear();
+    }
   }
 
 #if BUILDFLAG(IS_ANDROID)
diff --git a/tot/base/files/file_enumerator_unittest.cc b/tot/base/files/file_enumerator_unittest.cc
index a0300ea..ec39021 100644
--- a/tot/base/files/file_enumerator_unittest.cc
+++ b/tot/base/files/file_enumerator_unittest.cc
@@ -97,8 +97,9 @@
   FileEnumerator enumerator(root_path, recursive, file_type, pattern,
                             folder_search_policy,
                             FileEnumerator::ErrorPolicy::IGNORE_ERRORS);
-  for (auto file = enumerator.Next(); !file.empty(); file = enumerator.Next())
+  for (auto file = enumerator.Next(); !file.empty(); file = enumerator.Next()) {
     rv.emplace_back(std::move(file));
+  }
   return rv;
 }
 
diff --git a/tot/base/files/file_enumerator_win.cc b/tot/base/files/file_enumerator_win.cc
index 614548c..076f48f 100644
--- a/tot/base/files/file_enumerator_win.cc
+++ b/tot/base/files/file_enumerator_win.cc
@@ -120,8 +120,9 @@
 }
 
 FileEnumerator::~FileEnumerator() {
-  if (find_handle_ != INVALID_HANDLE_VALUE)
+  if (find_handle_ != INVALID_HANDLE_VALUE) {
     FindClose(find_handle_);
+  }
 }
 
 FileEnumerator::FileInfo FileEnumerator::GetInfo() const {
@@ -183,8 +184,9 @@
     }
 
     const FilePath filename(find_data().cFileName);
-    if (ShouldSkip(filename))
+    if (ShouldSkip(filename)) {
       continue;
+    }
 
     const bool is_dir =
         (find_data().dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
@@ -197,12 +199,14 @@
       // directory. However, don't do recursion through reparse points or we
       // may end up with an infinite cycle.
       DWORD attributes = GetFileAttributes(abs_path.value().c_str());
-      if (!(attributes & FILE_ATTRIBUTE_REPARSE_POINT))
+      if (!(attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
         pending_paths_.push(abs_path);
+      }
     }
 
-    if (IsTypeMatched(is_dir) && IsPatternMatched(filename))
+    if (IsTypeMatched(is_dir) && IsPatternMatched(filename)) {
       return abs_path;
+    }
   }
   return FilePath();
 }
diff --git a/tot/base/files/file_locking_unittest.cc b/tot/base/files/file_locking_unittest.cc
index bdd4934..88cc5ab 100644
--- a/tot/base/files/file_locking_unittest.cc
+++ b/tot/base/files/file_locking_unittest.cc
@@ -63,8 +63,9 @@
                              const base::TimeDelta& timeout) {
   const base::Time finish_by = base::Time::Now() + timeout;
   while (!CheckEvent(signal_dir, signal_file)) {
-    if (base::Time::Now() > finish_by)
+    if (base::Time::Now() > finish_by) {
       return false;
+    }
     base::PlatformThread::Sleep(base::Milliseconds(10));
   }
   return true;
diff --git a/tot/base/files/file_path.cc b/tot/base/files/file_path.cc
index 33d0948..4b91b56 100644
--- a/tot/base/files/file_path.cc
+++ b/tot/base/files/file_path.cc
@@ -18,7 +18,6 @@
 #include "base/files/safe_base_name.h"
 #include "base/numerics/safe_conversions.h"
 #include "base/pickle.h"
-#include "base/ranges/algorithm.h"
 #include "base/strings/strcat.h"
 #include "base/strings/string_util.h"
 #include "base/strings/sys_string_conversions.h"
@@ -42,7 +41,7 @@
 namespace base {
 
 using StringType = FilePath::StringType;
-using StringPieceType = FilePath::StringPieceType;
+using StringViewType = FilePath::StringViewType;
 
 namespace {
 
@@ -57,7 +56,7 @@
 // otherwise returns npos.  This can only be true on Windows, when a pathname
 // begins with a letter followed by a colon.  On other platforms, this always
 // returns npos.
-StringPieceType::size_type FindDriveLetter(StringPieceType path) {
+StringViewType::size_type FindDriveLetter(StringViewType path) {
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
   // This is dependent on an ASCII-based character set, but that's a
   // reasonable assumption.  iswalpha can be too inclusive here.
@@ -71,36 +70,38 @@
 }
 
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-bool EqualDriveLetterCaseInsensitive(StringPieceType a, StringPieceType b) {
+bool EqualDriveLetterCaseInsensitive(StringViewType a, StringViewType b) {
   size_t a_letter_pos = FindDriveLetter(a);
   size_t b_letter_pos = FindDriveLetter(b);
 
-  if (a_letter_pos == StringType::npos || b_letter_pos == StringType::npos)
+  if (a_letter_pos == StringType::npos || b_letter_pos == StringType::npos) {
     return a == b;
+  }
 
-  StringPieceType a_letter(a.substr(0, a_letter_pos + 1));
-  StringPieceType b_letter(b.substr(0, b_letter_pos + 1));
-  if (!StartsWith(a_letter, b_letter, CompareCase::INSENSITIVE_ASCII))
+  StringViewType a_letter(a.substr(0, a_letter_pos + 1));
+  StringViewType b_letter(b.substr(0, b_letter_pos + 1));
+  if (!StartsWith(a_letter, b_letter, CompareCase::INSENSITIVE_ASCII)) {
     return false;
+  }
 
-  StringPieceType a_rest(a.substr(a_letter_pos + 1));
-  StringPieceType b_rest(b.substr(b_letter_pos + 1));
+  StringViewType a_rest(a.substr(a_letter_pos + 1));
+  StringViewType b_rest(b.substr(b_letter_pos + 1));
   return a_rest == b_rest;
 }
 #endif  // defined(FILE_PATH_USES_DRIVE_LETTERS)
 
-bool IsPathAbsolute(StringPieceType path) {
+bool IsPathAbsolute(StringViewType path) {
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
   StringType::size_type letter = FindDriveLetter(path);
   if (letter != StringType::npos) {
     // Look for a separator right after the drive specification.
     return path.length() > letter + 1 &&
-        FilePath::IsSeparator(path[letter + 1]);
+           FilePath::IsSeparator(path[letter + 1]);
   }
   // Look for a pair of leading separators.
-  return path.length() > 1 &&
-      FilePath::IsSeparator(path[0]) && FilePath::IsSeparator(path[1]);
-#else  // FILE_PATH_USES_DRIVE_LETTERS
+  return path.length() > 1 && FilePath::IsSeparator(path[0]) &&
+         FilePath::IsSeparator(path[1]);
+#else   // FILE_PATH_USES_DRIVE_LETTERS
   // Look for a separator in the first position.
   return path.length() > 0 && FilePath::IsSeparator(path[0]);
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
@@ -108,8 +109,9 @@
 
 bool AreAllSeparators(const StringType& input) {
   for (auto it : input) {
-    if (!FilePath::IsSeparator(it))
+    if (!FilePath::IsSeparator(it)) {
       return false;
+    }
   }
 
   return true;
@@ -120,8 +122,10 @@
 // Returns npos if it can't find an extension.
 StringType::size_type FinalExtensionSeparatorPosition(const StringType& path) {
   // Special case "." and ".."
-  if (path == FilePath::kCurrentDirectory || path == FilePath::kParentDirectory)
+  if (path == FilePath::kCurrentDirectory ||
+      path == FilePath::kParentDirectory) {
     return StringType::npos;
+  }
 
   return path.rfind(FilePath::kExtensionSeparator);
 }
@@ -134,14 +138,14 @@
   const StringType::size_type last_dot = FinalExtensionSeparatorPosition(path);
 
   // No extension, or the extension is the whole filename.
-  if (last_dot == StringType::npos || last_dot == 0U)
+  if (last_dot == StringType::npos || last_dot == 0U) {
     return last_dot;
+  }
 
   const StringType::size_type penultimate_dot =
       path.rfind(FilePath::kExtensionSeparator, last_dot - 1);
-  const StringType::size_type last_separator =
-      path.find_last_of(FilePath::kSeparators, last_dot - 1,
-                        FilePath::kSeparatorsLength - 1);
+  const StringType::size_type last_separator = path.find_last_of(
+      FilePath::kSeparators, last_dot - 1, FilePath::kSeparatorsLength - 1);
 
   if (penultimate_dot == StringType::npos ||
       (last_separator != StringType::npos &&
@@ -151,8 +155,9 @@
 
   for (auto* i : kCommonDoubleExtensions) {
     StringType extension(path, penultimate_dot + 1);
-    if (EqualsCaseInsensitiveASCII(extension, i))
+    if (EqualsCaseInsensitiveASCII(extension, i)) {
       return penultimate_dot;
+    }
   }
 
   StringType extension(path, last_dot + 1);
@@ -186,10 +191,11 @@
 FilePath::FilePath(const FilePath& that) = default;
 FilePath::FilePath(FilePath&& that) noexcept = default;
 
-FilePath::FilePath(StringPieceType path) : path_(path) {
+FilePath::FilePath(StringViewType path) : path_(path) {
   StringType::size_type nul_pos = path_.find(kStringTerminator);
-  if (nul_pos != StringType::npos)
+  if (nul_pos != StringType::npos) {
     path_.erase(nul_pos, StringType::npos);
+  }
 }
 
 FilePath::~FilePath() = default;
@@ -201,19 +207,11 @@
 bool FilePath::operator==(const FilePath& that) const {
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
   return EqualDriveLetterCaseInsensitive(this->path_, that.path_);
-#else  // defined(FILE_PATH_USES_DRIVE_LETTERS)
+#else   // defined(FILE_PATH_USES_DRIVE_LETTERS)
   return path_ == that.path_;
 #endif  // defined(FILE_PATH_USES_DRIVE_LETTERS)
 }
 
-bool FilePath::operator!=(const FilePath& that) const {
-#if defined(FILE_PATH_USES_DRIVE_LETTERS)
-  return !EqualDriveLetterCaseInsensitive(this->path_, that.path_);
-#else  // defined(FILE_PATH_USES_DRIVE_LETTERS)
-  return path_ != that.path_;
-#endif  // defined(FILE_PATH_USES_DRIVE_LETTERS)
-}
-
 std::ostream& operator<<(std::ostream& out, const FilePath& file_path) {
   return out << file_path.value();
 }
@@ -231,8 +229,9 @@
 
 std::vector<FilePath::StringType> FilePath::GetComponents() const {
   std::vector<StringType> ret_val;
-  if (value().empty())
+  if (value().empty()) {
     return ret_val;
+  }
 
   FilePath current = *this;
   FilePath base;
@@ -240,23 +239,26 @@
   // Capture path components.
   while (current != current.DirName()) {
     base = current.BaseName();
-    if (!AreAllSeparators(base.value()))
+    if (!AreAllSeparators(base.value())) {
       ret_val.push_back(base.value());
+    }
     current = current.DirName();
   }
 
   // Capture root, if any.
   base = current.BaseName();
-  if (!base.value().empty() && base.value() != kCurrentDirectory)
+  if (!base.value().empty() && base.value() != kCurrentDirectory) {
     ret_val.push_back(current.BaseName().value());
+  }
 
   // Capture drive letter, if any.
   FilePath dir = current.DirName();
   StringType::size_type letter = FindDriveLetter(dir.value());
-  if (letter != StringType::npos)
+  if (letter != StringType::npos) {
     ret_val.emplace_back(dir.value(), 0, letter + 1);
+  }
 
-  ranges::reverse(ret_val);
+  std::ranges::reverse(ret_val);
   return ret_val;
 }
 
@@ -264,19 +266,18 @@
   return AppendRelativePath(child, nullptr);
 }
 
-bool FilePath::AppendRelativePath(const FilePath& child,
-                                  FilePath* path) const {
+bool FilePath::AppendRelativePath(const FilePath& child, FilePath* path) const {
   std::vector<StringType> parent_components = GetComponents();
   std::vector<StringType> child_components = child.GetComponents();
 
   if (parent_components.empty() ||
-      parent_components.size() >= child_components.size())
+      parent_components.size() >= child_components.size()) {
     return false;
+  }
 
   std::vector<StringType>::const_iterator parent_comp =
       parent_components.begin();
-  std::vector<StringType>::const_iterator child_comp =
-      child_components.begin();
+  std::vector<StringType>::const_iterator child_comp = child_components.begin();
 
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
   // Windows can access case sensitive filesystems, so component
@@ -284,8 +285,10 @@
   // never case sensitive.
   if ((FindDriveLetter(*parent_comp) != StringType::npos) &&
       (FindDriveLetter(*child_comp) != StringType::npos)) {
-    if (!StartsWith(*parent_comp, *child_comp, CompareCase::INSENSITIVE_ASCII))
+    if (!StartsWith(*parent_comp, *child_comp,
+                    CompareCase::INSENSITIVE_ASCII)) {
       return false;
+    }
     ++parent_comp;
     ++child_comp;
   }
@@ -302,8 +305,9 @@
   }
 
   while (parent_comp != parent_components.end()) {
-    if (*parent_comp != *child_comp)
+    if (*parent_comp != *child_comp) {
       return false;
+    }
     ++parent_comp;
     ++child_comp;
   }
@@ -330,9 +334,8 @@
   // resizes below using letter will still be valid.
   StringType::size_type letter = FindDriveLetter(new_path.path_);
 
-  StringType::size_type last_separator =
-      new_path.path_.find_last_of(kSeparators, StringType::npos,
-                                  kSeparatorsLength - 1);
+  StringType::size_type last_separator = new_path.path_.find_last_of(
+      kSeparators, StringType::npos, kSeparatorsLength - 1);
   if (last_separator == StringType::npos) {
     // path_ is in the current directory.
     new_path.path_.resize(letter + 1);
@@ -364,8 +367,9 @@
   }
 
   new_path.StripTrailingSeparatorsInternal();
-  if (!new_path.path_.length())
+  if (!new_path.path_.length()) {
     new_path.path_ = kCurrentDirectory;
+  }
 
   return new_path;
 }
@@ -382,9 +386,8 @@
 
   // Keep everything after the final separator, but if the pathname is only
   // one character and it's a separator, leave it alone.
-  StringType::size_type last_separator =
-      new_path.path_.find_last_of(kSeparators, StringType::npos,
-                                  kSeparatorsLength - 1);
+  StringType::size_type last_separator = new_path.path_.find_last_of(
+      kSeparators, StringType::npos, kSeparatorsLength - 1);
   if (last_separator != StringType::npos &&
       last_separator < new_path.path_.length() - 1) {
     new_path.path_.erase(0, last_separator + 1);
@@ -396,8 +399,9 @@
 StringType FilePath::Extension() const {
   FilePath base(BaseName());
   const StringType::size_type dot = ExtensionSeparatorPosition(base.path_);
-  if (dot == StringType::npos)
+  if (dot == StringType::npos) {
     return StringType();
+  }
 
   return base.path_.substr(dot, StringType::npos);
 }
@@ -405,40 +409,47 @@
 StringType FilePath::FinalExtension() const {
   FilePath base(BaseName());
   const StringType::size_type dot = FinalExtensionSeparatorPosition(base.path_);
-  if (dot == StringType::npos)
+  if (dot == StringType::npos) {
     return StringType();
+  }
 
   return base.path_.substr(dot, StringType::npos);
 }
 
 FilePath FilePath::RemoveExtension() const {
-  if (Extension().empty())
+  if (Extension().empty()) {
     return *this;
+  }
 
   const StringType::size_type dot = ExtensionSeparatorPosition(path_);
-  if (dot == StringType::npos)
+  if (dot == StringType::npos) {
     return *this;
+  }
 
   return FilePath(path_.substr(0, dot));
 }
 
 FilePath FilePath::RemoveFinalExtension() const {
-  if (FinalExtension().empty())
+  if (FinalExtension().empty()) {
     return *this;
+  }
 
   const StringType::size_type dot = FinalExtensionSeparatorPosition(path_);
-  if (dot == StringType::npos)
+  if (dot == StringType::npos) {
     return *this;
+  }
 
   return FilePath(path_.substr(0, dot));
 }
 
-FilePath FilePath::InsertBeforeExtension(StringPieceType suffix) const {
-  if (suffix.empty())
+FilePath FilePath::InsertBeforeExtension(StringViewType suffix) const {
+  if (suffix.empty()) {
     return FilePath(path_);
+  }
 
-  if (IsEmptyOrSpecialCase(BaseName().value()))
+  if (IsEmptyOrSpecialCase(BaseName().value())) {
     return FilePath();
+  }
 
   return FilePath(
       base::StrCat({RemoveExtension().value(), suffix, Extension()}));
@@ -446,6 +457,11 @@
 
 FilePath FilePath::InsertBeforeExtensionASCII(std::string_view suffix) const {
   DCHECK(IsStringASCII(suffix));
+  return InsertBeforeExtensionUTF8(suffix);
+}
+
+FilePath FilePath::InsertBeforeExtensionUTF8(std::string_view suffix) const {
+  DCHECK(IsStringUTF8(suffix));
 #if BUILDFLAG(IS_WIN)
   return InsertBeforeExtension(UTF8ToWide(suffix));
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
@@ -453,14 +469,16 @@
 #endif
 }
 
-FilePath FilePath::AddExtension(StringPieceType extension) const {
-  if (IsEmptyOrSpecialCase(BaseName().value()))
+FilePath FilePath::AddExtension(StringViewType extension) const {
+  if (IsEmptyOrSpecialCase(BaseName().value())) {
     return FilePath();
+  }
 
   // If the new extension is "" or ".", then just return the current FilePath.
   if (extension.empty() ||
-      (extension.size() == 1 && extension[0] == kExtensionSeparator))
+      (extension.size() == 1 && extension[0] == kExtensionSeparator)) {
     return *this;
+  }
 
   StringType str = path_;
   if (extension[0] != kExtensionSeparator &&
@@ -473,6 +491,11 @@
 
 FilePath FilePath::AddExtensionASCII(std::string_view extension) const {
   DCHECK(IsStringASCII(extension));
+  return AddExtensionUTF8(extension);
+}
+
+FilePath FilePath::AddExtensionUTF8(std::string_view extension) const {
+  DCHECK(IsStringUTF8(extension));
 #if BUILDFLAG(IS_WIN)
   return AddExtension(UTF8ToWide(extension));
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
@@ -480,53 +503,58 @@
 #endif
 }
 
-FilePath FilePath::ReplaceExtension(StringPieceType extension) const {
-  if (IsEmptyOrSpecialCase(BaseName().value()))
+FilePath FilePath::ReplaceExtension(StringViewType extension) const {
+  if (IsEmptyOrSpecialCase(BaseName().value())) {
     return FilePath();
+  }
 
   FilePath no_ext = RemoveExtension();
   // If the new extension is "" or ".", then just remove the current extension.
   if (extension.empty() ||
-      (extension.size() == 1 && extension[0] == kExtensionSeparator))
+      (extension.size() == 1 && extension[0] == kExtensionSeparator)) {
     return no_ext;
+  }
 
   StringType str = no_ext.value();
-  if (extension[0] != kExtensionSeparator)
+  if (extension[0] != kExtensionSeparator) {
     str.append(1, kExtensionSeparator);
+  }
   str.append(extension);
   return FilePath(str);
 }
 
-bool FilePath::MatchesExtension(StringPieceType extension) const {
+bool FilePath::MatchesExtension(StringViewType extension) const {
   DCHECK(extension.empty() || extension[0] == kExtensionSeparator);
 
   StringType current_extension = Extension();
 
-  if (current_extension.length() != extension.length())
+  if (current_extension.length() != extension.length()) {
     return false;
+  }
 
   return FilePath::CompareEqualIgnoreCase(extension, current_extension);
 }
 
-bool FilePath::MatchesFinalExtension(StringPieceType extension) const {
+bool FilePath::MatchesFinalExtension(StringViewType extension) const {
   DCHECK(extension.empty() || extension[0] == kExtensionSeparator);
 
   StringType current_final_extension = FinalExtension();
 
-  if (current_final_extension.length() != extension.length())
+  if (current_final_extension.length() != extension.length()) {
     return false;
+  }
 
   return FilePath::CompareEqualIgnoreCase(extension, current_final_extension);
 }
 
-FilePath FilePath::Append(StringPieceType component) const {
-  StringPieceType appended = component;
+FilePath FilePath::Append(StringViewType component) const {
+  StringViewType appended = component;
   StringType without_nuls;
 
   StringType::size_type nul_pos = component.find(kStringTerminator);
-  if (nul_pos != StringPieceType::npos) {
+  if (nul_pos != StringViewType::npos) {
     without_nuls = StringType(component.substr(0, nul_pos));
-    appended = StringPieceType(without_nuls);
+    appended = StringViewType(without_nuls);
   }
 
   DCHECK(!IsPathAbsolute(appended));
@@ -573,6 +601,11 @@
 
 FilePath FilePath::AppendASCII(std::string_view component) const {
   DCHECK(base::IsStringASCII(component));
+  return AppendUTF8(component);
+}
+
+FilePath FilePath::AppendUTF8(std::string_view component) const {
+  DCHECK(base::IsStringUTF8(component));
 #if BUILDFLAG(IS_WIN)
   return Append(UTF8ToWide(component));
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
@@ -590,14 +623,16 @@
 }
 
 bool FilePath::EndsWithSeparator() const {
-  if (empty())
+  if (empty()) {
     return false;
+  }
   return IsSeparator(path_.back());
 }
 
 FilePath FilePath::AsEndingWithSeparator() const {
-  if (EndsWithSeparator() || path_.empty())
+  if (EndsWithSeparator() || path_.empty()) {
     return *this;
+  }
 
   StringType path_str;
   path_str.reserve(path_.length() + 1);  // Only allocate string once.
@@ -681,8 +716,9 @@
 }
 
 std::string FilePath::MaybeAsASCII() const {
-  if (base::IsStringASCII(path_))
+  if (base::IsStringASCII(path_)) {
     return path_;
+  }
   return std::string();
 }
 
@@ -741,18 +777,21 @@
 bool FilePath::ReadFromPickle(PickleIterator* iter) {
 #if BUILDFLAG(IS_WIN)
   std::u16string path;
-  if (!iter->ReadString16(&path))
+  if (!iter->ReadString16(&path)) {
     return false;
+  }
   path_ = UTF16ToWide(path);
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
-  if (!iter->ReadString(&path_))
+  if (!iter->ReadString(&path_)) {
     return false;
+  }
 #else
 #error Unsupported platform
 #endif
 
-  if (path_.find(kStringTerminator) != StringType::npos)
+  if (path_.find(kStringTerminator) != StringType::npos) {
     return false;
+  }
 
   return true;
 }
@@ -760,8 +799,8 @@
 #if BUILDFLAG(IS_WIN)
 // Windows specific implementation of file string comparisons.
 
-int FilePath::CompareIgnoreCase(StringPieceType string1,
-                                StringPieceType string2) {
+int FilePath::CompareIgnoreCase(StringViewType string1,
+                                StringViewType string2) {
   // CharUpperW within user32 is used here because it will provide unicode
   // conversions regardless of locale. The STL alternative, towupper, has a
   // locale consideration that prevents it from converting all characters by
@@ -770,31 +809,36 @@
   // Perform character-wise upper case comparison rather than using the
   // fully Unicode-aware CompareString(). For details see:
   // http://blogs.msdn.com/michkap/archive/2005/10/17/481600.aspx
-  StringPieceType::const_iterator i1 = string1.begin();
-  StringPieceType::const_iterator i2 = string2.begin();
-  StringPieceType::const_iterator string1end = string1.end();
-  StringPieceType::const_iterator string2end = string2.end();
-  for ( ; i1 != string1end && i2 != string2end; ++i1, ++i2) {
+  StringViewType::const_iterator i1 = string1.begin();
+  StringViewType::const_iterator i2 = string2.begin();
+  StringViewType::const_iterator string1end = string1.end();
+  StringViewType::const_iterator string2end = string2.end();
+  for (; i1 != string1end && i2 != string2end; ++i1, ++i2) {
     wchar_t c1 =
         (wchar_t)LOWORD(::CharUpperW((LPWSTR)(DWORD_PTR)MAKELONG(*i1, 0)));
     wchar_t c2 =
         (wchar_t)LOWORD(::CharUpperW((LPWSTR)(DWORD_PTR)MAKELONG(*i2, 0)));
-    if (c1 < c2)
+    if (c1 < c2) {
       return -1;
-    if (c1 > c2)
+    }
+    if (c1 > c2) {
       return 1;
+    }
   }
-  if (i1 != string1end)
+  if (i1 != string1end) {
     return 1;
-  if (i2 != string2end)
+  }
+  if (i2 != string2end) {
     return -1;
+  }
   return 0;
 }
 
 #elif BUILDFLAG(IS_APPLE)
 // Mac OS X specific implementation of file string comparisons.
 
-// cf. https://developer.apple.com/library/archive/technotes/tn/tn1150.html#UnicodeSubtleties
+// cf.
+// https://developer.apple.com/library/archive/technotes/tn/tn1150.html#UnicodeSubtleties
 //
 // "When using CreateTextEncoding to create a text encoding, you should set
 // the TextEncodingBase to kTextEncodingUnicodeV2_0, set the
@@ -805,7 +849,8 @@
 //
 // Another technical article for X 10.4 updates this: one should use
 // the new (unambiguous) kUnicodeHFSPlusDecompVariant.
-// cf. http://developer.apple.com/mac/library/releasenotes/TextFonts/RN-TEC/index.html
+// cf.
+// http://developer.apple.com/mac/library/releasenotes/TextFonts/RN-TEC/index.html
 //
 // This implementation uses CFStringGetFileSystemRepresentation() to get the
 // decomposed form, and an adapted version of the FastUnicodeCompare as
@@ -1234,8 +1279,9 @@
     if (codepoint > 0 && codepoint <= 0xFFFF) {
       // Check if there is a subtable for this upper byte.
       int lookup_offset = lower_case_table[codepoint >> 8];
-      if (lookup_offset != 0)
+      if (lookup_offset != 0) {
         codepoint = lower_case_table[lookup_offset + (codepoint & 0x00FF)];
+      }
       // Note: `codepoint` may be again 0 at this point if the character was
       // an ignorable.
     }
@@ -1248,8 +1294,8 @@
 // Special UTF-8 version of FastUnicodeCompare. Cf:
 // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
 // The input strings must be in the special HFS decomposed form.
-int FilePath::HFSFastUnicodeCompare(StringPieceType string1,
-                                    StringPieceType string2) {
+int FilePath::HFSFastUnicodeCompare(StringViewType string1,
+                                    StringViewType string2) {
   size_t length1 = string1.length();
   size_t length2 = string2.length();
   size_t index1 = 0;
@@ -1260,8 +1306,9 @@
         HFSReadNextNonIgnorableCodepoint(string1.data(), length1, &index1);
     base_icu::UChar32 codepoint2 =
         HFSReadNextNonIgnorableCodepoint(string2.data(), length2, &index2);
-    if (codepoint1 != codepoint2)
+    if (codepoint1 != codepoint2) {
       return (codepoint1 < codepoint2) ? -1 : 1;
+    }
     if (codepoint1 == 0) {
       DCHECK_EQ(index1, length1);
       DCHECK_EQ(index2, length2);
@@ -1270,7 +1317,7 @@
   }
 }
 
-StringType FilePath::GetHFSDecomposedForm(StringPieceType string) {
+StringType FilePath::GetHFSDecomposedForm(StringViewType string) {
   apple::ScopedCFTypeRef<CFStringRef> cfstring(CFStringCreateWithBytesNoCopy(
       nullptr, reinterpret_cast<const UInt8*>(string.data()),
       checked_cast<CFIndex>(string.length()), kCFStringEncodingUTF8, false,
@@ -1306,14 +1353,16 @@
   return result;
 }
 
-int FilePath::CompareIgnoreCase(StringPieceType string1,
-                                StringPieceType string2) {
+int FilePath::CompareIgnoreCase(StringViewType string1,
+                                StringViewType string2) {
   // Quick checks for empty strings - these speed things up a bit and make the
   // following code cleaner.
-  if (string1.empty())
+  if (string1.empty()) {
     return string2.empty() ? 0 : -1;
-  if (string2.empty())
+  }
+  if (string2.empty()) {
     return 1;
+  }
 
   StringType hfs1 = GetHFSDecomposedForm(string1);
   StringType hfs2 = GetHFSDecomposedForm(string2);
@@ -1334,10 +1383,12 @@
     if (!cfstring1 || !cfstring2) {
       int comparison = memcmp(string1.data(), string2.data(),
                               std::min(string1.length(), string2.length()));
-      if (comparison < 0)
+      if (comparison < 0) {
         return -1;
-      if (comparison > 0)
+      }
+      if (comparison > 0) {
         return 1;
+      }
       return 0;
     }
 
@@ -1351,20 +1402,21 @@
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
 
 // Generic Posix system comparisons.
-int FilePath::CompareIgnoreCase(StringPieceType string1,
-                                StringPieceType string2) {
+int FilePath::CompareIgnoreCase(StringViewType string1,
+                                StringViewType string2) {
   size_t rlen = std::min(string1.size(), string2.size());
   int comparison = strncasecmp(string1.data(), string2.data(), rlen);
-  if (comparison < 0 || (comparison == 0 && string1.size() < string2.size()))
+  if (comparison < 0 || (comparison == 0 && string1.size() < string2.size())) {
     return -1;
-  if (comparison > 0 || (comparison == 0 && string1.size() > string2.size()))
+  }
+  if (comparison > 0 || (comparison == 0 && string1.size() > string2.size())) {
     return 1;
+  }
   return 0;
 }
 
 #endif  // OS versions of CompareIgnoreCase()
 
-
 void FilePath::StripTrailingSeparatorsInternal() {
   // If there is no drive letter, start will be 1, which will prevent stripping
   // the leading separator if there is only one separator.  If there is a drive
@@ -1375,8 +1427,7 @@
 
   StringType::size_type last_stripped = StringType::npos;
   for (StringType::size_type pos = path_.length();
-       pos > start && IsSeparator(path_[pos - 1]);
-       --pos) {
+       pos > start && IsSeparator(path_[pos - 1]); --pos) {
     // If the string only has two separators and they're at the beginning,
     // don't strip them, unless the string began with more than two separators.
     if (pos != start + 1 || last_stripped == start + 2 ||
diff --git a/tot/base/files/file_path.h b/tot/base/files/file_path.h
index 5d14b77..bbe1c44 100644
--- a/tot/base/files/file_path.h
+++ b/tot/base/files/file_path.h
@@ -146,7 +146,7 @@
 #endif  // BUILDFLAG(IS_WIN)
 
 #if BUILDFLAG(IS_APPLE)
-typedef const struct __CFString* CFStringRef;
+using CFStringRef = const struct __CFString*;
 #endif
 
 namespace base {
@@ -162,16 +162,16 @@
 #if BUILDFLAG(IS_WIN)
   // On Windows, for Unicode-aware applications, native pathnames are wchar_t
   // arrays encoded in UTF-16.
-  typedef std::wstring StringType;
+  using StringType = std::wstring;
 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
   // On most platforms, native pathnames are char arrays, and the encoding
   // may or may not be specified.  On Mac OS X, native pathnames are encoded
   // in UTF-8.
-  typedef std::string StringType;
+  using StringType = std::string;
 #endif  // BUILDFLAG(IS_WIN)
 
-  typedef StringType::value_type CharType;
-  typedef std::basic_string_view<CharType> StringPieceType;
+  using CharType = StringType::value_type;
+  using StringViewType = std::basic_string_view<CharType>;
 
   // Null-terminated array of separators used to separate components in paths.
   // Each character in this array is a valid separator, but kSeparators[0] is
@@ -198,7 +198,7 @@
 
   FilePath();
   FilePath(const FilePath& that);
-  explicit FilePath(StringPieceType path);
+  explicit FilePath(StringViewType path);
   ~FilePath();
   FilePath& operator=(const FilePath& that);
 
@@ -209,14 +209,12 @@
   // unspecified state.
   FilePath& operator=(FilePath&& that) noexcept;
 
+  // On systems which use drive letters, the drive letters are compared
+  // case-insensitively.
   bool operator==(const FilePath& that) const;
 
-  bool operator!=(const FilePath& that) const;
-
   // Required for some STL containers and operations
-  bool operator<(const FilePath& that) const {
-    return path_ < that.path_;
-  }
+  auto operator<=>(const FilePath& that) const = default;
 
   const StringType& value() const LIFETIME_BOUND { return path_; }
 
@@ -327,31 +325,45 @@
   // path == "jojo.jpg"         suffix == " (1)", returns "jojo (1).jpg"
   // path == "C:\pics\jojo"     suffix == " (1)", returns "C:\pics\jojo (1)"
   // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)"
-  [[nodiscard]] FilePath InsertBeforeExtension(StringPieceType suffix) const;
+  [[nodiscard]] FilePath InsertBeforeExtension(StringViewType suffix) const;
   [[nodiscard]] FilePath InsertBeforeExtensionASCII(
       std::string_view suffix) const;
 
+  // Like above, but takes the `suffix` as an UTF8 string.
+  // While all modern OSes support UTF-8, there is no requirement for the
+  // filenames to actually be UTF-8, e.g. on Linux. So inserting UTF-8 could
+  // result in Mojibake filenames.
+  [[nodiscard]] FilePath InsertBeforeExtensionUTF8(
+      std::string_view suffix) const;
+
   // Adds |extension| to |file_name|. Returns the current FilePath if
   // |extension| is empty. Returns "" if BaseName() == "." or "..".
-  [[nodiscard]] FilePath AddExtension(StringPieceType extension) const;
+  [[nodiscard]] FilePath AddExtension(StringViewType extension) const;
 
   // Like above, but takes the extension as an ASCII string. See AppendASCII for
   // details on how this is handled.
   [[nodiscard]] FilePath AddExtensionASCII(std::string_view extension) const;
 
+  // Like above, but takes the extension as an UTF8 string. See AppendUTF8 for
+  // details on how this is handled.
+  // While all modern OSes support UTF-8, there is no requirement for the
+  // filenames to actually be UTF-8, e.g. on Linux. So appending UTF-8 could
+  // result in Mojibake filenames.
+  [[nodiscard]] FilePath AddExtensionUTF8(std::string_view extension) const;
+
   // Replaces the extension of |file_name| with |extension|.  If |file_name|
   // does not have an extension, then |extension| is added.  If |extension| is
   // empty, then the extension is removed from |file_name|.
   // Returns "" if BaseName() == "." or "..".
-  [[nodiscard]] FilePath ReplaceExtension(StringPieceType extension) const;
+  [[nodiscard]] FilePath ReplaceExtension(StringViewType extension) const;
 
   // Returns true if file path's Extension() matches `extension`. The test is
   // case insensitive. Don't forget the leading period if appropriate.
-  bool MatchesExtension(StringPieceType extension) const;
+  bool MatchesExtension(StringViewType extension) const;
 
   // Returns true if file path's FinalExtension() matches `extension`. The
   // test is case insensitive. Don't forget the leading period if appropriate.
-  bool MatchesFinalExtension(StringPieceType extension) const;
+  bool MatchesFinalExtension(StringViewType extension) const;
 
   // Returns a FilePath by appending a separator and the supplied path
   // component to this object's path.  Append takes care to avoid adding
@@ -359,7 +371,7 @@
   // If this object's path is kCurrentDirectory ('.'), a new FilePath
   // corresponding only to |component| is returned.  |component| must be a
   // relative path; it is an error to pass an absolute path.
-  [[nodiscard]] FilePath Append(StringPieceType component) const;
+  [[nodiscard]] FilePath Append(StringViewType component) const;
   [[nodiscard]] FilePath Append(const FilePath& component) const;
   [[nodiscard]] FilePath Append(const SafeBaseName& component) const;
 
@@ -371,6 +383,12 @@
   // system paths will always be ASCII.
   [[nodiscard]] FilePath AppendASCII(std::string_view component) const;
 
+  // Like above, but takes the `component` as an UTF8 string.
+  // While all modern OSes support UTF-8, there is no requirement for the
+  // filenames to actually be UTF-8, e.g. on Linux. So appending UTF-8 could
+  // result in Mojibake filenames.
+  [[nodiscard]] FilePath AppendUTF8(std::string_view component) const;
+
   // Returns true if this FilePath contains an absolute path.  On Windows, an
   // absolute path begins with either a drive letter specification followed by
   // a separator character, or with two separator characters.  On POSIX
@@ -460,14 +478,13 @@
   // on parts of a file path, e.g., just the extension.
   // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and
   // greater-than respectively.
-  static int CompareIgnoreCase(StringPieceType string1,
-                               StringPieceType string2);
-  static bool CompareEqualIgnoreCase(StringPieceType string1,
-                                     StringPieceType string2) {
+  static int CompareIgnoreCase(StringViewType string1, StringViewType string2);
+  static bool CompareEqualIgnoreCase(StringViewType string1,
+                                     StringViewType string2) {
     return CompareIgnoreCase(string1, string2) == 0;
   }
-  static bool CompareLessIgnoreCase(StringPieceType string1,
-                                    StringPieceType string2) {
+  static bool CompareLessIgnoreCase(StringViewType string1,
+                                    StringViewType string2) {
     return CompareIgnoreCase(string1, string2) < 0;
   }
 
@@ -480,15 +497,15 @@
   // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties
   // for further comments.
   // Returns the empty string if the conversion failed.
-  static StringType GetHFSDecomposedForm(StringPieceType string);
+  static StringType GetHFSDecomposedForm(StringViewType string);
   static StringType GetHFSDecomposedForm(CFStringRef cfstring);
 
   // Special UTF-8 version of FastUnicodeCompare. Cf:
   // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
   // IMPORTANT: The input strings must be in the special HFS decomposed form!
   // (cf. above GetHFSDecomposedForm method)
-  static int HFSFastUnicodeCompare(StringPieceType string1,
-                                   StringPieceType string2);
+  static int HFSFastUnicodeCompare(StringViewType string1,
+                                   StringViewType string2);
 #endif
 
 #if BUILDFLAG(IS_ANDROID)
diff --git a/tot/base/files/file_path_fuzzer.cc b/tot/base/files/file_path_fuzzer.cc
index a41a916..94be1ca 100644
--- a/tot/base/files/file_path_fuzzer.cc
+++ b/tot/base/files/file_path_fuzzer.cc
@@ -2,6 +2,8 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "base/files/file_path.h"
+
 #include <fuzzer/FuzzedDataProvider.h>
 #include <stdint.h>
 
@@ -10,7 +12,6 @@
 
 #include "base/check.h"
 #include "base/check_op.h"
-#include "base/files/file_path.h"
 #include "base/pickle.h"
 #include "base/strings/string_util.h"
 #include "base/strings/utf_string_conversions.h"
@@ -90,8 +91,9 @@
   // Smoke-test operations against a second path.
   FilePath second_path(GenerateNativeString(provider));
   std::ignore = path.IsParent(second_path);
-  if (!second_path.IsAbsolute())
+  if (!second_path.IsAbsolute()) {
     std::ignore = path.Append(second_path);
+  }
   FilePath relative_path;
   std::ignore = path.AppendRelativePath(second_path, &relative_path);
 
diff --git a/tot/base/files/file_path_unittest.cc b/tot/base/files/file_path_unittest.cc
index 9c50ba6..be17e0b 100644
--- a/tot/base/files/file_path_unittest.cc
+++ b/tot/base/files/file_path_unittest.cc
@@ -11,12 +11,14 @@
 
 #include <stddef.h>
 
+#include <array>
 #include <sstream>
 #include <string_view>
 
 #include "base/files/safe_base_name.h"
 #include "base/strings/utf_ostream_operators.h"
 #include "base/strings/utf_string_conversions.h"
+#include "base/test/gtest_util.h"
 #include "build/build_config.h"
 #include "build/buildflag.h"
 #include "testing/gtest/include/gtest/gtest.h"
@@ -42,301 +44,301 @@
 namespace base {
 
 struct UnaryTestData {
-  FilePath::StringPieceType input;
-  FilePath::StringPieceType expected;
+  FilePath::StringViewType input;
+  FilePath::StringViewType expected;
 };
 
 struct UnaryBooleanTestData {
-  FilePath::StringPieceType input;
+  FilePath::StringViewType input;
   bool expected;
 };
 
 struct BinaryTestData {
-  FilePath::StringPieceType inputs[2];
-  FilePath::StringPieceType expected;
+  FilePath::StringViewType inputs[2];
+  FilePath::StringViewType expected;
 };
 
 struct BinaryBooleanTestData {
-  FilePath::StringPieceType inputs[2];
+  FilePath::StringViewType inputs[2];
   bool expected;
 };
 
 struct BinaryIntTestData {
-  FilePath::StringPieceType inputs[2];
+  FilePath::StringViewType inputs[2];
   int expected;
 };
 
 struct UTF8TestData {
-  FilePath::StringPieceType native;
+  FilePath::StringViewType native;
   std::string_view utf8;
 };
 
 // file_util winds up using autoreleased objects on the Mac, so this needs
 // to be a PlatformTest
-typedef PlatformTest FilePathTest;
+using FilePathTest = PlatformTest;
 
 TEST_F(FilePathTest, DirName) {
-  const struct UnaryTestData cases[] = {
-    {FPL(""), FPL(".")},
-    {FPL("aa"), FPL(".")},
-    {FPL("/aa/bb"), FPL("/aa")},
-    {FPL("/aa/bb/"), FPL("/aa")},
-    {FPL("/aa/bb//"), FPL("/aa")},
-    {FPL("/aa/bb/ccc"), FPL("/aa/bb")},
-    {FPL("/aa"), FPL("/")},
-    {FPL("/aa/"), FPL("/")},
-    {FPL("/"), FPL("/")},
-    {FPL("//"), FPL("//")},
-    {FPL("///"), FPL("/")},
-    {FPL("aa/"), FPL(".")},
-    {FPL("aa/bb"), FPL("aa")},
-    {FPL("aa/bb/"), FPL("aa")},
-    {FPL("aa/bb//"), FPL("aa")},
-    {FPL("aa//bb//"), FPL("aa")},
-    {FPL("aa//bb/"), FPL("aa")},
-    {FPL("aa//bb"), FPL("aa")},
-    {FPL("//aa/bb"), FPL("//aa")},
-    {FPL("//aa/"), FPL("//")},
-    {FPL("//aa"), FPL("//")},
+  const auto cases = std::to_array<UnaryTestData>({
+      {FPL(""), FPL(".")},
+      {FPL("aa"), FPL(".")},
+      {FPL("/aa/bb"), FPL("/aa")},
+      {FPL("/aa/bb/"), FPL("/aa")},
+      {FPL("/aa/bb//"), FPL("/aa")},
+      {FPL("/aa/bb/ccc"), FPL("/aa/bb")},
+      {FPL("/aa"), FPL("/")},
+      {FPL("/aa/"), FPL("/")},
+      {FPL("/"), FPL("/")},
+      {FPL("//"), FPL("//")},
+      {FPL("///"), FPL("/")},
+      {FPL("aa/"), FPL(".")},
+      {FPL("aa/bb"), FPL("aa")},
+      {FPL("aa/bb/"), FPL("aa")},
+      {FPL("aa/bb//"), FPL("aa")},
+      {FPL("aa//bb//"), FPL("aa")},
+      {FPL("aa//bb/"), FPL("aa")},
+      {FPL("aa//bb"), FPL("aa")},
+      {FPL("//aa/bb"), FPL("//aa")},
+      {FPL("//aa/"), FPL("//")},
+      {FPL("//aa"), FPL("//")},
 #if BUILDFLAG(IS_POSIX)
-    {FPL("///aa/"), FPL("/")},
-    {FPL("///aa"), FPL("/")},
-    {FPL("///"), FPL("/")},
+      {FPL("///aa/"), FPL("/")},
+      {FPL("///aa"), FPL("/")},
+      {FPL("///"), FPL("/")},
 #endif  // BUILDFLAG(IS_POSIX)
-    {FPL("0:"), FPL(".")},
-    {FPL("@:"), FPL(".")},
-    {FPL("[:"), FPL(".")},
-    {FPL("`:"), FPL(".")},
-    {FPL("{:"), FPL(".")},
-    {FPL("\xB3:"), FPL(".")},
-    {FPL("\xC5:"), FPL(".")},
-    {FPL("/aa/../bb/cc"), FPL("/aa/../bb")},
+      {FPL("0:"), FPL(".")},
+      {FPL("@:"), FPL(".")},
+      {FPL("[:"), FPL(".")},
+      {FPL("`:"), FPL(".")},
+      {FPL("{:"), FPL(".")},
+      {FPL("\xB3:"), FPL(".")},
+      {FPL("\xC5:"), FPL(".")},
+      {FPL("/aa/../bb/cc"), FPL("/aa/../bb")},
 #if BUILDFLAG(IS_WIN)
-    {FPL("\x0143:"), FPL(".")},
+      {FPL("\x0143:"), FPL(".")},
 #endif  // BUILDFLAG(IS_WIN)
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    {FPL("c:"), FPL("c:")},
-    {FPL("C:"), FPL("C:")},
-    {FPL("A:"), FPL("A:")},
-    {FPL("Z:"), FPL("Z:")},
-    {FPL("a:"), FPL("a:")},
-    {FPL("z:"), FPL("z:")},
-    {FPL("c:aa"), FPL("c:")},
-    {FPL("c:/"), FPL("c:/")},
-    {FPL("c://"), FPL("c://")},
-    {FPL("c:///"), FPL("c:/")},
-    {FPL("c:/aa"), FPL("c:/")},
-    {FPL("c:/aa/"), FPL("c:/")},
-    {FPL("c:/aa/bb"), FPL("c:/aa")},
-    {FPL("c:aa/bb"), FPL("c:aa")},
+      {FPL("c:"), FPL("c:")},
+      {FPL("C:"), FPL("C:")},
+      {FPL("A:"), FPL("A:")},
+      {FPL("Z:"), FPL("Z:")},
+      {FPL("a:"), FPL("a:")},
+      {FPL("z:"), FPL("z:")},
+      {FPL("c:aa"), FPL("c:")},
+      {FPL("c:/"), FPL("c:/")},
+      {FPL("c://"), FPL("c://")},
+      {FPL("c:///"), FPL("c:/")},
+      {FPL("c:/aa"), FPL("c:/")},
+      {FPL("c:/aa/"), FPL("c:/")},
+      {FPL("c:/aa/bb"), FPL("c:/aa")},
+      {FPL("c:aa/bb"), FPL("c:aa")},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    {FPL("\\aa\\bb"), FPL("\\aa")},
-    {FPL("\\aa\\bb\\"), FPL("\\aa")},
-    {FPL("\\aa\\bb\\\\"), FPL("\\aa")},
-    {FPL("\\aa\\bb\\ccc"), FPL("\\aa\\bb")},
-    {FPL("\\aa"), FPL("\\")},
-    {FPL("\\aa\\"), FPL("\\")},
-    {FPL("\\"), FPL("\\")},
-    {FPL("\\\\"), FPL("\\\\")},
-    {FPL("\\\\\\"), FPL("\\")},
-    {FPL("aa\\"), FPL(".")},
-    {FPL("aa\\bb"), FPL("aa")},
-    {FPL("aa\\bb\\"), FPL("aa")},
-    {FPL("aa\\bb\\\\"), FPL("aa")},
-    {FPL("aa\\\\bb\\\\"), FPL("aa")},
-    {FPL("aa\\\\bb\\"), FPL("aa")},
-    {FPL("aa\\\\bb"), FPL("aa")},
-    {FPL("\\\\aa\\bb"), FPL("\\\\aa")},
-    {FPL("\\\\aa\\"), FPL("\\\\")},
-    {FPL("\\\\aa"), FPL("\\\\")},
-    {FPL("aa\\..\\bb\\c"), FPL("aa\\..\\bb")},
+      {FPL("\\aa\\bb"), FPL("\\aa")},
+      {FPL("\\aa\\bb\\"), FPL("\\aa")},
+      {FPL("\\aa\\bb\\\\"), FPL("\\aa")},
+      {FPL("\\aa\\bb\\ccc"), FPL("\\aa\\bb")},
+      {FPL("\\aa"), FPL("\\")},
+      {FPL("\\aa\\"), FPL("\\")},
+      {FPL("\\"), FPL("\\")},
+      {FPL("\\\\"), FPL("\\\\")},
+      {FPL("\\\\\\"), FPL("\\")},
+      {FPL("aa\\"), FPL(".")},
+      {FPL("aa\\bb"), FPL("aa")},
+      {FPL("aa\\bb\\"), FPL("aa")},
+      {FPL("aa\\bb\\\\"), FPL("aa")},
+      {FPL("aa\\\\bb\\\\"), FPL("aa")},
+      {FPL("aa\\\\bb\\"), FPL("aa")},
+      {FPL("aa\\\\bb"), FPL("aa")},
+      {FPL("\\\\aa\\bb"), FPL("\\\\aa")},
+      {FPL("\\\\aa\\"), FPL("\\\\")},
+      {FPL("\\\\aa"), FPL("\\\\")},
+      {FPL("aa\\..\\bb\\c"), FPL("aa\\..\\bb")},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    {FPL("c:\\"), FPL("c:\\")},
-    {FPL("c:\\\\"), FPL("c:\\\\")},
-    {FPL("c:\\\\\\"), FPL("c:\\")},
-    {FPL("c:\\aa"), FPL("c:\\")},
-    {FPL("c:\\aa\\"), FPL("c:\\")},
-    {FPL("c:\\aa\\bb"), FPL("c:\\aa")},
-    {FPL("c:aa\\bb"), FPL("c:aa")},
+      {FPL("c:\\"), FPL("c:\\")},
+      {FPL("c:\\\\"), FPL("c:\\\\")},
+      {FPL("c:\\\\\\"), FPL("c:\\")},
+      {FPL("c:\\aa"), FPL("c:\\")},
+      {FPL("c:\\aa\\"), FPL("c:\\")},
+      {FPL("c:\\aa\\bb"), FPL("c:\\aa")},
+      {FPL("c:aa\\bb"), FPL("c:aa")},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #endif  // FILE_PATH_USES_WIN_SEPARATORS
-  };
+  });
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath input(cases[i].input);
     FilePath observed = input.DirName();
-    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed.value()) <<
-              "i: " << i << ", input: " << input.value();
+    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed.value())
+        << "i: " << i << ", input: " << input.value();
   }
 }
 
 TEST_F(FilePathTest, BaseName) {
-  const struct UnaryTestData cases[] = {
-    {FPL(""), FPL("")},
-    {FPL("aa"), FPL("aa")},
-    {FPL("/aa/bb"), FPL("bb")},
-    {FPL("/aa/bb/"), FPL("bb")},
-    {FPL("/aa/bb//"), FPL("bb")},
-    {FPL("/aa/bb/ccc"), FPL("ccc")},
-    {FPL("/aa"), FPL("aa")},
-    {FPL("/"), FPL("/")},
-    {FPL("//"), FPL("//")},
-    {FPL("///"), FPL("/")},
-    {FPL("aa/"), FPL("aa")},
-    {FPL("aa/bb"), FPL("bb")},
-    {FPL("aa/bb/"), FPL("bb")},
-    {FPL("aa/bb//"), FPL("bb")},
-    {FPL("aa//bb//"), FPL("bb")},
-    {FPL("aa//bb/"), FPL("bb")},
-    {FPL("aa//bb"), FPL("bb")},
-    {FPL("//aa/bb"), FPL("bb")},
-    {FPL("//aa/"), FPL("aa")},
-    {FPL("//aa"), FPL("aa")},
-    {FPL("0:"), FPL("0:")},
-    {FPL("@:"), FPL("@:")},
-    {FPL("[:"), FPL("[:")},
-    {FPL("`:"), FPL("`:")},
-    {FPL("{:"), FPL("{:")},
-    {FPL("\xB3:"), FPL("\xB3:")},
-    {FPL("\xC5:"), FPL("\xC5:")},
+  const auto cases = std::to_array<UnaryTestData>({
+      {FPL(""), FPL("")},
+      {FPL("aa"), FPL("aa")},
+      {FPL("/aa/bb"), FPL("bb")},
+      {FPL("/aa/bb/"), FPL("bb")},
+      {FPL("/aa/bb//"), FPL("bb")},
+      {FPL("/aa/bb/ccc"), FPL("ccc")},
+      {FPL("/aa"), FPL("aa")},
+      {FPL("/"), FPL("/")},
+      {FPL("//"), FPL("//")},
+      {FPL("///"), FPL("/")},
+      {FPL("aa/"), FPL("aa")},
+      {FPL("aa/bb"), FPL("bb")},
+      {FPL("aa/bb/"), FPL("bb")},
+      {FPL("aa/bb//"), FPL("bb")},
+      {FPL("aa//bb//"), FPL("bb")},
+      {FPL("aa//bb/"), FPL("bb")},
+      {FPL("aa//bb"), FPL("bb")},
+      {FPL("//aa/bb"), FPL("bb")},
+      {FPL("//aa/"), FPL("aa")},
+      {FPL("//aa"), FPL("aa")},
+      {FPL("0:"), FPL("0:")},
+      {FPL("@:"), FPL("@:")},
+      {FPL("[:"), FPL("[:")},
+      {FPL("`:"), FPL("`:")},
+      {FPL("{:"), FPL("{:")},
+      {FPL("\xB3:"), FPL("\xB3:")},
+      {FPL("\xC5:"), FPL("\xC5:")},
 #if BUILDFLAG(IS_WIN)
-    {FPL("\x0143:"), FPL("\x0143:")},
+      {FPL("\x0143:"), FPL("\x0143:")},
 #endif  // BUILDFLAG(IS_WIN)
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    {FPL("c:"), FPL("")},
-    {FPL("C:"), FPL("")},
-    {FPL("A:"), FPL("")},
-    {FPL("Z:"), FPL("")},
-    {FPL("a:"), FPL("")},
-    {FPL("z:"), FPL("")},
-    {FPL("c:aa"), FPL("aa")},
-    {FPL("c:/"), FPL("/")},
-    {FPL("c://"), FPL("//")},
-    {FPL("c:///"), FPL("/")},
-    {FPL("c:/aa"), FPL("aa")},
-    {FPL("c:/aa/"), FPL("aa")},
-    {FPL("c:/aa/bb"), FPL("bb")},
-    {FPL("c:aa/bb"), FPL("bb")},
+      {FPL("c:"), FPL("")},
+      {FPL("C:"), FPL("")},
+      {FPL("A:"), FPL("")},
+      {FPL("Z:"), FPL("")},
+      {FPL("a:"), FPL("")},
+      {FPL("z:"), FPL("")},
+      {FPL("c:aa"), FPL("aa")},
+      {FPL("c:/"), FPL("/")},
+      {FPL("c://"), FPL("//")},
+      {FPL("c:///"), FPL("/")},
+      {FPL("c:/aa"), FPL("aa")},
+      {FPL("c:/aa/"), FPL("aa")},
+      {FPL("c:/aa/bb"), FPL("bb")},
+      {FPL("c:aa/bb"), FPL("bb")},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    {FPL("\\aa\\bb"), FPL("bb")},
-    {FPL("\\aa\\bb\\"), FPL("bb")},
-    {FPL("\\aa\\bb\\\\"), FPL("bb")},
-    {FPL("\\aa\\bb\\ccc"), FPL("ccc")},
-    {FPL("\\aa"), FPL("aa")},
-    {FPL("\\"), FPL("\\")},
-    {FPL("\\\\"), FPL("\\\\")},
-    {FPL("\\\\\\"), FPL("\\")},
-    {FPL("aa\\"), FPL("aa")},
-    {FPL("aa\\bb"), FPL("bb")},
-    {FPL("aa\\bb\\"), FPL("bb")},
-    {FPL("aa\\bb\\\\"), FPL("bb")},
-    {FPL("aa\\\\bb\\\\"), FPL("bb")},
-    {FPL("aa\\\\bb\\"), FPL("bb")},
-    {FPL("aa\\\\bb"), FPL("bb")},
-    {FPL("\\\\aa\\bb"), FPL("bb")},
-    {FPL("\\\\aa\\"), FPL("aa")},
-    {FPL("\\\\aa"), FPL("aa")},
+      {FPL("\\aa\\bb"), FPL("bb")},
+      {FPL("\\aa\\bb\\"), FPL("bb")},
+      {FPL("\\aa\\bb\\\\"), FPL("bb")},
+      {FPL("\\aa\\bb\\ccc"), FPL("ccc")},
+      {FPL("\\aa"), FPL("aa")},
+      {FPL("\\"), FPL("\\")},
+      {FPL("\\\\"), FPL("\\\\")},
+      {FPL("\\\\\\"), FPL("\\")},
+      {FPL("aa\\"), FPL("aa")},
+      {FPL("aa\\bb"), FPL("bb")},
+      {FPL("aa\\bb\\"), FPL("bb")},
+      {FPL("aa\\bb\\\\"), FPL("bb")},
+      {FPL("aa\\\\bb\\\\"), FPL("bb")},
+      {FPL("aa\\\\bb\\"), FPL("bb")},
+      {FPL("aa\\\\bb"), FPL("bb")},
+      {FPL("\\\\aa\\bb"), FPL("bb")},
+      {FPL("\\\\aa\\"), FPL("aa")},
+      {FPL("\\\\aa"), FPL("aa")},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    {FPL("c:\\"), FPL("\\")},
-    {FPL("c:\\\\"), FPL("\\\\")},
-    {FPL("c:\\\\\\"), FPL("\\")},
-    {FPL("c:\\aa"), FPL("aa")},
-    {FPL("c:\\aa\\"), FPL("aa")},
-    {FPL("c:\\aa\\bb"), FPL("bb")},
-    {FPL("c:aa\\bb"), FPL("bb")},
+      {FPL("c:\\"), FPL("\\")},
+      {FPL("c:\\\\"), FPL("\\\\")},
+      {FPL("c:\\\\\\"), FPL("\\")},
+      {FPL("c:\\aa"), FPL("aa")},
+      {FPL("c:\\aa\\"), FPL("aa")},
+      {FPL("c:\\aa\\bb"), FPL("bb")},
+      {FPL("c:aa\\bb"), FPL("bb")},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #endif  // FILE_PATH_USES_WIN_SEPARATORS
-  };
+  });
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath input(cases[i].input);
     FilePath observed = input.BaseName();
-    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed.value()) <<
-              "i: " << i << ", input: " << input.value();
+    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed.value())
+        << "i: " << i << ", input: " << input.value();
   }
 }
 
 TEST_F(FilePathTest, Append) {
-  const struct BinaryTestData cases[] = {
-    { { FPL(""),           FPL("cc") }, FPL("cc") },
-    { { FPL("."),          FPL("ff") }, FPL("ff") },
-    { { FPL("."),          FPL("") },   FPL(".") },
-    { { FPL("/"),          FPL("cc") }, FPL("/cc") },
-    { { FPL("/aa"),        FPL("") },   FPL("/aa") },
-    { { FPL("/aa/"),       FPL("") },   FPL("/aa") },
-    { { FPL("//aa"),       FPL("") },   FPL("//aa") },
-    { { FPL("//aa/"),      FPL("") },   FPL("//aa") },
-    { { FPL("//"),         FPL("aa") }, FPL("//aa") },
+  const auto cases = std::to_array<BinaryTestData>({
+      {{FPL(""), FPL("cc")}, FPL("cc")},
+      {{FPL("."), FPL("ff")}, FPL("ff")},
+      {{FPL("."), FPL("")}, FPL(".")},
+      {{FPL("/"), FPL("cc")}, FPL("/cc")},
+      {{FPL("/aa"), FPL("")}, FPL("/aa")},
+      {{FPL("/aa/"), FPL("")}, FPL("/aa")},
+      {{FPL("//aa"), FPL("")}, FPL("//aa")},
+      {{FPL("//aa/"), FPL("")}, FPL("//aa")},
+      {{FPL("//"), FPL("aa")}, FPL("//aa")},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    { { FPL("c:"),         FPL("a") },  FPL("c:a") },
-    { { FPL("c:"),         FPL("") },   FPL("c:") },
-    { { FPL("c:/"),        FPL("a") },  FPL("c:/a") },
-    { { FPL("c://"),       FPL("a") },  FPL("c://a") },
-    { { FPL("c:///"),      FPL("a") },  FPL("c:/a") },
+      {{FPL("c:"), FPL("a")}, FPL("c:a")},
+      {{FPL("c:"), FPL("")}, FPL("c:")},
+      {{FPL("c:/"), FPL("a")}, FPL("c:/a")},
+      {{FPL("c://"), FPL("a")}, FPL("c://a")},
+      {{FPL("c:///"), FPL("a")}, FPL("c:/a")},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    // Append introduces the default separator character, so these test cases
-    // need to be defined with different expected results on platforms that use
-    // different default separator characters.
-    { { FPL("\\"),         FPL("cc") }, FPL("\\cc") },
-    { { FPL("\\aa"),       FPL("") },   FPL("\\aa") },
-    { { FPL("\\aa\\"),     FPL("") },   FPL("\\aa") },
-    { { FPL("\\\\aa"),     FPL("") },   FPL("\\\\aa") },
-    { { FPL("\\\\aa\\"),   FPL("") },   FPL("\\\\aa") },
-    { { FPL("\\\\"),       FPL("aa") }, FPL("\\\\aa") },
-    { { FPL("/aa/bb"),     FPL("cc") }, FPL("/aa/bb\\cc") },
-    { { FPL("/aa/bb/"),    FPL("cc") }, FPL("/aa/bb\\cc") },
-    { { FPL("aa/bb/"),     FPL("cc") }, FPL("aa/bb\\cc") },
-    { { FPL("aa/bb"),      FPL("cc") }, FPL("aa/bb\\cc") },
-    { { FPL("a/b"),        FPL("c") },  FPL("a/b\\c") },
-    { { FPL("a/b/"),       FPL("c") },  FPL("a/b\\c") },
-    { { FPL("//aa"),       FPL("bb") }, FPL("//aa\\bb") },
-    { { FPL("//aa/"),      FPL("bb") }, FPL("//aa\\bb") },
-    { { FPL("\\aa\\bb"),   FPL("cc") }, FPL("\\aa\\bb\\cc") },
-    { { FPL("\\aa\\bb\\"), FPL("cc") }, FPL("\\aa\\bb\\cc") },
-    { { FPL("aa\\bb\\"),   FPL("cc") }, FPL("aa\\bb\\cc") },
-    { { FPL("aa\\bb"),     FPL("cc") }, FPL("aa\\bb\\cc") },
-    { { FPL("a\\b"),       FPL("c") },  FPL("a\\b\\c") },
-    { { FPL("a\\b\\"),     FPL("c") },  FPL("a\\b\\c") },
-    { { FPL("\\\\aa"),     FPL("bb") }, FPL("\\\\aa\\bb") },
-    { { FPL("\\\\aa\\"),   FPL("bb") }, FPL("\\\\aa\\bb") },
+      // Append introduces the default separator character, so these test cases
+      // need to be defined with different expected results on platforms that
+      // use different default separator characters.
+      {{FPL("\\"), FPL("cc")}, FPL("\\cc")},
+      {{FPL("\\aa"), FPL("")}, FPL("\\aa")},
+      {{FPL("\\aa\\"), FPL("")}, FPL("\\aa")},
+      {{FPL("\\\\aa"), FPL("")}, FPL("\\\\aa")},
+      {{FPL("\\\\aa\\"), FPL("")}, FPL("\\\\aa")},
+      {{FPL("\\\\"), FPL("aa")}, FPL("\\\\aa")},
+      {{FPL("/aa/bb"), FPL("cc")}, FPL("/aa/bb\\cc")},
+      {{FPL("/aa/bb/"), FPL("cc")}, FPL("/aa/bb\\cc")},
+      {{FPL("aa/bb/"), FPL("cc")}, FPL("aa/bb\\cc")},
+      {{FPL("aa/bb"), FPL("cc")}, FPL("aa/bb\\cc")},
+      {{FPL("a/b"), FPL("c")}, FPL("a/b\\c")},
+      {{FPL("a/b/"), FPL("c")}, FPL("a/b\\c")},
+      {{FPL("//aa"), FPL("bb")}, FPL("//aa\\bb")},
+      {{FPL("//aa/"), FPL("bb")}, FPL("//aa\\bb")},
+      {{FPL("\\aa\\bb"), FPL("cc")}, FPL("\\aa\\bb\\cc")},
+      {{FPL("\\aa\\bb\\"), FPL("cc")}, FPL("\\aa\\bb\\cc")},
+      {{FPL("aa\\bb\\"), FPL("cc")}, FPL("aa\\bb\\cc")},
+      {{FPL("aa\\bb"), FPL("cc")}, FPL("aa\\bb\\cc")},
+      {{FPL("a\\b"), FPL("c")}, FPL("a\\b\\c")},
+      {{FPL("a\\b\\"), FPL("c")}, FPL("a\\b\\c")},
+      {{FPL("\\\\aa"), FPL("bb")}, FPL("\\\\aa\\bb")},
+      {{FPL("\\\\aa\\"), FPL("bb")}, FPL("\\\\aa\\bb")},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    { { FPL("c:\\"),       FPL("a") },  FPL("c:\\a") },
-    { { FPL("c:\\\\"),     FPL("a") },  FPL("c:\\\\a") },
-    { { FPL("c:\\\\\\"),   FPL("a") },  FPL("c:\\a") },
-    { { FPL("c:\\"),       FPL("") },   FPL("c:\\") },
-    { { FPL("c:\\a"),      FPL("b") },  FPL("c:\\a\\b") },
-    { { FPL("c:\\a\\"),    FPL("b") },  FPL("c:\\a\\b") },
+      {{FPL("c:\\"), FPL("a")}, FPL("c:\\a")},
+      {{FPL("c:\\\\"), FPL("a")}, FPL("c:\\\\a")},
+      {{FPL("c:\\\\\\"), FPL("a")}, FPL("c:\\a")},
+      {{FPL("c:\\"), FPL("")}, FPL("c:\\")},
+      {{FPL("c:\\a"), FPL("b")}, FPL("c:\\a\\b")},
+      {{FPL("c:\\a\\"), FPL("b")}, FPL("c:\\a\\b")},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
-#else  // FILE_PATH_USES_WIN_SEPARATORS
-    { { FPL("/aa/bb"),     FPL("cc") }, FPL("/aa/bb/cc") },
-    { { FPL("/aa/bb/"),    FPL("cc") }, FPL("/aa/bb/cc") },
-    { { FPL("aa/bb/"),     FPL("cc") }, FPL("aa/bb/cc") },
-    { { FPL("aa/bb"),      FPL("cc") }, FPL("aa/bb/cc") },
-    { { FPL("a/b"),        FPL("c") },  FPL("a/b/c") },
-    { { FPL("a/b/"),       FPL("c") },  FPL("a/b/c") },
-    { { FPL("//aa"),       FPL("bb") }, FPL("//aa/bb") },
-    { { FPL("//aa/"),      FPL("bb") }, FPL("//aa/bb") },
+#else   // FILE_PATH_USES_WIN_SEPARATORS
+      {{FPL("/aa/bb"), FPL("cc")}, FPL("/aa/bb/cc")},
+      {{FPL("/aa/bb/"), FPL("cc")}, FPL("/aa/bb/cc")},
+      {{FPL("aa/bb/"), FPL("cc")}, FPL("aa/bb/cc")},
+      {{FPL("aa/bb"), FPL("cc")}, FPL("aa/bb/cc")},
+      {{FPL("a/b"), FPL("c")}, FPL("a/b/c")},
+      {{FPL("a/b/"), FPL("c")}, FPL("a/b/c")},
+      {{FPL("//aa"), FPL("bb")}, FPL("//aa/bb")},
+      {{FPL("//aa/"), FPL("bb")}, FPL("//aa/bb")},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    { { FPL("c:/"),        FPL("a") },  FPL("c:/a") },
-    { { FPL("c:/"),        FPL("") },   FPL("c:/") },
-    { { FPL("c:/a"),       FPL("b") },  FPL("c:/a/b") },
-    { { FPL("c:/a/"),      FPL("b") },  FPL("c:/a/b") },
+      {{FPL("c:/"), FPL("a")}, FPL("c:/a")},
+      {{FPL("c:/"), FPL("")}, FPL("c:/")},
+      {{FPL("c:/a"), FPL("b")}, FPL("c:/a/b")},
+      {{FPL("c:/a/"), FPL("b")}, FPL("c:/a/b")},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #endif  // FILE_PATH_USES_WIN_SEPARATORS
-  };
+  });
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath root(cases[i].inputs[0]);
     FilePath::StringType leaf(cases[i].inputs[1]);
     FilePath observed_str = root.Append(leaf);
-    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed_str.value()) <<
-              "i: " << i << ", root: " << root.value() << ", leaf: " << leaf;
+    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed_str.value())
+        << "i: " << i << ", root: " << root.value() << ", leaf: " << leaf;
     FilePath observed_path = root.Append(FilePath(leaf));
-    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed_path.value()) <<
-              "i: " << i << ", root: " << root.value() << ", leaf: " << leaf;
+    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed_path.value())
+        << "i: " << i << ", root: " << root.value() << ", leaf: " << leaf;
 
     // TODO(erikkay): It would be nice to have a unicode test append value to
     // handle the case when AppendASCII is passed UTF8
@@ -346,190 +348,289 @@
     std::string ascii = leaf;
 #endif
     observed_str = root.AppendASCII(ascii);
-    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed_str.value()) <<
-              "i: " << i << ", root: " << root.value() << ", leaf: " << leaf;
+    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed_str.value())
+        << "i: " << i << ", root: " << root.value() << ", leaf: " << leaf;
   }
 }
 
+// Test UTF8 values within a file path.
+class FilePathUTF8Test : public ::testing::TestWithParam<FilePath::StringType> {
+ protected:
+  FilePath::StringType testcase() const { return GetParam(); }
+};
+
+INSTANTIATE_TEST_SUITE_P(
+    FilePathUTF8TestCases,
+    FilePathUTF8Test,
+    ::testing::Values(FPL("خطأ في عملية التحقق من التحديث 5555"),
+                      FPL("अपडेट जांच में यह गड़बड़ी है 5555"),
+                      FPL("更新確認エラー 5555。")));
+
+TEST_P(FilePathUTF8Test, Test) {
+  FilePath root(FPL(""));
+  FilePath::StringType leaf(testcase());
+  FilePath observed_str = root.Append(leaf);
+  EXPECT_EQ(FilePath::StringType(testcase()), observed_str.value());
+  FilePath observed_path = root.Append(FilePath(leaf));
+  EXPECT_EQ(FilePath::StringType(testcase()), observed_path.value());
+
+#if BUILDFLAG(IS_WIN)
+  std::string utf8 = WideToUTF8(leaf);
+#else
+  std::string utf8 = leaf;
+#endif
+  EXPECT_DCHECK_DEATH({ observed_str = root.AppendASCII(utf8); });
+  EXPECT_DCHECK_DEATH(
+      { observed_str = root.InsertBeforeExtensionASCII(utf8); });
+  EXPECT_DCHECK_DEATH({ observed_str = root.AddExtensionASCII(utf8); });
+
+  observed_str = root.AppendUTF8(utf8);
+  EXPECT_EQ(FilePath::StringType(testcase()), observed_str.value());
+
+  observed_str = root.InsertBeforeExtensionUTF8(utf8);
+  EXPECT_TRUE(observed_str.empty());
+
+  observed_str = root.AddExtensionUTF8(utf8);
+  EXPECT_TRUE(observed_str.empty());
+}
+
+class FilePathUTF8InvalidTest : public ::testing::TestWithParam<std::string> {
+ protected:
+  std::string invalid_utf8_value() const { return GetParam(); }
+};
+
+INSTANTIATE_TEST_SUITE_P(
+    FilePathUTF8InvalidTestCases,
+    FilePathUTF8InvalidTest,
+    ::testing::Values(
+        // Invalid encoding of U+1FFFE (0x8F instead of 0x9F)
+        "\xF0\x8F\xBF\xBE",
+
+        // Surrogate code points
+        "\xED\xA0\x80\xED\xBF\xBF",
+        "\xED\xA0\x8F",
+        "\xED\xBF\xBF",
+
+        // Overlong sequences
+        "\xC0\x80",                  // U+0000
+        "\xC1\x80\xC1\x81",          // "AB"
+        "\xE0\x80\x80",              // U+0000
+        "\xE0\x82\x80",              // U+0080
+        "\xE0\x9F\xBF",              // U+07FF
+        "\xF0\x80\x80\x8D",          // U+000D
+        "\xF0\x80\x82\x91",          // U+0091
+        "\xF0\x80\xA0\x80",          // U+0800
+        "\xF0\x8F\xBB\xBF",          // U+FEFF (BOM)
+        "\xF8\x80\x80\x80\xBF",      // U+003F
+        "\xFC\x80\x80\x80\xA0\xA5",  // U+00A5
+
+        // Beyond U+10FFFF (the upper limit of Unicode codespace)
+        "\xF4\x90\x80\x80",          // U+110000
+        "\xF8\xA0\xBF\x80\xBF",      // 5 bytes
+        "\xFC\x9C\xBF\x80\xBF\x80",  // 6 bytes
+
+        // BOM in UTF-16(BE|LE)
+        "\xFE\xFF",
+        "\xFF\xFE",
+
+        // Strings in legacy encodings. We can certainly make up strings
+        // in a legacy encoding that are valid in UTF-8, but in real data,
+        // most of them are invalid as UTF-8.
+
+        // cafe with U+00E9 in ISO-8859-1
+        "caf\xE9",
+        // U+AC00, U+AC001 in EUC-KR
+        "\xB0\xA1\xB0\xA2",
+        // U+4F60 U+597D in Big5
+        "\xA7\x41\xA6\x6E",
+        // "abc" with U+201[CD] in windows-125[0-8]
+        // clang-format off
+        "\x93" "abc\x94",
+        // clang-format on
+        // U+0639 U+064E U+0644 U+064E in ISO-8859-6
+        "\xD9\xEE\xE4\xEE",
+        // U+03B3 U+03B5 U+03B9 U+03AC in ISO-8859-7
+        "\xE3\xE5\xE9\xDC"));
+
+TEST_P(FilePathUTF8InvalidTest, Test) {
+  FilePath root(FPL(""));
+  FilePath observed_str;
+  EXPECT_DCHECK_DEATH(
+      { observed_str = root.AppendASCII(invalid_utf8_value()); });
+  EXPECT_DCHECK_DEATH({
+    observed_str = root.InsertBeforeExtensionASCII(invalid_utf8_value());
+  });
+  EXPECT_DCHECK_DEATH(
+      { observed_str = root.AddExtensionASCII(invalid_utf8_value()); });
+
+  EXPECT_DCHECK_DEATH(
+      { observed_str = root.AppendUTF8(invalid_utf8_value()); });
+  EXPECT_DCHECK_DEATH(
+      { observed_str = root.InsertBeforeExtensionUTF8(invalid_utf8_value()); });
+  EXPECT_DCHECK_DEATH(
+      { observed_str = root.AddExtensionUTF8(invalid_utf8_value()); });
+}
+
 TEST_F(FilePathTest, StripTrailingSeparators) {
-  const struct UnaryTestData cases[] = {
-    { FPL(""),              FPL("") },
-    { FPL("/"),             FPL("/") },
-    { FPL("//"),            FPL("//") },
-    { FPL("///"),           FPL("/") },
-    { FPL("////"),          FPL("/") },
-    { FPL("a/"),            FPL("a") },
-    { FPL("a//"),           FPL("a") },
-    { FPL("a///"),          FPL("a") },
-    { FPL("a////"),         FPL("a") },
-    { FPL("/a"),            FPL("/a") },
-    { FPL("/a/"),           FPL("/a") },
-    { FPL("/a//"),          FPL("/a") },
-    { FPL("/a///"),         FPL("/a") },
-    { FPL("/a////"),        FPL("/a") },
+  const auto cases = std::to_array<UnaryTestData>({
+      {FPL(""), FPL("")},
+      {FPL("/"), FPL("/")},
+      {FPL("//"), FPL("//")},
+      {FPL("///"), FPL("/")},
+      {FPL("////"), FPL("/")},
+      {FPL("a/"), FPL("a")},
+      {FPL("a//"), FPL("a")},
+      {FPL("a///"), FPL("a")},
+      {FPL("a////"), FPL("a")},
+      {FPL("/a"), FPL("/a")},
+      {FPL("/a/"), FPL("/a")},
+      {FPL("/a//"), FPL("/a")},
+      {FPL("/a///"), FPL("/a")},
+      {FPL("/a////"), FPL("/a")},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    { FPL("c:"),            FPL("c:") },
-    { FPL("c:/"),           FPL("c:/") },
-    { FPL("c://"),          FPL("c://") },
-    { FPL("c:///"),         FPL("c:/") },
-    { FPL("c:////"),        FPL("c:/") },
-    { FPL("c:/a"),          FPL("c:/a") },
-    { FPL("c:/a/"),         FPL("c:/a") },
-    { FPL("c:/a//"),        FPL("c:/a") },
-    { FPL("c:/a///"),       FPL("c:/a") },
-    { FPL("c:/a////"),      FPL("c:/a") },
+      {FPL("c:"), FPL("c:")},
+      {FPL("c:/"), FPL("c:/")},
+      {FPL("c://"), FPL("c://")},
+      {FPL("c:///"), FPL("c:/")},
+      {FPL("c:////"), FPL("c:/")},
+      {FPL("c:/a"), FPL("c:/a")},
+      {FPL("c:/a/"), FPL("c:/a")},
+      {FPL("c:/a//"), FPL("c:/a")},
+      {FPL("c:/a///"), FPL("c:/a")},
+      {FPL("c:/a////"), FPL("c:/a")},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    { FPL("\\"),            FPL("\\") },
-    { FPL("\\\\"),          FPL("\\\\") },
-    { FPL("\\\\\\"),        FPL("\\") },
-    { FPL("\\\\\\\\"),      FPL("\\") },
-    { FPL("a\\"),           FPL("a") },
-    { FPL("a\\\\"),         FPL("a") },
-    { FPL("a\\\\\\"),       FPL("a") },
-    { FPL("a\\\\\\\\"),     FPL("a") },
-    { FPL("\\a"),           FPL("\\a") },
-    { FPL("\\a\\"),         FPL("\\a") },
-    { FPL("\\a\\\\"),       FPL("\\a") },
-    { FPL("\\a\\\\\\"),     FPL("\\a") },
-    { FPL("\\a\\\\\\\\"),   FPL("\\a") },
+      {FPL("\\"), FPL("\\")},
+      {FPL("\\\\"), FPL("\\\\")},
+      {FPL("\\\\\\"), FPL("\\")},
+      {FPL("\\\\\\\\"), FPL("\\")},
+      {FPL("a\\"), FPL("a")},
+      {FPL("a\\\\"), FPL("a")},
+      {FPL("a\\\\\\"), FPL("a")},
+      {FPL("a\\\\\\\\"), FPL("a")},
+      {FPL("\\a"), FPL("\\a")},
+      {FPL("\\a\\"), FPL("\\a")},
+      {FPL("\\a\\\\"), FPL("\\a")},
+      {FPL("\\a\\\\\\"), FPL("\\a")},
+      {FPL("\\a\\\\\\\\"), FPL("\\a")},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    { FPL("c:\\"),          FPL("c:\\") },
-    { FPL("c:\\\\"),        FPL("c:\\\\") },
-    { FPL("c:\\\\\\"),      FPL("c:\\") },
-    { FPL("c:\\\\\\\\"),    FPL("c:\\") },
-    { FPL("c:\\a"),         FPL("c:\\a") },
-    { FPL("c:\\a\\"),       FPL("c:\\a") },
-    { FPL("c:\\a\\\\"),     FPL("c:\\a") },
-    { FPL("c:\\a\\\\\\"),   FPL("c:\\a") },
-    { FPL("c:\\a\\\\\\\\"), FPL("c:\\a") },
+      {FPL("c:\\"), FPL("c:\\")},
+      {FPL("c:\\\\"), FPL("c:\\\\")},
+      {FPL("c:\\\\\\"), FPL("c:\\")},
+      {FPL("c:\\\\\\\\"), FPL("c:\\")},
+      {FPL("c:\\a"), FPL("c:\\a")},
+      {FPL("c:\\a\\"), FPL("c:\\a")},
+      {FPL("c:\\a\\\\"), FPL("c:\\a")},
+      {FPL("c:\\a\\\\\\"), FPL("c:\\a")},
+      {FPL("c:\\a\\\\\\\\"), FPL("c:\\a")},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #endif  // FILE_PATH_USES_WIN_SEPARATORS
-  };
+  });
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath input(cases[i].input);
     FilePath observed = input.StripTrailingSeparators();
-    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed.value()) <<
-              "i: " << i << ", input: " << input.value();
+    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed.value())
+        << "i: " << i << ", input: " << input.value();
   }
 }
 
 TEST_F(FilePathTest, IsAbsoluteOrNetwork) {
-  const struct {
-    FilePath::StringPieceType input;
+  struct Cases {
+    FilePath::StringViewType input;
     bool expected_is_absolute;
     bool expected_is_network;
-  } cases[] = {
-    { FPL(""),       false, false },
-    { FPL("a"),      false, false },
-    { FPL("c:"),     false, false },
-    { FPL("c:a"),    false, false },
-    { FPL("a/b"),    false, false },
-    { FPL("//"),     true,  true },
-    { FPL("//a"),    true,  true },
-    { FPL("c:a/b"),  false, false },
-    { FPL("?:/a"),   false, false },
+  };
+  const auto cases = std::to_array<Cases>({
+      {FPL(""), false, false},       {FPL("a"), false, false},
+      {FPL("c:"), false, false},     {FPL("c:a"), false, false},
+      {FPL("a/b"), false, false},    {FPL("//"), true, true},
+      {FPL("//a"), true, true},      {FPL("c:a/b"), false, false},
+      {FPL("?:/a"), false, false},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    { FPL("/"),      false, false },
-    { FPL("/a"),     false, false },
-    { FPL("/."),     false, false },
-    { FPL("/.."),    false, false },
-    { FPL("c:/"),    true,  false },
-    { FPL("c:/a"),   true,  false },
-    { FPL("c:/."),   true,  false },
-    { FPL("c:/.."),  true,  false },
-    { FPL("C:/a"),   true,  false },
-    { FPL("d:/a"),   true,  false },
+      {FPL("/"), false, false},      {FPL("/a"), false, false},
+      {FPL("/."), false, false},     {FPL("/.."), false, false},
+      {FPL("c:/"), true, false},     {FPL("c:/a"), true, false},
+      {FPL("c:/."), true, false},    {FPL("c:/.."), true, false},
+      {FPL("C:/a"), true, false},    {FPL("d:/a"), true, false},
 #else  // FILE_PATH_USES_DRIVE_LETTERS
-    { FPL("/"),      true,  false },
-    { FPL("/a"),     true,  false },
-    { FPL("/."),     true,  false },
-    { FPL("/.."),    true,  false },
-    { FPL("c:/"),    false, false },
+      {FPL("/"), true, false},
+      {FPL("/a"), true, false},
+      {FPL("/."), true, false},
+      {FPL("/.."), true, false},
+      {FPL("c:/"), false, false},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    { FPL("a\\b"),   false, false },
-    { FPL("\\\\"),   true,  true },
-    { FPL("\\\\a"),  true,  true },
-    { FPL("a\\b"),   false, false },
-    { FPL("\\\\"),   true,  true },
-    { FPL("//a"),    true,  true },
-    { FPL("c:a\\b"), false, false },
-    { FPL("?:\\a"),  false, false },
+      {FPL("a\\b"), false, false},   {FPL("\\\\"), true, true},
+      {FPL("\\\\a"), true, true},    {FPL("a\\b"), false, false},
+      {FPL("\\\\"), true, true},     {FPL("//a"), true, true},
+      {FPL("c:a\\b"), false, false}, {FPL("?:\\a"), false, false},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    { FPL("\\"),     false, false },
-    { FPL("\\a"),    false, false },
-    { FPL("\\."),    false, false },
-    { FPL("\\.."),   false, false },
-    { FPL("c:\\"),   true,  false },
-    { FPL("c:\\"),   true,  false },
-    { FPL("c:\\a"),  true,  false },
-    { FPL("c:\\."),  true,  false },
-    { FPL("c:\\.."), true,  false },
-    { FPL("C:\\a"),  true,  false },
-    { FPL("d:\\a"),  true,  false },
+      {FPL("\\"), false, false},     {FPL("\\a"), false, false},
+      {FPL("\\."), false, false},    {FPL("\\.."), false, false},
+      {FPL("c:\\"), true, false},    {FPL("c:\\"), true, false},
+      {FPL("c:\\a"), true, false},   {FPL("c:\\."), true, false},
+      {FPL("c:\\.."), true, false},  {FPL("C:\\a"), true, false},
+      {FPL("d:\\a"), true, false},
 #else  // FILE_PATH_USES_DRIVE_LETTERS
-    { FPL("\\"),     true,  false },
-    { FPL("\\a"),    true,  false },
-    { FPL("\\."),    true,  false },
-    { FPL("\\.."),   true,  false },
-    { FPL("c:\\"),   false, false },
+      {FPL("\\"), true, false},      {FPL("\\a"), true, false},
+      {FPL("\\."), true, false},     {FPL("\\.."), true, false},
+      {FPL("c:\\"), false, false},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #endif  // FILE_PATH_USES_WIN_SEPARATORS
-  };
+  });
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath input(cases[i].input);
     bool observed_is_absolute = input.IsAbsolute();
-    EXPECT_EQ(cases[i].expected_is_absolute, observed_is_absolute) <<
-              "i: " << i << ", input: " << input.value();
+    EXPECT_EQ(cases[i].expected_is_absolute, observed_is_absolute)
+        << "i: " << i << ", input: " << input.value();
     bool observed_is_network = input.IsNetwork();
-    EXPECT_EQ(cases[i].expected_is_network, observed_is_network) <<
-              "i: " << i << ", input: " << input.value();
+    EXPECT_EQ(cases[i].expected_is_network, observed_is_network)
+        << "i: " << i << ", input: " << input.value();
   }
 }
 
 TEST_F(FilePathTest, PathComponentsTest) {
-  const struct UnaryTestData cases[] = {
-    { FPL("//foo/bar/baz/"),          FPL("|//|foo|bar|baz")},
-    { FPL("///"),                     FPL("|/")},
+  const auto cases = std::to_array<UnaryTestData>({
+      {FPL("//foo/bar/baz/"), FPL("|//|foo|bar|baz")},
+      {FPL("///"), FPL("|/")},
 #if BUILDFLAG(IS_POSIX)
-    {FPL("///foo//bar/baz"),          FPL("|/|foo|bar|baz")},
+      {FPL("///foo//bar/baz"), FPL("|/|foo|bar|baz")},
 #endif  // BUILDFLAG(IS_POSIX)
-    { FPL("/foo//bar//baz/"),         FPL("|/|foo|bar|baz")},
-    { FPL("/foo/bar/baz/"),           FPL("|/|foo|bar|baz")},
-    { FPL("/foo/bar/baz//"),          FPL("|/|foo|bar|baz")},
-    { FPL("/foo/bar/baz///"),         FPL("|/|foo|bar|baz")},
-    { FPL("/foo/bar/baz"),            FPL("|/|foo|bar|baz")},
-    { FPL("/foo/bar.bot/baz.txt"),    FPL("|/|foo|bar.bot|baz.txt")},
-    { FPL("//foo//bar/baz"),          FPL("|//|foo|bar|baz")},
-    { FPL("/"),                       FPL("|/")},
-    { FPL("foo"),                     FPL("|foo")},
-    { FPL(""),                        FPL("")},
+      {FPL("/foo//bar//baz/"), FPL("|/|foo|bar|baz")},
+      {FPL("/foo/bar/baz/"), FPL("|/|foo|bar|baz")},
+      {FPL("/foo/bar/baz//"), FPL("|/|foo|bar|baz")},
+      {FPL("/foo/bar/baz///"), FPL("|/|foo|bar|baz")},
+      {FPL("/foo/bar/baz"), FPL("|/|foo|bar|baz")},
+      {FPL("/foo/bar.bot/baz.txt"), FPL("|/|foo|bar.bot|baz.txt")},
+      {FPL("//foo//bar/baz"), FPL("|//|foo|bar|baz")},
+      {FPL("/"), FPL("|/")},
+      {FPL("foo"), FPL("|foo")},
+      {FPL(""), FPL("")},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    { FPL("e:/foo"),                  FPL("|e:|/|foo")},
-    { FPL("e:/"),                     FPL("|e:|/")},
-    { FPL("e:"),                      FPL("|e:")},
+      {FPL("e:/foo"), FPL("|e:|/|foo")},
+      {FPL("e:/"), FPL("|e:|/")},
+      {FPL("e:"), FPL("|e:")},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    { FPL("../foo"),                  FPL("|..|foo")},
-    { FPL("./foo"),                   FPL("|foo")},
-    { FPL("../foo/bar/"),             FPL("|..|foo|bar") },
-    { FPL("\\\\foo\\bar\\baz\\"),     FPL("|\\\\|foo|bar|baz")},
-    { FPL("\\\\\\"),                  FPL("|\\")},
-    { FPL("\\foo\\\\bar\\\\baz\\"),   FPL("|\\|foo|bar|baz")},
-    { FPL("\\foo\\bar\\baz\\"),       FPL("|\\|foo|bar|baz")},
-    { FPL("\\foo\\bar\\baz\\\\"),     FPL("|\\|foo|bar|baz")},
-    { FPL("\\foo\\bar\\baz\\\\\\"),   FPL("|\\|foo|bar|baz")},
-    { FPL("\\foo\\bar\\baz"),         FPL("|\\|foo|bar|baz")},
-    { FPL("\\foo\\bar/baz\\\\\\"),    FPL("|\\|foo|bar|baz")},
-    { FPL("/foo\\bar\\baz"),          FPL("|/|foo|bar|baz")},
-    { FPL("\\foo\\bar.bot\\baz.txt"), FPL("|\\|foo|bar.bot|baz.txt")},
-    { FPL("\\\\foo\\\\bar\\baz"),     FPL("|\\\\|foo|bar|baz")},
-    { FPL("\\"),                      FPL("|\\")},
+      {FPL("../foo"), FPL("|..|foo")},
+      {FPL("./foo"), FPL("|foo")},
+      {FPL("../foo/bar/"), FPL("|..|foo|bar")},
+      {FPL("\\\\foo\\bar\\baz\\"), FPL("|\\\\|foo|bar|baz")},
+      {FPL("\\\\\\"), FPL("|\\")},
+      {FPL("\\foo\\\\bar\\\\baz\\"), FPL("|\\|foo|bar|baz")},
+      {FPL("\\foo\\bar\\baz\\"), FPL("|\\|foo|bar|baz")},
+      {FPL("\\foo\\bar\\baz\\\\"), FPL("|\\|foo|bar|baz")},
+      {FPL("\\foo\\bar\\baz\\\\\\"), FPL("|\\|foo|bar|baz")},
+      {FPL("\\foo\\bar\\baz"), FPL("|\\|foo|bar|baz")},
+      {FPL("\\foo\\bar/baz\\\\\\"), FPL("|\\|foo|bar|baz")},
+      {FPL("/foo\\bar\\baz"), FPL("|/|foo|bar|baz")},
+      {FPL("\\foo\\bar.bot\\baz.txt"), FPL("|\\|foo|bar.bot|baz.txt")},
+      {FPL("\\\\foo\\\\bar\\baz"), FPL("|\\\\|foo|bar|baz")},
+      {FPL("\\"), FPL("|\\")},
 #endif  // FILE_PATH_USES_WIN_SEPARATORS
-  };
+  });
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath input(cases[i].input);
@@ -540,134 +641,134 @@
       observed.append(FILE_PATH_LITERAL("|"), 1);
       observed.append(j);
     }
-    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed) <<
-              "i: " << i << ", input: " << input.value();
+    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed)
+        << "i: " << i << ", input: " << input.value();
   }
 }
 
 TEST_F(FilePathTest, IsParentTest) {
-  const struct BinaryBooleanTestData cases[] = {
-    { { FPL("/"),             FPL("/foo/bar/baz") },      true},
-    { { FPL("/foo"),          FPL("/foo/bar/baz") },      true},
-    { { FPL("/foo/bar"),      FPL("/foo/bar/baz") },      true},
-    { { FPL("/foo/bar/"),     FPL("/foo/bar/baz") },      true},
-    { { FPL("//foo/bar/"),    FPL("//foo/bar/baz") },     true},
-    { { FPL("/foo/bar"),      FPL("/foo2/bar/baz") },     false},
-    { { FPL("/foo/bar.txt"),  FPL("/foo/bar/baz") },      false},
-    { { FPL("/foo/bar"),      FPL("/foo/bar2/baz") },     false},
-    { { FPL("/foo/bar"),      FPL("/foo/bar") },          false},
-    { { FPL("/foo/bar/baz"),  FPL("/foo/bar") },          false},
-    { { FPL("foo"),           FPL("foo/bar/baz") },       true},
-    { { FPL("foo/bar"),       FPL("foo/bar/baz") },       true},
-    { { FPL("foo/bar"),       FPL("foo2/bar/baz") },      false},
-    { { FPL("foo/bar"),       FPL("foo/bar2/baz") },      false},
-    { { FPL(""),              FPL("foo") },               false},
+  const auto cases = std::to_array<BinaryBooleanTestData>({
+      {{FPL("/"), FPL("/foo/bar/baz")}, true},
+      {{FPL("/foo"), FPL("/foo/bar/baz")}, true},
+      {{FPL("/foo/bar"), FPL("/foo/bar/baz")}, true},
+      {{FPL("/foo/bar/"), FPL("/foo/bar/baz")}, true},
+      {{FPL("//foo/bar/"), FPL("//foo/bar/baz")}, true},
+      {{FPL("/foo/bar"), FPL("/foo2/bar/baz")}, false},
+      {{FPL("/foo/bar.txt"), FPL("/foo/bar/baz")}, false},
+      {{FPL("/foo/bar"), FPL("/foo/bar2/baz")}, false},
+      {{FPL("/foo/bar"), FPL("/foo/bar")}, false},
+      {{FPL("/foo/bar/baz"), FPL("/foo/bar")}, false},
+      {{FPL("foo"), FPL("foo/bar/baz")}, true},
+      {{FPL("foo/bar"), FPL("foo/bar/baz")}, true},
+      {{FPL("foo/bar"), FPL("foo2/bar/baz")}, false},
+      {{FPL("foo/bar"), FPL("foo/bar2/baz")}, false},
+      {{FPL(""), FPL("foo")}, false},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    { { FPL("c:/foo/bar"),    FPL("c:/foo/bar/baz") },    true},
-    { { FPL("E:/foo/bar"),    FPL("e:/foo/bar/baz") },    true},
-    { { FPL("f:/foo/bar"),    FPL("F:/foo/bar/baz") },    true},
-    { { FPL("E:/Foo/bar"),    FPL("e:/foo/bar/baz") },    false},
-    { { FPL("f:/foo/bar"),    FPL("F:/foo/Bar/baz") },    false},
-    { { FPL("c:/"),           FPL("c:/foo/bar/baz") },    true},
-    { { FPL("c:"),            FPL("c:/foo/bar/baz") },    true},
-    { { FPL("c:/foo/bar"),    FPL("d:/foo/bar/baz") },    false},
-    { { FPL("c:/foo/bar"),    FPL("D:/foo/bar/baz") },    false},
-    { { FPL("C:/foo/bar"),    FPL("d:/foo/bar/baz") },    false},
-    { { FPL("c:/foo/bar"),    FPL("c:/foo2/bar/baz") },   false},
-    { { FPL("e:/foo/bar"),    FPL("E:/foo2/bar/baz") },   false},
-    { { FPL("F:/foo/bar"),    FPL("f:/foo2/bar/baz") },   false},
-    { { FPL("c:/foo/bar"),    FPL("c:/foo/bar2/baz") },   false},
+      {{FPL("c:/foo/bar"), FPL("c:/foo/bar/baz")}, true},
+      {{FPL("E:/foo/bar"), FPL("e:/foo/bar/baz")}, true},
+      {{FPL("f:/foo/bar"), FPL("F:/foo/bar/baz")}, true},
+      {{FPL("E:/Foo/bar"), FPL("e:/foo/bar/baz")}, false},
+      {{FPL("f:/foo/bar"), FPL("F:/foo/Bar/baz")}, false},
+      {{FPL("c:/"), FPL("c:/foo/bar/baz")}, true},
+      {{FPL("c:"), FPL("c:/foo/bar/baz")}, true},
+      {{FPL("c:/foo/bar"), FPL("d:/foo/bar/baz")}, false},
+      {{FPL("c:/foo/bar"), FPL("D:/foo/bar/baz")}, false},
+      {{FPL("C:/foo/bar"), FPL("d:/foo/bar/baz")}, false},
+      {{FPL("c:/foo/bar"), FPL("c:/foo2/bar/baz")}, false},
+      {{FPL("e:/foo/bar"), FPL("E:/foo2/bar/baz")}, false},
+      {{FPL("F:/foo/bar"), FPL("f:/foo2/bar/baz")}, false},
+      {{FPL("c:/foo/bar"), FPL("c:/foo/bar2/baz")}, false},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    { { FPL("\\foo\\bar"),    FPL("\\foo\\bar\\baz") },   true},
-    { { FPL("\\foo/bar"),     FPL("\\foo\\bar\\baz") },   true},
-    { { FPL("\\foo/bar"),     FPL("\\foo/bar/baz") },     true},
-    { { FPL("\\"),            FPL("\\foo\\bar\\baz") },   true},
-    { { FPL(""),              FPL("\\foo\\bar\\baz") },   false},
-    { { FPL("\\foo\\bar"),    FPL("\\foo2\\bar\\baz") },  false},
-    { { FPL("\\foo\\bar"),    FPL("\\foo\\bar2\\baz") },  false},
+      {{FPL("\\foo\\bar"), FPL("\\foo\\bar\\baz")}, true},
+      {{FPL("\\foo/bar"), FPL("\\foo\\bar\\baz")}, true},
+      {{FPL("\\foo/bar"), FPL("\\foo/bar/baz")}, true},
+      {{FPL("\\"), FPL("\\foo\\bar\\baz")}, true},
+      {{FPL(""), FPL("\\foo\\bar\\baz")}, false},
+      {{FPL("\\foo\\bar"), FPL("\\foo2\\bar\\baz")}, false},
+      {{FPL("\\foo\\bar"), FPL("\\foo\\bar2\\baz")}, false},
 #endif  // FILE_PATH_USES_WIN_SEPARATORS
-  };
+  });
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath parent(cases[i].inputs[0]);
     FilePath child(cases[i].inputs[1]);
 
-    EXPECT_EQ(parent.IsParent(child), cases[i].expected) <<
-        "i: " << i << ", parent: " << parent.value() << ", child: " <<
-        child.value();
+    EXPECT_EQ(parent.IsParent(child), cases[i].expected)
+        << "i: " << i << ", parent: " << parent.value()
+        << ", child: " << child.value();
   }
 }
 
 TEST_F(FilePathTest, AppendRelativePathTest) {
-  const struct BinaryTestData cases[] = {
+  const auto cases = std::to_array<BinaryTestData>({
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    { { FPL("/"),             FPL("/foo/bar/baz") },      FPL("foo\\bar\\baz")},
-#else  // FILE_PATH_USES_WIN_SEPARATORS
-    { { FPL("/"),             FPL("/foo/bar/baz") },      FPL("foo/bar/baz")},
+      {{FPL("/"), FPL("/foo/bar/baz")}, FPL("foo\\bar\\baz")},
+#else   // FILE_PATH_USES_WIN_SEPARATORS
+      {{FPL("/"), FPL("/foo/bar/baz")}, FPL("foo/bar/baz")},
 #endif  // FILE_PATH_USES_WIN_SEPARATORS
-    { { FPL("/foo/bar"),      FPL("/foo/bar/baz") },      FPL("baz")},
-    { { FPL("/foo/bar/"),     FPL("/foo/bar/baz") },      FPL("baz")},
-    { { FPL("//foo/bar/"),    FPL("//foo/bar/baz") },     FPL("baz")},
-    { { FPL("/foo/bar"),      FPL("/foo2/bar/baz") },     FPL("")},
-    { { FPL("/foo/bar.txt"),  FPL("/foo/bar/baz") },      FPL("")},
-    { { FPL("/foo/bar"),      FPL("/foo/bar2/baz") },     FPL("")},
-    { { FPL("/foo/bar"),      FPL("/foo/bar") },          FPL("")},
-    { { FPL("/foo/bar/baz"),  FPL("/foo/bar") },          FPL("")},
-    { { FPL("foo/bar"),       FPL("foo/bar/baz") },       FPL("baz")},
-    { { FPL("foo/bar"),       FPL("foo2/bar/baz") },      FPL("")},
-    { { FPL("foo/bar"),       FPL("foo/bar2/baz") },      FPL("")},
-    { { FPL(""),              FPL("foo") },               FPL("")},
+      {{FPL("/foo/bar"), FPL("/foo/bar/baz")}, FPL("baz")},
+      {{FPL("/foo/bar/"), FPL("/foo/bar/baz")}, FPL("baz")},
+      {{FPL("//foo/bar/"), FPL("//foo/bar/baz")}, FPL("baz")},
+      {{FPL("/foo/bar"), FPL("/foo2/bar/baz")}, FPL("")},
+      {{FPL("/foo/bar.txt"), FPL("/foo/bar/baz")}, FPL("")},
+      {{FPL("/foo/bar"), FPL("/foo/bar2/baz")}, FPL("")},
+      {{FPL("/foo/bar"), FPL("/foo/bar")}, FPL("")},
+      {{FPL("/foo/bar/baz"), FPL("/foo/bar")}, FPL("")},
+      {{FPL("foo/bar"), FPL("foo/bar/baz")}, FPL("baz")},
+      {{FPL("foo/bar"), FPL("foo2/bar/baz")}, FPL("")},
+      {{FPL("foo/bar"), FPL("foo/bar2/baz")}, FPL("")},
+      {{FPL(""), FPL("foo")}, FPL("")},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    { { FPL("c:/foo/bar"),    FPL("c:/foo/bar/baz") },    FPL("baz")},
-    { { FPL("E:/foo/bar"),    FPL("e:/foo/bar/baz") },    FPL("baz")},
-    { { FPL("f:/foo/bar"),    FPL("F:/foo/bar/baz") },    FPL("baz")},
-    { { FPL("E:/Foo/bar"),    FPL("e:/foo/bar/baz") },    FPL("")},
-    { { FPL("f:/foo/bar"),    FPL("F:/foo/Bar/baz") },    FPL("")},
+      {{FPL("c:/foo/bar"), FPL("c:/foo/bar/baz")}, FPL("baz")},
+      {{FPL("E:/foo/bar"), FPL("e:/foo/bar/baz")}, FPL("baz")},
+      {{FPL("f:/foo/bar"), FPL("F:/foo/bar/baz")}, FPL("baz")},
+      {{FPL("E:/Foo/bar"), FPL("e:/foo/bar/baz")}, FPL("")},
+      {{FPL("f:/foo/bar"), FPL("F:/foo/Bar/baz")}, FPL("")},
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    { { FPL("c:/"),           FPL("c:/foo/bar/baz") },    FPL("foo\\bar\\baz")},
-    // TODO(akalin): Figure out how to handle the corner case in the
-    // commented-out test case below.  Appending to an empty path gives
-    // /foo\bar\baz but appending to a nonempty path "blah" gives
-    // blah\foo\bar\baz.
-    // { { FPL("c:"),            FPL("c:/foo/bar/baz") }, FPL("foo\\bar\\baz")},
+      {{FPL("c:/"), FPL("c:/foo/bar/baz")}, FPL("foo\\bar\\baz")},
+  // TODO(akalin): Figure out how to handle the corner case in the
+  // commented-out test case below.  Appending to an empty path gives
+  // /foo\bar\baz but appending to a nonempty path "blah" gives
+  // blah\foo\bar\baz.
+  // { { FPL("c:"),            FPL("c:/foo/bar/baz") }, FPL("foo\\bar\\baz")},
 #endif  // FILE_PATH_USES_WIN_SEPARATORS
-    { { FPL("c:/foo/bar"),    FPL("d:/foo/bar/baz") },    FPL("")},
-    { { FPL("c:/foo/bar"),    FPL("D:/foo/bar/baz") },    FPL("")},
-    { { FPL("C:/foo/bar"),    FPL("d:/foo/bar/baz") },    FPL("")},
-    { { FPL("c:/foo/bar"),    FPL("c:/foo2/bar/baz") },   FPL("")},
-    { { FPL("e:/foo/bar"),    FPL("E:/foo2/bar/baz") },   FPL("")},
-    { { FPL("F:/foo/bar"),    FPL("f:/foo2/bar/baz") },   FPL("")},
-    { { FPL("c:/foo/bar"),    FPL("c:/foo/bar2/baz") },   FPL("")},
+      {{FPL("c:/foo/bar"), FPL("d:/foo/bar/baz")}, FPL("")},
+      {{FPL("c:/foo/bar"), FPL("D:/foo/bar/baz")}, FPL("")},
+      {{FPL("C:/foo/bar"), FPL("d:/foo/bar/baz")}, FPL("")},
+      {{FPL("c:/foo/bar"), FPL("c:/foo2/bar/baz")}, FPL("")},
+      {{FPL("e:/foo/bar"), FPL("E:/foo2/bar/baz")}, FPL("")},
+      {{FPL("F:/foo/bar"), FPL("f:/foo2/bar/baz")}, FPL("")},
+      {{FPL("c:/foo/bar"), FPL("c:/foo/bar2/baz")}, FPL("")},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    { { FPL("\\foo\\bar"),    FPL("\\foo\\bar\\baz") },   FPL("baz")},
-    { { FPL("\\foo/bar"),     FPL("\\foo\\bar\\baz") },   FPL("baz")},
-    { { FPL("\\foo/bar"),     FPL("\\foo/bar/baz") },     FPL("baz")},
-    { { FPL("\\"),            FPL("\\foo\\bar\\baz") },   FPL("foo\\bar\\baz")},
-    { { FPL(""),              FPL("\\foo\\bar\\baz") },   FPL("")},
-    { { FPL("\\foo\\bar"),    FPL("\\foo2\\bar\\baz") },  FPL("")},
-    { { FPL("\\foo\\bar"),    FPL("\\foo\\bar2\\baz") },  FPL("")},
+      {{FPL("\\foo\\bar"), FPL("\\foo\\bar\\baz")}, FPL("baz")},
+      {{FPL("\\foo/bar"), FPL("\\foo\\bar\\baz")}, FPL("baz")},
+      {{FPL("\\foo/bar"), FPL("\\foo/bar/baz")}, FPL("baz")},
+      {{FPL("\\"), FPL("\\foo\\bar\\baz")}, FPL("foo\\bar\\baz")},
+      {{FPL(""), FPL("\\foo\\bar\\baz")}, FPL("")},
+      {{FPL("\\foo\\bar"), FPL("\\foo2\\bar\\baz")}, FPL("")},
+      {{FPL("\\foo\\bar"), FPL("\\foo\\bar2\\baz")}, FPL("")},
 #endif  // FILE_PATH_USES_WIN_SEPARATORS
 
-    // For network paths, the hosts are compared ignoring case, while the rest
-    // of the path is compared using case.
-    { { FPL("//FOO/bar/"),    FPL("//foo/bar/baz") },     FPL("baz")},
-    { { FPL("//foo/BAR/"),    FPL("//foo/bar/baz") },     FPL("")},
-    // For non-network paths, the first component is not a host and should be
-    // compared using case.
-    { { FPL("/FOO/bar/"),     FPL("/foo/bar/baz") },      FPL("")},
-    // Degenerate case when parent has no hostname.
-    { { FPL("//"),            FPL("//foo") },             FPL("foo")},
+      // For network paths, the hosts are compared ignoring case, while the rest
+      // of the path is compared using case.
+      {{FPL("//FOO/bar/"), FPL("//foo/bar/baz")}, FPL("baz")},
+      {{FPL("//foo/BAR/"), FPL("//foo/bar/baz")}, FPL("")},
+      // For non-network paths, the first component is not a host and should be
+      // compared using case.
+      {{FPL("/FOO/bar/"), FPL("/foo/bar/baz")}, FPL("")},
+      // Degenerate case when parent has no hostname.
+      {{FPL("//"), FPL("//foo")}, FPL("foo")},
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    // Network path tests but using Windows path separators.
-    { { FPL("\\\\FOO\\bar"),  FPL("\\\\foo\\bar\\baz") }, FPL("baz")},
-    { { FPL("\\\\fOO\\Bar"),  FPL("\\\\foo\\bar\\baz") }, FPL("")},
-    { { FPL("\\FOO\\bar"),    FPL("\\foo\\bar\\baz") },   FPL("")},
-    { { FPL("\\\\"),          FPL("\\\\foo") },           FPL("foo")},
+      // Network path tests but using Windows path separators.
+      {{FPL("\\\\FOO\\bar"), FPL("\\\\foo\\bar\\baz")}, FPL("baz")},
+      {{FPL("\\\\fOO\\Bar"), FPL("\\\\foo\\bar\\baz")}, FPL("")},
+      {{FPL("\\FOO\\bar"), FPL("\\foo\\bar\\baz")}, FPL("")},
+      {{FPL("\\\\"), FPL("\\\\foo")}, FPL("foo")},
 #endif  // FILE_PATH_USES_WIN_SEPARATORS
 
-  };
+  });
 
   const FilePath base(FPL("blah"));
 
@@ -690,70 +791,69 @@
       EXPECT_EQ(!cases[i].expected.empty(), success)
           << "i: " << i << ", parent: " << parent.value()
           << ", child: " << child.value();
-      EXPECT_EQ(base.Append(cases[i].expected).value(), result.value()) <<
-        "i: " << i << ", parent: " << parent.value() << ", child: " <<
-        child.value();
+      EXPECT_EQ(base.Append(cases[i].expected).value(), result.value())
+          << "i: " << i << ", parent: " << parent.value()
+          << ", child: " << child.value();
     }
   }
 }
 
 TEST_F(FilePathTest, EqualityTest) {
-  const struct BinaryBooleanTestData cases[] = {
-    { { FPL("/foo/bar/baz"),  FPL("/foo/bar/baz") },      true},
-    { { FPL("/foo/bar"),      FPL("/foo/bar/baz") },      false},
-    { { FPL("/foo/bar/baz"),  FPL("/foo/bar") },          false},
-    { { FPL("//foo/bar/"),    FPL("//foo/bar/") },        true},
-    { { FPL("/foo/bar"),      FPL("/foo2/bar") },         false},
-    { { FPL("/foo/bar.txt"),  FPL("/foo/bar") },          false},
-    { { FPL("foo/bar"),       FPL("foo/bar") },           true},
-    { { FPL("foo/bar"),       FPL("foo/bar/baz") },       false},
-    { { FPL(""),              FPL("foo") },               false},
+  const auto cases = std::to_array<BinaryBooleanTestData>({
+      {{FPL("/foo/bar/baz"), FPL("/foo/bar/baz")}, true},
+      {{FPL("/foo/bar"), FPL("/foo/bar/baz")}, false},
+      {{FPL("/foo/bar/baz"), FPL("/foo/bar")}, false},
+      {{FPL("//foo/bar/"), FPL("//foo/bar/")}, true},
+      {{FPL("/foo/bar"), FPL("/foo2/bar")}, false},
+      {{FPL("/foo/bar.txt"), FPL("/foo/bar")}, false},
+      {{FPL("foo/bar"), FPL("foo/bar")}, true},
+      {{FPL("foo/bar"), FPL("foo/bar/baz")}, false},
+      {{FPL(""), FPL("foo")}, false},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    { { FPL("c:/foo/bar"),    FPL("c:/foo/bar") },        true},
-    { { FPL("E:/foo/bar"),    FPL("e:/foo/bar") },        true},
-    { { FPL("f:/foo/bar"),    FPL("F:/foo/bar") },        true},
-    { { FPL("E:/Foo/bar"),    FPL("e:/foo/bar") },        false},
-    { { FPL("f:/foo/bar"),    FPL("F:/foo/Bar") },        false},
-    { { FPL("c:/"),           FPL("c:/") },               true},
-    { { FPL("c:"),            FPL("c:") },                true},
-    { { FPL("c:/foo/bar"),    FPL("d:/foo/bar") },        false},
-    { { FPL("c:/foo/bar"),    FPL("D:/foo/bar") },        false},
-    { { FPL("C:/foo/bar"),    FPL("d:/foo/bar") },        false},
-    { { FPL("c:/foo/bar"),    FPL("c:/foo2/bar") },       false},
+      {{FPL("c:/foo/bar"), FPL("c:/foo/bar")}, true},
+      {{FPL("E:/foo/bar"), FPL("e:/foo/bar")}, true},
+      {{FPL("f:/foo/bar"), FPL("F:/foo/bar")}, true},
+      {{FPL("E:/Foo/bar"), FPL("e:/foo/bar")}, false},
+      {{FPL("f:/foo/bar"), FPL("F:/foo/Bar")}, false},
+      {{FPL("c:/"), FPL("c:/")}, true},
+      {{FPL("c:"), FPL("c:")}, true},
+      {{FPL("c:/foo/bar"), FPL("d:/foo/bar")}, false},
+      {{FPL("c:/foo/bar"), FPL("D:/foo/bar")}, false},
+      {{FPL("C:/foo/bar"), FPL("d:/foo/bar")}, false},
+      {{FPL("c:/foo/bar"), FPL("c:/foo2/bar")}, false},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    { { FPL("\\foo\\bar"),    FPL("\\foo\\bar") },        true},
-    { { FPL("\\foo/bar"),     FPL("\\foo/bar") },         true},
-    { { FPL("\\foo/bar"),     FPL("\\foo\\bar") },        false},
-    { { FPL("\\"),            FPL("\\") },                true},
-    { { FPL("\\"),            FPL("/") },                 false},
-    { { FPL(""),              FPL("\\") },                false},
-    { { FPL("\\foo\\bar"),    FPL("\\foo2\\bar") },       false},
-    { { FPL("\\foo\\bar"),    FPL("\\foo\\bar2") },       false},
+      {{FPL("\\foo\\bar"), FPL("\\foo\\bar")}, true},
+      {{FPL("\\foo/bar"), FPL("\\foo/bar")}, true},
+      {{FPL("\\foo/bar"), FPL("\\foo\\bar")}, false},
+      {{FPL("\\"), FPL("\\")}, true},
+      {{FPL("\\"), FPL("/")}, false},
+      {{FPL(""), FPL("\\")}, false},
+      {{FPL("\\foo\\bar"), FPL("\\foo2\\bar")}, false},
+      {{FPL("\\foo\\bar"), FPL("\\foo\\bar2")}, false},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    { { FPL("c:\\foo\\bar"),    FPL("c:\\foo\\bar") },    true},
-    { { FPL("E:\\foo\\bar"),    FPL("e:\\foo\\bar") },    true},
-    { { FPL("f:\\foo\\bar"),    FPL("F:\\foo/bar") },     false},
+      {{FPL("c:\\foo\\bar"), FPL("c:\\foo\\bar")}, true},
+      {{FPL("E:\\foo\\bar"), FPL("e:\\foo\\bar")}, true},
+      {{FPL("f:\\foo\\bar"), FPL("F:\\foo/bar")}, false},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #endif  // FILE_PATH_USES_WIN_SEPARATORS
-  };
+  });
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath a(cases[i].inputs[0]);
     FilePath b(cases[i].inputs[1]);
 
-    EXPECT_EQ(a == b, cases[i].expected) <<
-      "equality i: " << i << ", a: " << a.value() << ", b: " <<
-      b.value();
+    EXPECT_EQ(a == b, cases[i].expected)
+        << "equality i: " << i << ", a: " << a.value() << ", b: " << b.value();
   }
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath a(cases[i].inputs[0]);
     FilePath b(cases[i].inputs[1]);
 
-    EXPECT_EQ(a != b, !cases[i].expected) <<
-      "inequality i: " << i << ", a: " << a.value() << ", b: " <<
-      b.value();
+    EXPECT_EQ(a != b, !cases[i].expected)
+        << "inequality i: " << i << ", a: " << a.value()
+        << ", b: " << b.value();
   }
 }
 
@@ -781,7 +881,7 @@
 
 TEST_F(FilePathTest, Extension2) {
   // clang-format off
-  const struct UnaryTestData cases[] = {
+  const auto cases = std::to_array<UnaryTestData>({
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
     { FPL("C:\\a\\b\\c.ext"),        FPL(".ext") },
     { FPL("C:\\a\\b\\c."),           FPL(".") },
@@ -815,8 +915,8 @@
     { FPL("/foo.bar/..////"),        FPL("") },
     { FPL("/foo.1234.luser.js"),     FPL(".js") },
     { FPL("/user.js"),               FPL(".js") },
-  };
-  const struct UnaryTestData double_extension_cases[] = {
+  });
+  const auto double_extension_cases = std::to_array<UnaryTestData>({
     // `kCommonDoubleExtensionSuffixes` cases. Blah is not on that allow-list.
     // Membership is (ASCII) case-insensitive: both ".Z" and ".z" match.
     { FPL("/foo.TAR.bz2"),           FPL(".TAR.bz2") },
@@ -840,7 +940,7 @@
     { FPL("/foo.1234.tar.gz"),       FPL(".tar.gz") },
     { FPL("/foo.tar.tar.gz"),        FPL(".tar.gz") },
     { FPL("/foo.tar.gz.gz"),         FPL(".gz.gz") },
-  };
+  });
   // clang-format on
 
   for (size_t i = 0; i < std::size(cases); ++i) {
@@ -862,65 +962,61 @@
 }
 
 TEST_F(FilePathTest, InsertBeforeExtension) {
-  const struct BinaryTestData cases[] = {
-    { { FPL(""),                FPL("") },        FPL("") },
-    { { FPL(""),                FPL("txt") },     FPL("") },
-    { { FPL("."),               FPL("txt") },     FPL("") },
-    { { FPL(".."),              FPL("txt") },     FPL("") },
-    { { FPL("foo.dll"),         FPL("txt") },     FPL("footxt.dll") },
-    { { FPL("."),               FPL("") },        FPL(".") },
-    { { FPL("foo.dll"),         FPL(".txt") },    FPL("foo.txt.dll") },
-    { { FPL("foo"),             FPL("txt") },     FPL("footxt") },
-    { { FPL("foo"),             FPL(".txt") },    FPL("foo.txt") },
-    { { FPL("foo.baz.dll"),     FPL("txt") },     FPL("foo.baztxt.dll") },
-    { { FPL("foo.baz.dll"),     FPL(".txt") },    FPL("foo.baz.txt.dll") },
-    { { FPL("foo.dll"),         FPL("") },        FPL("foo.dll") },
-    { { FPL("foo.dll"),         FPL(".") },       FPL("foo..dll") },
-    { { FPL("foo"),             FPL("") },        FPL("foo") },
-    { { FPL("foo"),             FPL(".") },       FPL("foo.") },
-    { { FPL("foo.baz.dll"),     FPL("") },        FPL("foo.baz.dll") },
-    { { FPL("foo.baz.dll"),     FPL(".") },       FPL("foo.baz..dll") },
+  const auto cases = std::to_array<BinaryTestData>({
+      {{FPL(""), FPL("")}, FPL("")},
+      {{FPL(""), FPL("txt")}, FPL("")},
+      {{FPL("."), FPL("txt")}, FPL("")},
+      {{FPL(".."), FPL("txt")}, FPL("")},
+      {{FPL("foo.dll"), FPL("txt")}, FPL("footxt.dll")},
+      {{FPL("."), FPL("")}, FPL(".")},
+      {{FPL("foo.dll"), FPL(".txt")}, FPL("foo.txt.dll")},
+      {{FPL("foo"), FPL("txt")}, FPL("footxt")},
+      {{FPL("foo"), FPL(".txt")}, FPL("foo.txt")},
+      {{FPL("foo.baz.dll"), FPL("txt")}, FPL("foo.baztxt.dll")},
+      {{FPL("foo.baz.dll"), FPL(".txt")}, FPL("foo.baz.txt.dll")},
+      {{FPL("foo.dll"), FPL("")}, FPL("foo.dll")},
+      {{FPL("foo.dll"), FPL(".")}, FPL("foo..dll")},
+      {{FPL("foo"), FPL("")}, FPL("foo")},
+      {{FPL("foo"), FPL(".")}, FPL("foo.")},
+      {{FPL("foo.baz.dll"), FPL("")}, FPL("foo.baz.dll")},
+      {{FPL("foo.baz.dll"), FPL(".")}, FPL("foo.baz..dll")},
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    { { FPL("\\"),              FPL("") },        FPL("\\") },
-    { { FPL("\\"),              FPL("txt") },     FPL("\\txt") },
-    { { FPL("\\."),             FPL("txt") },     FPL("") },
-    { { FPL("\\.."),            FPL("txt") },     FPL("") },
-    { { FPL("\\."),             FPL("") },        FPL("\\.") },
-    { { FPL("C:\\bar\\foo.dll"), FPL("txt") },
-        FPL("C:\\bar\\footxt.dll") },
-    { { FPL("C:\\bar.baz\\foodll"), FPL("txt") },
-        FPL("C:\\bar.baz\\foodlltxt") },
-    { { FPL("C:\\bar.baz\\foo.dll"), FPL("txt") },
-        FPL("C:\\bar.baz\\footxt.dll") },
-    { { FPL("C:\\bar.baz\\foo.dll.exe"), FPL("txt") },
-        FPL("C:\\bar.baz\\foo.dlltxt.exe") },
-    { { FPL("C:\\bar.baz\\foo"), FPL("") },
-        FPL("C:\\bar.baz\\foo") },
-    { { FPL("C:\\bar.baz\\foo.exe"), FPL("") },
-        FPL("C:\\bar.baz\\foo.exe") },
-    { { FPL("C:\\bar.baz\\foo.dll.exe"), FPL("") },
-        FPL("C:\\bar.baz\\foo.dll.exe") },
-    { { FPL("C:\\bar\\baz\\foo.exe"), FPL(" (1)") },
-        FPL("C:\\bar\\baz\\foo (1).exe") },
-    { { FPL("C:\\foo.baz\\\\"), FPL(" (1)") },    FPL("C:\\foo (1).baz") },
-    { { FPL("C:\\foo.baz\\..\\"), FPL(" (1)") },  FPL("") },
+      {{FPL("\\"), FPL("")}, FPL("\\")},
+      {{FPL("\\"), FPL("txt")}, FPL("\\txt")},
+      {{FPL("\\."), FPL("txt")}, FPL("")},
+      {{FPL("\\.."), FPL("txt")}, FPL("")},
+      {{FPL("\\."), FPL("")}, FPL("\\.")},
+      {{FPL("C:\\bar\\foo.dll"), FPL("txt")}, FPL("C:\\bar\\footxt.dll")},
+      {{FPL("C:\\bar.baz\\foodll"), FPL("txt")}, FPL("C:\\bar.baz\\foodlltxt")},
+      {{FPL("C:\\bar.baz\\foo.dll"), FPL("txt")},
+       FPL("C:\\bar.baz\\footxt.dll")},
+      {{FPL("C:\\bar.baz\\foo.dll.exe"), FPL("txt")},
+       FPL("C:\\bar.baz\\foo.dlltxt.exe")},
+      {{FPL("C:\\bar.baz\\foo"), FPL("")}, FPL("C:\\bar.baz\\foo")},
+      {{FPL("C:\\bar.baz\\foo.exe"), FPL("")}, FPL("C:\\bar.baz\\foo.exe")},
+      {{FPL("C:\\bar.baz\\foo.dll.exe"), FPL("")},
+       FPL("C:\\bar.baz\\foo.dll.exe")},
+      {{FPL("C:\\bar\\baz\\foo.exe"), FPL(" (1)")},
+       FPL("C:\\bar\\baz\\foo (1).exe")},
+      {{FPL("C:\\foo.baz\\\\"), FPL(" (1)")}, FPL("C:\\foo (1).baz")},
+      {{FPL("C:\\foo.baz\\..\\"), FPL(" (1)")}, FPL("")},
 #endif
-    { { FPL("/"),               FPL("") },        FPL("/") },
-    { { FPL("/"),               FPL("txt") },     FPL("/txt") },
-    { { FPL("/."),              FPL("txt") },     FPL("") },
-    { { FPL("/.."),             FPL("txt") },     FPL("") },
-    { { FPL("/."),              FPL("") },        FPL("/.") },
-    { { FPL("/bar/foo.dll"),    FPL("txt") },     FPL("/bar/footxt.dll") },
-    { { FPL("/bar.baz/foodll"), FPL("txt") },     FPL("/bar.baz/foodlltxt") },
-    { { FPL("/bar.baz/foo.dll"), FPL("txt") },    FPL("/bar.baz/footxt.dll") },
-    { { FPL("/bar.baz/foo.dll.exe"), FPL("txt") },
-        FPL("/bar.baz/foo.dlltxt.exe") },
-    { { FPL("/bar.baz/foo"),    FPL("") },        FPL("/bar.baz/foo") },
-    { { FPL("/bar.baz/foo.exe"), FPL("") },       FPL("/bar.baz/foo.exe") },
-    { { FPL("/bar.baz/foo.dll.exe"), FPL("") },   FPL("/bar.baz/foo.dll.exe") },
-    { { FPL("/bar/baz/foo.exe"), FPL(" (1)") },   FPL("/bar/baz/foo (1).exe") },
-    { { FPL("/bar/baz/..////"), FPL(" (1)") },    FPL("") },
-  };
+      {{FPL("/"), FPL("")}, FPL("/")},
+      {{FPL("/"), FPL("txt")}, FPL("/txt")},
+      {{FPL("/."), FPL("txt")}, FPL("")},
+      {{FPL("/.."), FPL("txt")}, FPL("")},
+      {{FPL("/."), FPL("")}, FPL("/.")},
+      {{FPL("/bar/foo.dll"), FPL("txt")}, FPL("/bar/footxt.dll")},
+      {{FPL("/bar.baz/foodll"), FPL("txt")}, FPL("/bar.baz/foodlltxt")},
+      {{FPL("/bar.baz/foo.dll"), FPL("txt")}, FPL("/bar.baz/footxt.dll")},
+      {{FPL("/bar.baz/foo.dll.exe"), FPL("txt")},
+       FPL("/bar.baz/foo.dlltxt.exe")},
+      {{FPL("/bar.baz/foo"), FPL("")}, FPL("/bar.baz/foo")},
+      {{FPL("/bar.baz/foo.exe"), FPL("")}, FPL("/bar.baz/foo.exe")},
+      {{FPL("/bar.baz/foo.dll.exe"), FPL("")}, FPL("/bar.baz/foo.dll.exe")},
+      {{FPL("/bar/baz/foo.exe"), FPL(" (1)")}, FPL("/bar/baz/foo (1).exe")},
+      {{FPL("/bar/baz/..////"), FPL(" (1)")}, FPL("")},
+  });
   for (unsigned int i = 0; i < std::size(cases); ++i) {
     FilePath path(cases[i].inputs[0]);
     FilePath result = path.InsertBeforeExtension(cases[i].inputs[1]);
@@ -931,35 +1027,35 @@
 }
 
 TEST_F(FilePathTest, RemoveExtension) {
-  const struct UnaryTestData cases[] = {
-    { FPL(""),                    FPL("") },
-    { FPL("."),                   FPL(".") },
-    { FPL(".."),                  FPL("..") },
-    { FPL("foo.dll"),             FPL("foo") },
-    { FPL("./foo.dll"),           FPL("./foo") },
-    { FPL("foo..dll"),            FPL("foo.") },
-    { FPL("foo"),                 FPL("foo") },
-    { FPL("foo."),                FPL("foo") },
-    { FPL("foo.."),               FPL("foo.") },
-    { FPL("foo.baz.dll"),         FPL("foo.baz") },
+  const auto cases = std::to_array<UnaryTestData>({
+      {FPL(""), FPL("")},
+      {FPL("."), FPL(".")},
+      {FPL(".."), FPL("..")},
+      {FPL("foo.dll"), FPL("foo")},
+      {FPL("./foo.dll"), FPL("./foo")},
+      {FPL("foo..dll"), FPL("foo.")},
+      {FPL("foo"), FPL("foo")},
+      {FPL("foo."), FPL("foo")},
+      {FPL("foo.."), FPL("foo.")},
+      {FPL("foo.baz.dll"), FPL("foo.baz")},
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    { FPL("C:\\foo.bar\\foo"),    FPL("C:\\foo.bar\\foo") },
-    { FPL("C:\\foo.bar\\..\\\\"), FPL("C:\\foo.bar\\..\\\\") },
+      {FPL("C:\\foo.bar\\foo"), FPL("C:\\foo.bar\\foo")},
+      {FPL("C:\\foo.bar\\..\\\\"), FPL("C:\\foo.bar\\..\\\\")},
 #endif
-    { FPL("/foo.bar/foo"),        FPL("/foo.bar/foo") },
-    { FPL("/foo.bar/..////"),     FPL("/foo.bar/..////") },
-  };
+      {FPL("/foo.bar/foo"), FPL("/foo.bar/foo")},
+      {FPL("/foo.bar/..////"), FPL("/foo.bar/..////")},
+  });
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath path(cases[i].input);
     FilePath removed = path.RemoveExtension();
     FilePath removed_final = path.RemoveFinalExtension();
-    EXPECT_EQ(cases[i].expected, removed.value()) << "i: " << i <<
-        ", path: " << path.value();
-    EXPECT_EQ(cases[i].expected, removed_final.value()) << "i: " << i <<
-        ", path: " << path.value();
+    EXPECT_EQ(cases[i].expected, removed.value())
+        << "i: " << i << ", path: " << path.value();
+    EXPECT_EQ(cases[i].expected, removed_final.value())
+        << "i: " << i << ", path: " << path.value();
   }
 
-  const FilePath::StringPieceType tarballs[] = {
+  const FilePath::StringViewType tarballs[] = {
       FPL("foo.tar.gz"), FPL("foo.tar.xz"), FPL("foo.tar.bz2"),
       FPL("foo.tar.Z"), FPL("foo.tar.bz")};
   for (size_t i = 0; i < std::size(tarballs); ++i) {
@@ -974,167 +1070,169 @@
 }
 
 TEST_F(FilePathTest, ReplaceExtension) {
-  const struct BinaryTestData cases[] = {
-    { { FPL(""),              FPL("") },      FPL("") },
-    { { FPL(""),              FPL("txt") },   FPL("") },
-    { { FPL("."),             FPL("txt") },   FPL("") },
-    { { FPL(".."),            FPL("txt") },   FPL("") },
-    { { FPL("."),             FPL("") },      FPL("") },
-    { { FPL("foo.dll"),       FPL("txt") },   FPL("foo.txt") },
-    { { FPL("./foo.dll"),     FPL("txt") },   FPL("./foo.txt") },
-    { { FPL("foo..dll"),      FPL("txt") },   FPL("foo..txt") },
-    { { FPL("foo.dll"),       FPL(".txt") },  FPL("foo.txt") },
-    { { FPL("foo"),           FPL("txt") },   FPL("foo.txt") },
-    { { FPL("foo."),          FPL("txt") },   FPL("foo.txt") },
-    { { FPL("foo.."),         FPL("txt") },   FPL("foo..txt") },
-    { { FPL("foo"),           FPL(".txt") },  FPL("foo.txt") },
-    { { FPL("foo.baz.dll"),   FPL("txt") },   FPL("foo.baz.txt") },
-    { { FPL("foo.baz.dll"),   FPL(".txt") },  FPL("foo.baz.txt") },
-    { { FPL("foo.dll"),       FPL("") },      FPL("foo") },
-    { { FPL("foo.dll"),       FPL(".") },     FPL("foo") },
-    { { FPL("foo"),           FPL("") },      FPL("foo") },
-    { { FPL("foo"),           FPL(".") },     FPL("foo") },
-    { { FPL("foo.baz.dll"),   FPL("") },      FPL("foo.baz") },
-    { { FPL("foo.baz.dll"),   FPL(".") },     FPL("foo.baz") },
+  const auto cases = std::to_array<BinaryTestData>({
+      {{FPL(""), FPL("")}, FPL("")},
+      {{FPL(""), FPL("txt")}, FPL("")},
+      {{FPL("."), FPL("txt")}, FPL("")},
+      {{FPL(".."), FPL("txt")}, FPL("")},
+      {{FPL("."), FPL("")}, FPL("")},
+      {{FPL("foo.dll"), FPL("txt")}, FPL("foo.txt")},
+      {{FPL("./foo.dll"), FPL("txt")}, FPL("./foo.txt")},
+      {{FPL("foo..dll"), FPL("txt")}, FPL("foo..txt")},
+      {{FPL("foo.dll"), FPL(".txt")}, FPL("foo.txt")},
+      {{FPL("foo"), FPL("txt")}, FPL("foo.txt")},
+      {{FPL("foo."), FPL("txt")}, FPL("foo.txt")},
+      {{FPL("foo.."), FPL("txt")}, FPL("foo..txt")},
+      {{FPL("foo"), FPL(".txt")}, FPL("foo.txt")},
+      {{FPL("foo.baz.dll"), FPL("txt")}, FPL("foo.baz.txt")},
+      {{FPL("foo.baz.dll"), FPL(".txt")}, FPL("foo.baz.txt")},
+      {{FPL("foo.dll"), FPL("")}, FPL("foo")},
+      {{FPL("foo.dll"), FPL(".")}, FPL("foo")},
+      {{FPL("foo"), FPL("")}, FPL("foo")},
+      {{FPL("foo"), FPL(".")}, FPL("foo")},
+      {{FPL("foo.baz.dll"), FPL("")}, FPL("foo.baz")},
+      {{FPL("foo.baz.dll"), FPL(".")}, FPL("foo.baz")},
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    { { FPL("C:\\foo.bar\\foo"),    FPL("baz") }, FPL("C:\\foo.bar\\foo.baz") },
-    { { FPL("C:\\foo.bar\\..\\\\"), FPL("baz") }, FPL("") },
+      {{FPL("C:\\foo.bar\\foo"), FPL("baz")}, FPL("C:\\foo.bar\\foo.baz")},
+      {{FPL("C:\\foo.bar\\..\\\\"), FPL("baz")}, FPL("")},
 #endif
-    { { FPL("/foo.bar/foo"),        FPL("baz") }, FPL("/foo.bar/foo.baz") },
-    { { FPL("/foo.bar/..////"),     FPL("baz") }, FPL("") },
-  };
+      {{FPL("/foo.bar/foo"), FPL("baz")}, FPL("/foo.bar/foo.baz")},
+      {{FPL("/foo.bar/..////"), FPL("baz")}, FPL("")},
+  });
   for (unsigned int i = 0; i < std::size(cases); ++i) {
     FilePath path(cases[i].inputs[0]);
     FilePath replaced = path.ReplaceExtension(cases[i].inputs[1]);
-    EXPECT_EQ(cases[i].expected, replaced.value()) << "i: " << i <<
-        ", path: " << path.value() << ", replace: " << cases[i].inputs[1];
+    EXPECT_EQ(cases[i].expected, replaced.value())
+        << "i: " << i << ", path: " << path.value()
+        << ", replace: " << cases[i].inputs[1];
   }
 }
 
 TEST_F(FilePathTest, AddExtension) {
-  const struct BinaryTestData cases[] = {
-    { { FPL(""),              FPL("") },      FPL("") },
-    { { FPL(""),              FPL("txt") },   FPL("") },
-    { { FPL("."),             FPL("txt") },   FPL("") },
-    { { FPL(".."),            FPL("txt") },   FPL("") },
-    { { FPL("."),             FPL("") },      FPL("") },
-    { { FPL("foo.dll"),       FPL("txt") },   FPL("foo.dll.txt") },
-    { { FPL("./foo.dll"),     FPL("txt") },   FPL("./foo.dll.txt") },
-    { { FPL("foo..dll"),      FPL("txt") },   FPL("foo..dll.txt") },
-    { { FPL("foo.dll"),       FPL(".txt") },  FPL("foo.dll.txt") },
-    { { FPL("foo"),           FPL("txt") },   FPL("foo.txt") },
-    { { FPL("foo."),          FPL("txt") },   FPL("foo.txt") },
-    { { FPL("foo.."),         FPL("txt") },   FPL("foo..txt") },
-    { { FPL("foo"),           FPL(".txt") },  FPL("foo.txt") },
-    { { FPL("foo.baz.dll"),   FPL("txt") },   FPL("foo.baz.dll.txt") },
-    { { FPL("foo.baz.dll"),   FPL(".txt") },  FPL("foo.baz.dll.txt") },
-    { { FPL("foo.dll"),       FPL("") },      FPL("foo.dll") },
-    { { FPL("foo.dll"),       FPL(".") },     FPL("foo.dll") },
-    { { FPL("foo"),           FPL("") },      FPL("foo") },
-    { { FPL("foo"),           FPL(".") },     FPL("foo") },
-    { { FPL("foo.baz.dll"),   FPL("") },      FPL("foo.baz.dll") },
-    { { FPL("foo.baz.dll"),   FPL(".") },     FPL("foo.baz.dll") },
+  const auto cases = std::to_array<BinaryTestData>({
+      {{FPL(""), FPL("")}, FPL("")},
+      {{FPL(""), FPL("txt")}, FPL("")},
+      {{FPL("."), FPL("txt")}, FPL("")},
+      {{FPL(".."), FPL("txt")}, FPL("")},
+      {{FPL("."), FPL("")}, FPL("")},
+      {{FPL("foo.dll"), FPL("txt")}, FPL("foo.dll.txt")},
+      {{FPL("./foo.dll"), FPL("txt")}, FPL("./foo.dll.txt")},
+      {{FPL("foo..dll"), FPL("txt")}, FPL("foo..dll.txt")},
+      {{FPL("foo.dll"), FPL(".txt")}, FPL("foo.dll.txt")},
+      {{FPL("foo"), FPL("txt")}, FPL("foo.txt")},
+      {{FPL("foo."), FPL("txt")}, FPL("foo.txt")},
+      {{FPL("foo.."), FPL("txt")}, FPL("foo..txt")},
+      {{FPL("foo"), FPL(".txt")}, FPL("foo.txt")},
+      {{FPL("foo.baz.dll"), FPL("txt")}, FPL("foo.baz.dll.txt")},
+      {{FPL("foo.baz.dll"), FPL(".txt")}, FPL("foo.baz.dll.txt")},
+      {{FPL("foo.dll"), FPL("")}, FPL("foo.dll")},
+      {{FPL("foo.dll"), FPL(".")}, FPL("foo.dll")},
+      {{FPL("foo"), FPL("")}, FPL("foo")},
+      {{FPL("foo"), FPL(".")}, FPL("foo")},
+      {{FPL("foo.baz.dll"), FPL("")}, FPL("foo.baz.dll")},
+      {{FPL("foo.baz.dll"), FPL(".")}, FPL("foo.baz.dll")},
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    { { FPL("C:\\foo.bar\\foo"),    FPL("baz") }, FPL("C:\\foo.bar\\foo.baz") },
-    { { FPL("C:\\foo.bar\\..\\\\"), FPL("baz") }, FPL("") },
+      {{FPL("C:\\foo.bar\\foo"), FPL("baz")}, FPL("C:\\foo.bar\\foo.baz")},
+      {{FPL("C:\\foo.bar\\..\\\\"), FPL("baz")}, FPL("")},
 #endif
-    { { FPL("/foo.bar/foo"),        FPL("baz") }, FPL("/foo.bar/foo.baz") },
-    { { FPL("/foo.bar/..////"),     FPL("baz") }, FPL("") },
-  };
+      {{FPL("/foo.bar/foo"), FPL("baz")}, FPL("/foo.bar/foo.baz")},
+      {{FPL("/foo.bar/..////"), FPL("baz")}, FPL("")},
+  });
   for (unsigned int i = 0; i < std::size(cases); ++i) {
     FilePath path(cases[i].inputs[0]);
     FilePath added = path.AddExtension(cases[i].inputs[1]);
-    EXPECT_EQ(cases[i].expected, added.value()) << "i: " << i <<
-        ", path: " << path.value() << ", add: " << cases[i].inputs[1];
+    EXPECT_EQ(cases[i].expected, added.value())
+        << "i: " << i << ", path: " << path.value()
+        << ", add: " << cases[i].inputs[1];
   }
 }
 
 TEST_F(FilePathTest, MatchesExtension) {
-  const struct BinaryBooleanTestData cases[] = {
-    {{FPL("foo"), FPL("")}, true},
-    {{FPL("foo"), FPL(".")}, false},
-    {{FPL("foo."), FPL("")}, false},
-    {{FPL("foo."), FPL(".")}, true},
-    {{FPL("foo.txt"), FPL(".dll")}, false},
-    {{FPL("foo.txt"), FPL(".txt")}, true},
-    {{FPL("foo.txt.dll"), FPL(".txt")}, false},
-    {{FPL("foo.txt.dll"), FPL(".dll")}, true},
-    {{FPL("foo.tar.gz"), FPL(".gz")}, false},
-    {{FPL("foo.tar.lzma"), FPL(".tar.lzma")}, true},
-    {{FPL("foo.TXT"), FPL(".txt")}, true},
-    {{FPL("foo.txt"), FPL(".TXT")}, true},
-    {{FPL("foo.tXt"), FPL(".txt")}, true},
-    {{FPL("foo.txt"), FPL(".tXt")}, true},
-    {{FPL("foo.tXt"), FPL(".TXT")}, true},
-    {{FPL("foo.tXt"), FPL(".tXt")}, true},
+  const auto cases = std::to_array<BinaryBooleanTestData>({
+      {{FPL("foo"), FPL("")}, true},
+      {{FPL("foo"), FPL(".")}, false},
+      {{FPL("foo."), FPL("")}, false},
+      {{FPL("foo."), FPL(".")}, true},
+      {{FPL("foo.txt"), FPL(".dll")}, false},
+      {{FPL("foo.txt"), FPL(".txt")}, true},
+      {{FPL("foo.txt.dll"), FPL(".txt")}, false},
+      {{FPL("foo.txt.dll"), FPL(".dll")}, true},
+      {{FPL("foo.tar.gz"), FPL(".gz")}, false},
+      {{FPL("foo.tar.lzma"), FPL(".tar.lzma")}, true},
+      {{FPL("foo.TXT"), FPL(".txt")}, true},
+      {{FPL("foo.txt"), FPL(".TXT")}, true},
+      {{FPL("foo.tXt"), FPL(".txt")}, true},
+      {{FPL("foo.txt"), FPL(".tXt")}, true},
+      {{FPL("foo.tXt"), FPL(".TXT")}, true},
+      {{FPL("foo.tXt"), FPL(".tXt")}, true},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    {{FPL("c:/foo.txt.dll"), FPL(".txt")}, false},
-    {{FPL("c:/foo.txt"), FPL(".txt")}, true},
+      {{FPL("c:/foo.txt.dll"), FPL(".txt")}, false},
+      {{FPL("c:/foo.txt"), FPL(".txt")}, true},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    {{FPL("c:\\bar\\foo.txt.dll"), FPL(".txt")}, false},
-    {{FPL("c:\\bar\\foo.txt"), FPL(".txt")}, true},
+      {{FPL("c:\\bar\\foo.txt.dll"), FPL(".txt")}, false},
+      {{FPL("c:\\bar\\foo.txt"), FPL(".txt")}, true},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
-    {{FPL("/bar/foo.txt.dll"), FPL(".txt")}, false},
-    {{FPL("/bar/foo.txt"), FPL(".txt")}, true},
+      {{FPL("/bar/foo.txt.dll"), FPL(".txt")}, false},
+      {{FPL("/bar/foo.txt"), FPL(".txt")}, true},
 #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_APPLE)
-    // Umlauts A, O, U: direct comparison, and upper case vs. lower case
-    {{FPL("foo.\u00E4\u00F6\u00FC"), FPL(".\u00E4\u00F6\u00FC")}, true},
-    {{FPL("foo.\u00C4\u00D6\u00DC"), FPL(".\u00E4\u00F6\u00FC")}, true},
-    // C with circumflex: direct comparison, and upper case vs. lower case
-    {{FPL("foo.\u0109"), FPL(".\u0109")}, true},
-    {{FPL("foo.\u0108"), FPL(".\u0109")}, true},
+      // Umlauts A, O, U: direct comparison, and upper case vs. lower case
+      {{FPL("foo.\u00E4\u00F6\u00FC"), FPL(".\u00E4\u00F6\u00FC")}, true},
+      {{FPL("foo.\u00C4\u00D6\u00DC"), FPL(".\u00E4\u00F6\u00FC")}, true},
+      // C with circumflex: direct comparison, and upper case vs. lower case
+      {{FPL("foo.\u0109"), FPL(".\u0109")}, true},
+      {{FPL("foo.\u0108"), FPL(".\u0109")}, true},
 #endif
-  };
+  });
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath path(cases[i].inputs[0]);
     FilePath::StringType ext(cases[i].inputs[1]);
 
-    EXPECT_EQ(cases[i].expected, path.MatchesExtension(ext)) <<
-        "i: " << i << ", path: " << path.value() << ", ext: " << ext;
+    EXPECT_EQ(cases[i].expected, path.MatchesExtension(ext))
+        << "i: " << i << ", path: " << path.value() << ", ext: " << ext;
   }
 }
 
 TEST_F(FilePathTest, MatchesFinalExtension) {
-  const struct BinaryBooleanTestData cases[] = {
-    {{FPL("foo"), FPL("")}, true},
-    {{FPL("foo"), FPL(".")}, false},
-    {{FPL("foo."), FPL("")}, false},
-    {{FPL("foo."), FPL(".")}, true},
-    {{FPL("foo.txt"), FPL(".dll")}, false},
-    {{FPL("foo.txt"), FPL(".txt")}, true},
-    {{FPL("foo.txt.dll"), FPL(".txt")}, false},
-    {{FPL("foo.txt.dll"), FPL(".dll")}, true},
-    {{FPL("foo.tar.gz"), FPL(".gz")}, true},
-    {{FPL("foo.tar.lzma"), FPL(".lzma")}, true},
-    {{FPL("foo.tar.lzma"), FPL(".tar.lzma")}, false},
-    {{FPL("foo.tlzma"), FPL(".tlzma")}, true},
-    {{FPL("foo.TXT"), FPL(".txt")}, true},
-    {{FPL("foo.txt"), FPL(".TXT")}, true},
-    {{FPL("foo.tXt"), FPL(".txt")}, true},
-    {{FPL("foo.txt"), FPL(".tXt")}, true},
-    {{FPL("foo.tXt"), FPL(".TXT")}, true},
-    {{FPL("foo.tXt"), FPL(".tXt")}, true},
+  const auto cases = std::to_array<BinaryBooleanTestData>({
+      {{FPL("foo"), FPL("")}, true},
+      {{FPL("foo"), FPL(".")}, false},
+      {{FPL("foo."), FPL("")}, false},
+      {{FPL("foo."), FPL(".")}, true},
+      {{FPL("foo.txt"), FPL(".dll")}, false},
+      {{FPL("foo.txt"), FPL(".txt")}, true},
+      {{FPL("foo.txt.dll"), FPL(".txt")}, false},
+      {{FPL("foo.txt.dll"), FPL(".dll")}, true},
+      {{FPL("foo.tar.gz"), FPL(".gz")}, true},
+      {{FPL("foo.tar.lzma"), FPL(".lzma")}, true},
+      {{FPL("foo.tar.lzma"), FPL(".tar.lzma")}, false},
+      {{FPL("foo.tlzma"), FPL(".tlzma")}, true},
+      {{FPL("foo.TXT"), FPL(".txt")}, true},
+      {{FPL("foo.txt"), FPL(".TXT")}, true},
+      {{FPL("foo.tXt"), FPL(".txt")}, true},
+      {{FPL("foo.txt"), FPL(".tXt")}, true},
+      {{FPL("foo.tXt"), FPL(".TXT")}, true},
+      {{FPL("foo.tXt"), FPL(".tXt")}, true},
 #if defined(FILE_PATH_USES_DRIVE_LETTERS)
-    {{FPL("c:/foo.txt.dll"), FPL(".txt")}, false},
-    {{FPL("c:/foo.txt"), FPL(".txt")}, true},
+      {{FPL("c:/foo.txt.dll"), FPL(".txt")}, false},
+      {{FPL("c:/foo.txt"), FPL(".txt")}, true},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
-    {{FPL("c:\\bar\\foo.txt.dll"), FPL(".txt")}, false},
-    {{FPL("c:\\bar\\foo.txt"), FPL(".txt")}, true},
+      {{FPL("c:\\bar\\foo.txt.dll"), FPL(".txt")}, false},
+      {{FPL("c:\\bar\\foo.txt"), FPL(".txt")}, true},
 #endif  // FILE_PATH_USES_DRIVE_LETTERS
-    {{FPL("/bar/foo.txt.dll"), FPL(".txt")}, false},
-    {{FPL("/bar/foo.txt"), FPL(".txt")}, true},
+      {{FPL("/bar/foo.txt.dll"), FPL(".txt")}, false},
+      {{FPL("/bar/foo.txt"), FPL(".txt")}, true},
 #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_APPLE)
-    // Umlauts A, O, U: direct comparison, and upper case vs. lower case
-    {{FPL("foo.\u00E4\u00F6\u00FC"), FPL(".\u00E4\u00F6\u00FC")}, true},
-    {{FPL("foo.\u00C4\u00D6\u00DC"), FPL(".\u00E4\u00F6\u00FC")}, true},
-    // C with circumflex: direct comparison, and upper case vs. lower case
-    {{FPL("foo.\u0109"), FPL(".\u0109")}, true},
-    {{FPL("foo.\u0108"), FPL(".\u0109")}, true},
+      // Umlauts A, O, U: direct comparison, and upper case vs. lower case
+      {{FPL("foo.\u00E4\u00F6\u00FC"), FPL(".\u00E4\u00F6\u00FC")}, true},
+      {{FPL("foo.\u00C4\u00D6\u00DC"), FPL(".\u00E4\u00F6\u00FC")}, true},
+      // C with circumflex: direct comparison, and upper case vs. lower case
+      {{FPL("foo.\u0109"), FPL(".\u0109")}, true},
+      {{FPL("foo.\u0108"), FPL(".\u0109")}, true},
 #endif
-  };
+  });
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath path(cases[i].inputs[0]);
@@ -1146,92 +1244,93 @@
 }
 
 TEST_F(FilePathTest, CompareIgnoreCase) {
-  const struct BinaryIntTestData cases[] = {
-    {{FPL("foo"), FPL("foo")}, 0},
-    {{FPL("FOO"), FPL("foo")}, 0},
-    {{FPL("foo.ext"), FPL("foo.ext")}, 0},
-    {{FPL("FOO.EXT"), FPL("foo.ext")}, 0},
-    {{FPL("Foo.Ext"), FPL("foo.ext")}, 0},
-    {{FPL("foO"), FPL("foo")}, 0},
-    {{FPL("foo"), FPL("foO")}, 0},
-    {{FPL("fOo"), FPL("foo")}, 0},
-    {{FPL("foo"), FPL("fOo")}, 0},
-    {{FPL("bar"), FPL("foo")}, -1},
-    {{FPL("foo"), FPL("bar")}, 1},
-    {{FPL("BAR"), FPL("foo")}, -1},
-    {{FPL("FOO"), FPL("bar")}, 1},
-    {{FPL("bar"), FPL("FOO")}, -1},
-    {{FPL("foo"), FPL("BAR")}, 1},
-    {{FPL("BAR"), FPL("FOO")}, -1},
-    {{FPL("FOO"), FPL("BAR")}, 1},
-    // German "Eszett" (lower case and the new-fangled upper case)
-    // Note that uc(<lowercase eszett>) => "SS", NOT <uppercase eszett>!
-    // However, neither Windows nor Mac OSX converts these.
-    // (or even have glyphs for <uppercase eszett>)
-    {{FPL("\u00DF"), FPL("\u00DF")}, 0},
-    {{FPL("\u1E9E"), FPL("\u1E9E")}, 0},
-    {{FPL("\u00DF"), FPL("\u1E9E")}, -1},
-    {{FPL("SS"), FPL("\u00DF")}, -1},
-    {{FPL("SS"), FPL("\u1E9E")}, -1},
+  const auto cases = std::to_array<BinaryIntTestData>({
+      {{FPL("foo"), FPL("foo")}, 0},
+      {{FPL("FOO"), FPL("foo")}, 0},
+      {{FPL("foo.ext"), FPL("foo.ext")}, 0},
+      {{FPL("FOO.EXT"), FPL("foo.ext")}, 0},
+      {{FPL("Foo.Ext"), FPL("foo.ext")}, 0},
+      {{FPL("foO"), FPL("foo")}, 0},
+      {{FPL("foo"), FPL("foO")}, 0},
+      {{FPL("fOo"), FPL("foo")}, 0},
+      {{FPL("foo"), FPL("fOo")}, 0},
+      {{FPL("bar"), FPL("foo")}, -1},
+      {{FPL("foo"), FPL("bar")}, 1},
+      {{FPL("BAR"), FPL("foo")}, -1},
+      {{FPL("FOO"), FPL("bar")}, 1},
+      {{FPL("bar"), FPL("FOO")}, -1},
+      {{FPL("foo"), FPL("BAR")}, 1},
+      {{FPL("BAR"), FPL("FOO")}, -1},
+      {{FPL("FOO"), FPL("BAR")}, 1},
+      // German "Eszett" (lower case and the new-fangled upper case)
+      // Note that uc(<lowercase eszett>) => "SS", NOT <uppercase eszett>!
+      // However, neither Windows nor Mac OSX converts these.
+      // (or even have glyphs for <uppercase eszett>)
+      {{FPL("\u00DF"), FPL("\u00DF")}, 0},
+      {{FPL("\u1E9E"), FPL("\u1E9E")}, 0},
+      {{FPL("\u00DF"), FPL("\u1E9E")}, -1},
+      {{FPL("SS"), FPL("\u00DF")}, -1},
+      {{FPL("SS"), FPL("\u1E9E")}, -1},
 #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_APPLE)
-    // Umlauts A, O, U: direct comparison, and upper case vs. lower case
-    {{FPL("\u00E4\u00F6\u00FC"), FPL("\u00E4\u00F6\u00FC")}, 0},
-    {{FPL("\u00C4\u00D6\u00DC"), FPL("\u00E4\u00F6\u00FC")}, 0},
-    // C with circumflex: direct comparison, and upper case vs. lower case
-    {{FPL("\u0109"), FPL("\u0109")}, 0},
-    {{FPL("\u0108"), FPL("\u0109")}, 0},
-    // Cyrillic letter SHA: direct comparison, and upper case vs. lower case
-    {{FPL("\u0428"), FPL("\u0428")}, 0},
-    {{FPL("\u0428"), FPL("\u0448")}, 0},
-    // Greek letter DELTA: direct comparison, and upper case vs. lower case
-    {{FPL("\u0394"), FPL("\u0394")}, 0},
-    {{FPL("\u0394"), FPL("\u03B4")}, 0},
-    // Japanese full-width A: direct comparison, and upper case vs. lower case
-    // Note that full-width and standard characters are considered different.
-    {{FPL("\uFF21"), FPL("\uFF21")}, 0},
-    {{FPL("\uFF21"), FPL("\uFF41")}, 0},
-    {{FPL("A"), FPL("\uFF21")}, -1},
-    {{FPL("A"), FPL("\uFF41")}, -1},
-    {{FPL("a"), FPL("\uFF21")}, -1},
-    {{FPL("a"), FPL("\uFF41")}, -1},
+      // Umlauts A, O, U: direct comparison, and upper case vs. lower case
+      {{FPL("\u00E4\u00F6\u00FC"), FPL("\u00E4\u00F6\u00FC")}, 0},
+      {{FPL("\u00C4\u00D6\u00DC"), FPL("\u00E4\u00F6\u00FC")}, 0},
+      // C with circumflex: direct comparison, and upper case vs. lower case
+      {{FPL("\u0109"), FPL("\u0109")}, 0},
+      {{FPL("\u0108"), FPL("\u0109")}, 0},
+      // Cyrillic letter SHA: direct comparison, and upper case vs. lower case
+      {{FPL("\u0428"), FPL("\u0428")}, 0},
+      {{FPL("\u0428"), FPL("\u0448")}, 0},
+      // Greek letter DELTA: direct comparison, and upper case vs. lower case
+      {{FPL("\u0394"), FPL("\u0394")}, 0},
+      {{FPL("\u0394"), FPL("\u03B4")}, 0},
+      // Japanese full-width A: direct comparison, and upper case vs. lower case
+      // Note that full-width and standard characters are considered different.
+      {{FPL("\uFF21"), FPL("\uFF21")}, 0},
+      {{FPL("\uFF21"), FPL("\uFF41")}, 0},
+      {{FPL("A"), FPL("\uFF21")}, -1},
+      {{FPL("A"), FPL("\uFF41")}, -1},
+      {{FPL("a"), FPL("\uFF21")}, -1},
+      {{FPL("a"), FPL("\uFF41")}, -1},
 #endif
 #if BUILDFLAG(IS_APPLE)
-    // Codepoints > 0x1000
-    // Georgian letter DON: direct comparison, and upper case vs. lower case
-    {{FPL("\u10A3"), FPL("\u10A3")}, 0},
-    {{FPL("\u10A3"), FPL("\u10D3")}, 0},
-    // Combining characters vs. pre-composed characters, upper and lower case
-    {{FPL("k\u0301u\u032Do\u0304\u0301n"), FPL("\u1E31\u1E77\u1E53n")}, 0},
-    {{FPL("k\u0301u\u032Do\u0304\u0301n"), FPL("kuon")}, 1},
-    {{FPL("kuon"), FPL("k\u0301u\u032Do\u0304\u0301n")}, -1},
-    {{FPL("K\u0301U\u032DO\u0304\u0301N"), FPL("KUON")}, 1},
-    {{FPL("KUON"), FPL("K\u0301U\u032DO\u0304\u0301N")}, -1},
-    {{FPL("k\u0301u\u032Do\u0304\u0301n"), FPL("KUON")}, 1},
-    {{FPL("K\u0301U\u032DO\u0304\u0301N"), FPL("\u1E31\u1E77\u1E53n")}, 0},
-    {{FPL("k\u0301u\u032Do\u0304\u0301n"), FPL("\u1E30\u1E76\u1E52n")}, 0},
-    {{FPL("k\u0301u\u032Do\u0304\u0302n"), FPL("\u1E30\u1E76\u1E52n")}, 1},
+      // Codepoints > 0x1000
+      // Georgian letter DON: direct comparison, and upper case vs. lower case
+      {{FPL("\u10A3"), FPL("\u10A3")}, 0},
+      {{FPL("\u10A3"), FPL("\u10D3")}, 0},
+      // Combining characters vs. pre-composed characters, upper and lower case
+      {{FPL("k\u0301u\u032Do\u0304\u0301n"), FPL("\u1E31\u1E77\u1E53n")}, 0},
+      {{FPL("k\u0301u\u032Do\u0304\u0301n"), FPL("kuon")}, 1},
+      {{FPL("kuon"), FPL("k\u0301u\u032Do\u0304\u0301n")}, -1},
+      {{FPL("K\u0301U\u032DO\u0304\u0301N"), FPL("KUON")}, 1},
+      {{FPL("KUON"), FPL("K\u0301U\u032DO\u0304\u0301N")}, -1},
+      {{FPL("k\u0301u\u032Do\u0304\u0301n"), FPL("KUON")}, 1},
+      {{FPL("K\u0301U\u032DO\u0304\u0301N"), FPL("\u1E31\u1E77\u1E53n")}, 0},
+      {{FPL("k\u0301u\u032Do\u0304\u0301n"), FPL("\u1E30\u1E76\u1E52n")}, 0},
+      {{FPL("k\u0301u\u032Do\u0304\u0302n"), FPL("\u1E30\u1E76\u1E52n")}, 1},
 
-    // Codepoints > 0xFFFF
-    // Here, we compare the `Adlam Letter Shu` in its capital and small version.
-    {{FPL("\U0001E921"), FPL("\U0001E943")}, -1},
-    {{FPL("\U0001E943"), FPL("\U0001E921")}, 1},
-    {{FPL("\U0001E921"), FPL("\U0001E921")}, 0},
-    {{FPL("\U0001E943"), FPL("\U0001E943")}, 0},
+      // Codepoints > 0xFFFF
+      // Here, we compare the `Adlam Letter Shu` in its capital and small
+      // version.
+      {{FPL("\U0001E921"), FPL("\U0001E943")}, -1},
+      {{FPL("\U0001E943"), FPL("\U0001E921")}, 1},
+      {{FPL("\U0001E921"), FPL("\U0001E921")}, 0},
+      {{FPL("\U0001E943"), FPL("\U0001E943")}, 0},
 #endif
-  };
+  });
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath::StringType s1(cases[i].inputs[0]);
     FilePath::StringType s2(cases[i].inputs[1]);
     int result = FilePath::CompareIgnoreCase(s1, s2);
-    EXPECT_EQ(cases[i].expected, result) <<
-        "i: " << i << ", s1: " << s1 << ", s2: " << s2;
+    EXPECT_EQ(cases[i].expected, result)
+        << "i: " << i << ", s1: " << s1 << ", s2: " << s2;
   }
 }
 
 TEST_F(FilePathTest, ReferencesParent) {
   // clang-format off
-  const struct UnaryBooleanTestData cases[] = {
+  const auto cases = std::to_array<UnaryBooleanTestData>({
     { FPL("."),        false },
     { FPL(".."),       true },
 #if BUILDFLAG(IS_WIN)
@@ -1260,22 +1359,22 @@
     { FPL("a/b/../"),  true },
     { FPL("a/../c"),   true },
     { FPL("a/b/c"),    false },
-  };
+  });
   // clang-format on
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath input(cases[i].input);
     bool observed = input.ReferencesParent();
-    EXPECT_EQ(cases[i].expected, observed) <<
-              "i: " << i << ", input: " << input.value();
+    EXPECT_EQ(cases[i].expected, observed)
+        << "i: " << i << ", input: " << input.value();
   }
 }
 
 TEST_F(FilePathTest, FromASCII) {
-  const struct UTF8TestData cases[] = {
+  const auto cases = std::to_array<UTF8TestData>({
       {FPL("foo.txt"), "foo.txt"},
       {FPL("!#$%&'()"), "!#$%&'()"},
-  };
+  });
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath from_ascii = FilePath::FromASCII(cases[i].utf8);
@@ -1285,14 +1384,14 @@
 }
 
 TEST_F(FilePathTest, FromUTF8Unsafe_And_AsUTF8Unsafe) {
-  const struct UTF8TestData cases[] = {
-    { FPL("foo.txt"), "foo.txt" },
-    // "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them.
-    { FPL("\u00E0\u00E8\u00F2.txt"), "\xC3\xA0\xC3\xA8\xC3\xB2.txt" },
-    // Full-width "ABC".
-    { FPL("\uFF21\uFF22\uFF23.txt"),
-      "\xEF\xBC\xA1\xEF\xBC\xA2\xEF\xBC\xA3.txt" },
-  };
+  const auto cases = std::to_array<UTF8TestData>({
+      {FPL("foo.txt"), "foo.txt"},
+      // "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them.
+      {FPL("\u00E0\u00E8\u00F2.txt"), "\xC3\xA0\xC3\xA8\xC3\xB2.txt"},
+      // Full-width "ABC".
+      {FPL("\uFF21\uFF22\uFF23.txt"),
+       "\xEF\xBC\xA1\xEF\xBC\xA2\xEF\xBC\xA3.txt"},
+  });
 
 #if !defined(SYSTEM_NATIVE_UTF8) && \
     (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS))
@@ -1362,54 +1461,51 @@
 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
 TEST_F(FilePathTest, NormalizePathSeparators) {
   const struct UnaryTestData cases[] = {
-    { FPL("foo/bar"), FPL("foo\\bar") },
-    { FPL("foo/bar\\betz"), FPL("foo\\bar\\betz") },
-    { FPL("foo\\bar"), FPL("foo\\bar") },
-    { FPL("foo\\bar/betz"), FPL("foo\\bar\\betz") },
-    { FPL("foo"), FPL("foo") },
-    // Trailing slashes don't automatically get stripped.  That's what
-    // StripTrailingSeparators() is for.
-    { FPL("foo\\"), FPL("foo\\") },
-    { FPL("foo/"), FPL("foo\\") },
-    { FPL("foo/bar\\"), FPL("foo\\bar\\") },
-    { FPL("foo\\bar/"), FPL("foo\\bar\\") },
-    { FPL("foo/bar/"), FPL("foo\\bar\\") },
-    { FPL("foo\\bar\\"), FPL("foo\\bar\\") },
-    { FPL("\\foo/bar"), FPL("\\foo\\bar") },
-    { FPL("/foo\\bar"), FPL("\\foo\\bar") },
-    { FPL("c:/foo/bar/"), FPL("c:\\foo\\bar\\") },
-    { FPL("/foo/bar/"), FPL("\\foo\\bar\\") },
-    { FPL("\\foo\\bar\\"), FPL("\\foo\\bar\\") },
-    { FPL("c:\\foo/bar"), FPL("c:\\foo\\bar") },
-    { FPL("//foo\\bar\\"), FPL("\\\\foo\\bar\\") },
-    { FPL("\\\\foo\\bar\\"), FPL("\\\\foo\\bar\\") },
-    { FPL("//foo\\bar\\"), FPL("\\\\foo\\bar\\") },
-    // This method does not normalize the number of path separators.
-    { FPL("foo\\\\bar"), FPL("foo\\\\bar") },
-    { FPL("foo//bar"), FPL("foo\\\\bar") },
-    { FPL("foo/\\bar"), FPL("foo\\\\bar") },
-    { FPL("foo\\/bar"), FPL("foo\\\\bar") },
-    { FPL("///foo\\\\bar"), FPL("\\\\\\foo\\\\bar") },
-    { FPL("foo//bar///"), FPL("foo\\\\bar\\\\\\") },
-    { FPL("foo/\\bar/\\"), FPL("foo\\\\bar\\\\") },
-    { FPL("/\\foo\\/bar"), FPL("\\\\foo\\\\bar") },
+      {FPL("foo/bar"), FPL("foo\\bar")},
+      {FPL("foo/bar\\betz"), FPL("foo\\bar\\betz")},
+      {FPL("foo\\bar"), FPL("foo\\bar")},
+      {FPL("foo\\bar/betz"), FPL("foo\\bar\\betz")},
+      {FPL("foo"), FPL("foo")},
+      // Trailing slashes don't automatically get stripped.  That's what
+      // StripTrailingSeparators() is for.
+      {FPL("foo\\"), FPL("foo\\")},
+      {FPL("foo/"), FPL("foo\\")},
+      {FPL("foo/bar\\"), FPL("foo\\bar\\")},
+      {FPL("foo\\bar/"), FPL("foo\\bar\\")},
+      {FPL("foo/bar/"), FPL("foo\\bar\\")},
+      {FPL("foo\\bar\\"), FPL("foo\\bar\\")},
+      {FPL("\\foo/bar"), FPL("\\foo\\bar")},
+      {FPL("/foo\\bar"), FPL("\\foo\\bar")},
+      {FPL("c:/foo/bar/"), FPL("c:\\foo\\bar\\")},
+      {FPL("/foo/bar/"), FPL("\\foo\\bar\\")},
+      {FPL("\\foo\\bar\\"), FPL("\\foo\\bar\\")},
+      {FPL("c:\\foo/bar"), FPL("c:\\foo\\bar")},
+      {FPL("//foo\\bar\\"), FPL("\\\\foo\\bar\\")},
+      {FPL("\\\\foo\\bar\\"), FPL("\\\\foo\\bar\\")},
+      {FPL("//foo\\bar\\"), FPL("\\\\foo\\bar\\")},
+      // This method does not normalize the number of path separators.
+      {FPL("foo\\\\bar"), FPL("foo\\\\bar")},
+      {FPL("foo//bar"), FPL("foo\\\\bar")},
+      {FPL("foo/\\bar"), FPL("foo\\\\bar")},
+      {FPL("foo\\/bar"), FPL("foo\\\\bar")},
+      {FPL("///foo\\\\bar"), FPL("\\\\\\foo\\\\bar")},
+      {FPL("foo//bar///"), FPL("foo\\\\bar\\\\\\")},
+      {FPL("foo/\\bar/\\"), FPL("foo\\\\bar\\\\")},
+      {FPL("/\\foo\\/bar"), FPL("\\\\foo\\\\bar")},
   };
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath input(cases[i].input);
     FilePath observed = input.NormalizePathSeparators();
-    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed.value()) <<
-              "i: " << i << ", input: " << input.value();
+    EXPECT_EQ(FilePath::StringType(cases[i].expected), observed.value())
+        << "i: " << i << ", input: " << input.value();
   }
 }
 #endif
 
 TEST_F(FilePathTest, EndsWithSeparator) {
   const UnaryBooleanTestData cases[] = {
-    { FPL(""), false },
-    { FPL("/"), true },
-    { FPL("foo/"), true },
-    { FPL("bar"), false },
-    { FPL("/foo/bar"), false },
+      {FPL(""), false},    {FPL("/"), true},         {FPL("foo/"), true},
+      {FPL("bar"), false}, {FPL("/foo/bar"), false},
   };
   for (const auto& i : cases) {
     FilePath input = FilePath(i.input).NormalizePathSeparators();
@@ -1418,12 +1514,10 @@
 }
 
 TEST_F(FilePathTest, AsEndingWithSeparator) {
-  const UnaryTestData cases[] = {
-    { FPL(""), FPL("") },
-    { FPL("/"), FPL("/") },
-    { FPL("foo"), FPL("foo/") },
-    { FPL("foo/"), FPL("foo/") }
-  };
+  const UnaryTestData cases[] = {{FPL(""), FPL("")},
+                                 {FPL("/"), FPL("/")},
+                                 {FPL("foo"), FPL("foo/")},
+                                 {FPL("foo/"), FPL("foo/")}};
   for (const auto& i : cases) {
     FilePath input = FilePath(i.input).NormalizePathSeparators();
     FilePath expected = FilePath(i.expected).NormalizePathSeparators();
@@ -1434,28 +1528,28 @@
 #if BUILDFLAG(IS_ANDROID)
 TEST_F(FilePathTest, ContentUriTest) {
   const struct UnaryBooleanTestData cases[] = {
-    { FPL("content://foo.bar"),    true },
-    { FPL("content://foo.bar/"),   true },
-    { FPL("content://foo/bar"),    true },
-    { FPL("CoNTenT://foo.bar"),    true },
-    { FPL("content://"),           true },
-    { FPL("content:///foo.bar"),   true },
-    { FPL("content://3foo/bar"),   true },
-    { FPL("content://_foo/bar"),   true },
-    { FPL(".. "),                  false },
-    { FPL("foo.bar"),              false },
-    { FPL("content:foo.bar"),      false },
-    { FPL("content:/foo.ba"),      false },
-    { FPL("content:/dir/foo.bar"), false },
-    { FPL("content: //foo.bar"),   false },
-    { FPL("content%2a%2f%2f"),     false },
+      {FPL("content://foo.bar"), true},
+      {FPL("content://foo.bar/"), true},
+      {FPL("content://foo/bar"), true},
+      {FPL("CoNTenT://foo.bar"), true},
+      {FPL("content://"), true},
+      {FPL("content:///foo.bar"), true},
+      {FPL("content://3foo/bar"), true},
+      {FPL("content://_foo/bar"), true},
+      {FPL(".. "), false},
+      {FPL("foo.bar"), false},
+      {FPL("content:foo.bar"), false},
+      {FPL("content:/foo.ba"), false},
+      {FPL("content:/dir/foo.bar"), false},
+      {FPL("content: //foo.bar"), false},
+      {FPL("content%2a%2f%2f"), false},
   };
 
   for (size_t i = 0; i < std::size(cases); ++i) {
     FilePath input(cases[i].input);
     bool observed = input.IsContentUri();
-    EXPECT_EQ(cases[i].expected, observed) <<
-              "i: " << i << ", input: " << input.value();
+    EXPECT_EQ(cases[i].expected, observed)
+        << "i: " << i << ", input: " << input.value();
   }
 }
 #endif
@@ -1479,15 +1573,12 @@
 #if BUILDFLAG(IS_APPLE)
 TEST_F(FilePathTest, GetHFSDecomposedFormWithInvalidInput) {
   const FilePath::CharType* cases[] = {
-    FPL("\xc3\x28"),
-    FPL("\xe2\x82\x28"),
-    FPL("\xe2\x28\xa1"),
-    FPL("\xf0\x28\x8c\xbc"),
-    FPL("\xf0\x28\x8c\x28"),
+      FPL("\xc3\x28"),         FPL("\xe2\x82\x28"),     FPL("\xe2\x28\xa1"),
+      FPL("\xf0\x28\x8c\xbc"), FPL("\xf0\x28\x8c\x28"),
   };
   for (auto* invalid_input : cases) {
-    FilePath::StringType observed = FilePath::GetHFSDecomposedForm(
-        invalid_input);
+    FilePath::StringType observed =
+        FilePath::GetHFSDecomposedForm(invalid_input);
     EXPECT_TRUE(observed.empty());
   }
 }
diff --git a/tot/base/files/file_path_watcher_fsevents.cc b/tot/base/files/file_path_watcher_fsevents.cc
index c0fc6e9..5e7ce58 100644
--- a/tot/base/files/file_path_watcher_fsevents.cc
+++ b/tot/base/files/file_path_watcher_fsevents.cc
@@ -36,8 +36,8 @@
   const unsigned kMaxLinksToResolve = 255;
 
   std::vector<FilePath::StringType> component_vector = path.GetComponents();
-  std::list<FilePath::StringType>
-      components(component_vector.begin(), component_vector.end());
+  std::list<FilePath::StringType> components(component_vector.begin(),
+                                             component_vector.end());
 
   FilePath result;
   unsigned resolve_count = 0;
@@ -54,8 +54,9 @@
 
     FilePath target;
     if (ReadSymbolicLink(current, &target)) {
-      if (target.IsAbsolute())
+      if (target.IsAbsolute()) {
         result.clear();
+      }
       std::vector<FilePath::StringType> target_components =
           target.GetComponents();
       components.insert(components.begin(), target_components.begin(),
@@ -66,8 +67,9 @@
     }
   }
 
-  if (resolve_count >= kMaxLinksToResolve)
+  if (resolve_count >= kMaxLinksToResolve) {
     result.clear();
+  }
   return result;
 }
 
@@ -93,8 +95,9 @@
 
   // This class could support non-recursive watches, but that is currently
   // left to FilePathWatcherKQueue.
-  if (type != Type::kRecursive)
+  if (type != Type::kRecursive) {
     return false;
+  }
 
   set_task_runner(SequencedTaskRunner::GetCurrentDefault());
   callback_ = callback;
@@ -142,12 +145,14 @@
   std::vector<FilePath> paths;
   FSEventStreamEventId root_change_at = FSEventStreamGetLatestEventId(stream);
   for (size_t i = 0; i < num_events; i++) {
-    if (flags[i] & kFSEventStreamEventFlagRootChanged)
+    if (flags[i] & kFSEventStreamEventFlagRootChanged) {
       root_changed = true;
-    if (event_ids[i])
+    }
+    if (event_ids[i]) {
       root_change_at = std::min(root_change_at, event_ids[i]);
-    paths.push_back(FilePath(
-        reinterpret_cast<char**>(event_paths)[i]).StripTrailingSeparators());
+    }
+    paths.push_back(FilePath(reinterpret_cast<char**>(event_paths)[i])
+                        .StripTrailingSeparators());
   }
 
   // Reinitialize the event stream if we find changes to the root. This is
@@ -169,8 +174,9 @@
         FROM_HERE, BindOnce(
                        [](WeakPtr<FilePathWatcherFSEvents> weak_watcher,
                           FSEventStreamEventId root_change_at) {
-                         if (!weak_watcher)
+                         if (!weak_watcher) {
                            return;
+                         }
                          FilePathWatcherFSEvents* watcher = weak_watcher.get();
                          dispatch_async(watcher->queue_.get(), ^{
                            watcher->UpdateEventStream(root_change_at);
diff --git a/tot/base/files/file_path_watcher_inotify.cc b/tot/base/files/file_path_watcher_inotify.cc
index 6fcfa83..43b97b0 100644
--- a/tot/base/files/file_path_watcher_inotify.cc
+++ b/tot/base/files/file_path_watcher_inotify.cc
@@ -338,8 +338,9 @@
     return;
   }
 
-  if (!StartThread())
+  if (!StartThread()) {
     return;
+  }
 
   valid_ = true;
 }
@@ -352,11 +353,13 @@
 
 InotifyReader::Watch InotifyReader::AddWatch(const FilePath& path,
                                              FilePathWatcherImpl* watcher) {
-  if (!valid_)
+  if (!valid_) {
     return kInvalidWatch;
+  }
 
-  if (watcher->WouldExceedWatchLimit())
+  if (watcher->WouldExceedWatchLimit()) {
     return kWatchLimitExceeded;
+  }
 
   AutoLock auto_lock(lock_);
 
@@ -365,8 +368,9 @@
       inotify_add_watch(inotify_fd_, path.value().c_str(),
                         IN_ATTRIB | IN_CREATE | IN_DELETE | IN_CLOSE_WRITE |
                             IN_MOVE | IN_ONLYDIR);
-  if (watch_int == -1)
+  if (watch_int == -1) {
     return kInvalidWatch;
+  }
   const Watch watch = static_cast<Watch>(watch_int);
 
   watchers_[watch].emplace(std::make_pair(watcher, watcher->GetWatcherEntry()));
@@ -375,14 +379,16 @@
 }
 
 void InotifyReader::RemoveWatch(Watch watch, FilePathWatcherImpl* watcher) {
-  if (!valid_ || (watch == kInvalidWatch))
+  if (!valid_ || (watch == kInvalidWatch)) {
     return;
+  }
 
   AutoLock auto_lock(lock_);
 
   auto watchers_it = watchers_.find(watch);
-  if (watchers_it == watchers_.end())
+  if (watchers_it == watchers_.end()) {
     return;
+  }
 
   auto& watcher_map = watchers_it->second;
   watcher_map.erase(watcher);
@@ -397,8 +403,9 @@
 }
 
 void InotifyReader::OnInotifyEvent(const inotify_event* event) {
-  if (event->mask & IN_IGNORED)
+  if (event->mask & IN_IGNORED) {
     return;
+  }
 
   FilePath::StringType child(event->len ? event->name : FILE_PATH_LITERAL(""));
   AutoLock auto_lock(lock_);
@@ -406,8 +413,9 @@
   // In racing conditions, RemoveWatch() could grab `lock_` first and remove
   // the entry for `event->wd`.
   auto watchers_it = watchers_.find(static_cast<Watch>(event->wd));
-  if (watchers_it == watchers_.end())
+  if (watchers_it == watchers_.end()) {
     return;
+  }
 
   auto& watcher_map = watchers_it->second;
   for (const auto& entry : watcher_map) {
@@ -468,8 +476,9 @@
   // Find the entries in |watches_| that correspond to |fired_watch|.
   for (size_t i = 0; i < watches_.size(); ++i) {
     const WatchEntry& watch_entry = watches_[i];
-    if (fired_watch != watch_entry.watch)
+    if (fired_watch != watch_entry.watch) {
       continue;
+    }
 
     // Check whether a path component of |target_| changed.
     bool change_on_target_path = child.empty() ||
@@ -655,8 +664,9 @@
   set_cancelled();
   callback_.Reset();
 
-  for (const auto& watch : watches_)
+  for (const auto& watch : watches_) {
     g_inotify_reader.Get().RemoveWatch(watch.watch, this);
+  }
   watches_.clear();
   target_.clear();
   RemoveRecursiveWatches();
@@ -675,20 +685,23 @@
     watch_entry.watch = InotifyReader::kInvalidWatch;
     watch_entry.linkname.clear();
     watch_entry.watch = g_inotify_reader.Get().AddWatch(path, this);
-    if (watch_entry.watch == InotifyReader::kWatchLimitExceeded)
+    if (watch_entry.watch == InotifyReader::kWatchLimitExceeded) {
       return false;
+    }
     if (watch_entry.watch == InotifyReader::kInvalidWatch) {
       // Ignore the error code (beyond symlink handling) to attempt to add
       // watches on accessible children of unreadable directories. Note that
       // this is a best-effort attempt; we may not catch events in this
       // scenario.
       if (IsLink(path)) {
-        if (!AddWatchForBrokenSymlink(path, &watch_entry))
+        if (!AddWatchForBrokenSymlink(path, &watch_entry)) {
           return false;
+        }
       }
     }
-    if (old_watch != watch_entry.watch)
+    if (old_watch != watch_entry.watch) {
       g_inotify_reader.Get().RemoveWatch(old_watch, this);
+    }
     path = path.Append(watch_entry.subdir);
   }
 
@@ -700,8 +713,9 @@
     bool is_dir) {
   DUMP_WILL_BE_CHECK(HasValidWatchVector());
 
-  if (type_ != Type::kRecursive)
+  if (type_ != Type::kRecursive) {
     return true;
+  }
 
   if (!DirectoryExists(target_)) {
     RemoveRecursiveWatches();
@@ -716,8 +730,9 @@
   }
 
   // Underneath |target_|, only directory changes trigger watch updates.
-  if (!is_dir)
+  if (!is_dir) {
     return true;
+  }
 
   const FilePath& changed_dir = Contains(recursive_paths_by_watch_, fired_watch)
                                     ? recursive_paths_by_watch_[fired_watch]
@@ -727,8 +742,9 @@
   auto end_it = start_it;
   for (; end_it != recursive_watches_by_path_.end(); ++end_it) {
     const FilePath& cur_path = end_it->first;
-    if (!changed_dir.IsParent(cur_path))
+    if (!changed_dir.IsParent(cur_path)) {
       break;
+    }
 
     // There could be a race when another process is changing contents under
     // `changed_dir` while chrome is watching (e.g. an Android app updating
@@ -780,8 +796,9 @@
       // Try to add new watches.
       InotifyReader::Watch watch =
           g_inotify_reader.Get().AddWatch(current, this);
-      if (watch == InotifyReader::kWatchLimitExceeded)
+      if (watch == InotifyReader::kWatchLimitExceeded) {
         return false;
+      }
 
       // The `watch` returned by inotify already exists. This is actually an
       // update operation.
@@ -797,8 +814,9 @@
       DUMP_WILL_BE_CHECK_NE(InotifyReader::kInvalidWatch, old_watch);
       InotifyReader::Watch watch =
           g_inotify_reader.Get().AddWatch(current, this);
-      if (watch == InotifyReader::kWatchLimitExceeded)
+      if (watch == InotifyReader::kWatchLimitExceeded) {
         return false;
+      }
       if (watch != old_watch) {
         g_inotify_reader.Get().RemoveWatch(old_watch, this);
         recursive_paths_by_watch_.erase(old_watch);
@@ -816,8 +834,9 @@
   DUMP_WILL_BE_CHECK(!path.empty());
   DUMP_WILL_BE_CHECK(target_.IsParent(path));
 
-  if (watch == InotifyReader::kInvalidWatch)
+  if (watch == InotifyReader::kInvalidWatch) {
     return;
+  }
 
   DUMP_WILL_BE_CHECK(!Contains(recursive_paths_by_watch_, watch));
   DUMP_WILL_BE_CHECK(!Contains(recursive_watches_by_path_, path));
@@ -826,11 +845,13 @@
 }
 
 void FilePathWatcherImpl::RemoveRecursiveWatches() {
-  if (type_ != Type::kRecursive)
+  if (type_ != Type::kRecursive) {
     return;
+  }
 
-  for (const auto& it : recursive_paths_by_watch_)
+  for (const auto& it : recursive_paths_by_watch_) {
     g_inotify_reader.Get().RemoveWatch(it.first, this);
+  }
 
   recursive_paths_by_watch_.clear();
   recursive_watches_by_path_.clear();
@@ -855,8 +876,9 @@
   // this case is required.
   InotifyReader::Watch watch =
       g_inotify_reader.Get().AddWatch(link->DirName(), this);
-  if (watch == InotifyReader::kWatchLimitExceeded)
+  if (watch == InotifyReader::kWatchLimitExceeded) {
     return false;
+  }
   if (watch == InotifyReader::kInvalidWatch) {
     // TODO(craig) Symlinks only work if the parent directory for the target
     // exist. Ideally we should make sure we've watched all the components of
@@ -871,11 +893,13 @@
 }
 
 bool FilePathWatcherImpl::HasValidWatchVector() const {
-  if (watches_.empty())
+  if (watches_.empty()) {
     return false;
+  }
   for (size_t i = 0; i < watches_.size() - 1; ++i) {
-    if (watches_[i].subdir.empty())
+    if (watches_[i].subdir.empty()) {
       return false;
+    }
   }
   return watches_.back().subdir.empty();
 }
diff --git a/tot/base/files/file_path_watcher_kqueue.cc b/tot/base/files/file_path_watcher_kqueue.cc
index 18476de..2387e95 100644
--- a/tot/base/files/file_path_watcher_kqueue.cc
+++ b/tot/base/files/file_path_watcher_kqueue.cc
@@ -13,6 +13,7 @@
 #include <stddef.h>
 #include <sys/param.h>
 
+#include <algorithm>
 #include <string>
 #include <vector>
 
@@ -20,7 +21,6 @@
 #include "base/files/file_util.h"
 #include "base/functional/bind.h"
 #include "base/logging.h"
-#include "base/ranges/algorithm.h"
 #include "base/strings/stringprintf.h"
 #include "base/task/sequenced_task_runner.h"
 #include "base/threading/scoped_blocking_call.h"
@@ -63,7 +63,7 @@
   FilePath built_path;
   bool path_still_exists = true;
   for (std::vector<FilePath::StringType>::iterator i = components.begin();
-      i != components.end(); ++i) {
+       i != components.end(); ++i) {
     if (i == components.begin()) {
       built_path = FilePath(*i);
     } else {
@@ -82,8 +82,9 @@
     EventData* data = new EventData(built_path, subdir);
     struct kevent event;
     EV_SET(&event, fd, EVFILT_VNODE, (EV_ADD | EV_CLEAR | EV_RECEIPT),
-           (NOTE_DELETE | NOTE_WRITE | NOTE_ATTRIB |
-            NOTE_RENAME | NOTE_REVOKE | NOTE_EXTEND), 0, data);
+           (NOTE_DELETE | NOTE_WRITE | NOTE_ATTRIB | NOTE_RENAME | NOTE_REVOKE |
+            NOTE_EXTEND),
+           0, data);
     events->push_back(event);
   }
   return last_existing_entry;
@@ -109,8 +110,9 @@
 uintptr_t FilePathWatcherKQueue::FileDescriptorForPath(const FilePath& path) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   int fd = HANDLE_EINTR(open(path.value().c_str(), O_EVTONLY));
-  if (fd < 0)
+  if (fd < 0) {
     return kNoFileDescriptor;
+  }
   return static_cast<uintptr_t>(fd);
 }
 
@@ -330,7 +332,7 @@
       DPLOG(ERROR) << "close kqueue";
     }
     kqueue_ = -1;
-    base::ranges::for_each(events_, ReleaseEvent);
+    std::ranges::for_each(events_, ReleaseEvent);
     events_.clear();
     callback_.Reset();
   }
diff --git a/tot/base/files/file_path_watcher_kqueue.h b/tot/base/files/file_path_watcher_kqueue.h
index b924a28..0bd21af 100644
--- a/tot/base/files/file_path_watcher_kqueue.h
+++ b/tot/base/files/file_path_watcher_kqueue.h
@@ -44,8 +44,8 @@
   class EventData {
    public:
     EventData(const FilePath& path, const FilePath::StringType& subdir)
-        : path_(path), subdir_(subdir) { }
-    FilePath path_;  // Full path to this item.
+        : path_(path), subdir_(subdir) {}
+    FilePath path_;                // Full path to this item.
     FilePath::StringType subdir_;  // Path to any sub item.
   };
 
diff --git a/tot/base/files/file_path_watcher_mac.cc b/tot/base/files/file_path_watcher_mac.cc
index fff1a4d..7bf702b 100644
--- a/tot/base/files/file_path_watcher_mac.cc
+++ b/tot/base/files/file_path_watcher_mac.cc
@@ -2,9 +2,10 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "base/files/file_path_watcher.h"
+
 #include <memory>
 
-#include "base/files/file_path_watcher.h"
 #include "base/files/file_path_watcher_kqueue.h"
 #include "base/memory/ptr_util.h"
 #include "build/build_config.h"
@@ -30,8 +31,9 @@
     // Use kqueue for non-recursive watches and FSEvents for recursive ones.
     DCHECK(!impl_.get());
     if (type == Type::kRecursive) {
-      if (!FilePathWatcher::RecursiveWatchAvailable())
+      if (!FilePathWatcher::RecursiveWatchAvailable()) {
         return false;
+      }
 #if !BUILDFLAG(IS_IOS)
       impl_ = std::make_unique<FilePathWatcherFSEvents>();
 #endif  // BUILDFLAG(IS_IOS)
@@ -43,8 +45,9 @@
   }
 
   void Cancel() override {
-    if (impl_.get())
+    if (impl_.get()) {
       impl_->Cancel();
+    }
     set_cancelled();
   }
 
diff --git a/tot/base/files/file_posix.cc b/tot/base/files/file_posix.cc
index ae70271..1863746 100644
--- a/tot/base/files/file_posix.cc
+++ b/tot/base/files/file_posix.cc
@@ -54,13 +54,11 @@
 #if BUILDFLAG(IS_APPLE)
 // When enabled, `F_FULLFSYNC` is not used in `File::Flush`. Instead,
 // `F_BARRIERFSYNC` or `flush()` is used (depending on the
-// "MacEfficientFileFlushUseBarrier" param). The feature exists to measure the
-// cost of `F_FULLFSYNC` compared to other solutions (not ready to enable by
-// default as-is). See
+// "MacEfficientFileFlushUseBarrier" param). See
 // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/fsync.2.html
 BASE_FEATURE(kMacEfficientFileFlush,
              "MacEfficientFileFlush",
-             base::FEATURE_DISABLED_BY_DEFAULT);
+             base::FEATURE_ENABLED_BY_DEFAULT);
 
 const FeatureParam<bool> kMacEfficientFileFlushUseBarrier{
     &kMacEfficientFileFlush, "MacEfficientFileFlushUseBarrier", true};
@@ -98,9 +96,9 @@
   // http://pubs.opengroup.org/onlinepubs/9699919799/
 
   timespec ts_times[2];
-  ts_times[0].tv_sec  = times[0].tv_sec;
+  ts_times[0].tv_sec = times[0].tv_sec;
   ts_times[0].tv_nsec = times[0].tv_usec * 1000;
-  ts_times[1].tv_sec  = times[1].tv_sec;
+  ts_times[1].tv_sec = times[1].tv_sec;
   ts_times[1].tv_nsec = times[1].tv_usec * 1000;
 
   return futimens(file, ts_times);
@@ -111,8 +109,9 @@
 
 #if !BUILDFLAG(IS_FUCHSIA)
 short FcntlFlockType(std::optional<File::LockMode> mode) {
-  if (!mode.has_value())
+  if (!mode.has_value()) {
     return F_UNLCK;
+  }
   switch (mode.value()) {
     case File::LockMode::kShared:
       return F_RDLCK;
@@ -129,8 +128,9 @@
   lock.l_whence = SEEK_SET;
   lock.l_start = 0;
   lock.l_len = 0;  // Lock entire file.
-  if (HANDLE_EINTR(fcntl(file, F_SETLK, &lock)) == -1)
+  if (HANDLE_EINTR(fcntl(file, F_SETLK, &lock)) == -1) {
     return File::GetLastFileError();
+  }
   return File::FILE_OK;
 }
 #endif
@@ -249,8 +249,9 @@
 }
 
 void File::Close() {
-  if (!IsValid())
+  if (!IsValid()) {
     return;
+  }
 
   SCOPED_FILE_TRACE("Close");
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
@@ -277,8 +278,9 @@
 int File::Read(int64_t offset, char* data, int size) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   DCHECK(IsValid());
-  if (size < 0 || !IsValueInRangeForNumericType<off_t>(offset + size - 1))
+  if (size < 0 || !IsValueInRangeForNumericType<off_t>(offset + size - 1)) {
     return -1;
+  }
 
   SCOPED_FILE_TRACE_WITH_SIZE("Read", size);
 
@@ -288,8 +290,9 @@
     rv = HANDLE_EINTR(pread(file_.get(), data + bytes_read,
                             static_cast<size_t>(size - bytes_read),
                             static_cast<off_t>(offset + bytes_read)));
-    if (rv <= 0)
+    if (rv <= 0) {
       break;
+    }
 
     bytes_read += rv;
   } while (bytes_read < size);
@@ -300,8 +303,9 @@
 int File::ReadAtCurrentPos(char* data, int size) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   DCHECK(IsValid());
-  if (size < 0)
+  if (size < 0) {
     return -1;
+  }
 
   SCOPED_FILE_TRACE_WITH_SIZE("ReadAtCurrentPos", size);
 
@@ -310,8 +314,9 @@
   do {
     rv = HANDLE_EINTR(read(file_.get(), data + bytes_read,
                            static_cast<size_t>(size - bytes_read)));
-    if (rv <= 0)
+    if (rv <= 0) {
       break;
+    }
 
     bytes_read += rv;
   } while (bytes_read < size);
@@ -322,8 +327,9 @@
 int File::ReadNoBestEffort(int64_t offset, char* data, int size) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   DCHECK(IsValid());
-  if (size < 0 || !IsValueInRangeForNumericType<off_t>(offset))
+  if (size < 0 || !IsValueInRangeForNumericType<off_t>(offset)) {
     return -1;
+  }
 
   SCOPED_FILE_TRACE_WITH_SIZE("ReadNoBestEffort", size);
   return checked_cast<int>(
@@ -334,8 +340,9 @@
 int File::ReadAtCurrentPosNoBestEffort(char* data, int size) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   DCHECK(IsValid());
-  if (size < 0)
+  if (size < 0) {
     return -1;
+  }
 
   SCOPED_FILE_TRACE_WITH_SIZE("ReadAtCurrentPosNoBestEffort", size);
   return checked_cast<int>(
@@ -345,12 +352,14 @@
 int File::Write(int64_t offset, const char* data, int size) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
 
-  if (IsOpenAppend(file_.get()))
+  if (IsOpenAppend(file_.get())) {
     return WriteAtCurrentPos(data, size);
+  }
 
   DCHECK(IsValid());
-  if (size < 0)
+  if (size < 0) {
     return -1;
+  }
 
   SCOPED_FILE_TRACE_WITH_SIZE("Write", size);
 
@@ -370,8 +379,9 @@
                              static_cast<size_t>(size - bytes_written),
                              offset + bytes_written));
 #endif
-    if (rv <= 0)
+    if (rv <= 0) {
       break;
+    }
 
     bytes_written += rv;
   } while (bytes_written < size);
@@ -382,8 +392,9 @@
 int File::WriteAtCurrentPos(const char* data, int size) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   DCHECK(IsValid());
-  if (size < 0)
+  if (size < 0) {
     return -1;
+  }
 
   SCOPED_FILE_TRACE_WITH_SIZE("WriteAtCurrentPos", size);
 
@@ -392,8 +403,9 @@
   do {
     rv = HANDLE_EINTR(write(file_.get(), data + bytes_written,
                             static_cast<size_t>(size - bytes_written)));
-    if (rv <= 0)
+    if (rv <= 0) {
       break;
+    }
 
     bytes_written += rv;
   } while (bytes_written < size);
@@ -404,8 +416,9 @@
 int File::WriteAtCurrentPosNoBestEffort(const char* data, int size) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   DCHECK(IsValid());
-  if (size < 0)
+  if (size < 0) {
     return -1;
+  }
 
   SCOPED_FILE_TRACE_WITH_SIZE("WriteAtCurrentPosNoBestEffort", size);
   return checked_cast<int>(
@@ -491,14 +504,16 @@
 #endif
 
 File File::Duplicate() const {
-  if (!IsValid())
+  if (!IsValid()) {
     return File();
+  }
 
   SCOPED_FILE_TRACE("Duplicate");
 
   ScopedPlatformFile other_fd(HANDLE_EINTR(dup(GetPlatformFile())));
-  if (!other_fd.is_valid())
+  if (!other_fd.is_valid()) {
     return File(File::GetLastFileError());
+  }
 
   return File(std::move(other_fd), async());
 }
@@ -562,8 +577,9 @@
   DCHECK(!IsValid());
 
   int open_flags = 0;
-  if (flags & FLAG_CREATE)
+  if (flags & FLAG_CREATE) {
     open_flags = O_CREAT | O_EXCL;
+  }
 
   created_ = false;
 
@@ -595,13 +611,15 @@
     NOTREACHED();
   }
 
-  if (flags & FLAG_TERMINAL_DEVICE)
+  if (flags & FLAG_TERMINAL_DEVICE) {
     open_flags |= O_NOCTTY | O_NDELAY;
+  }
 
-  if (flags & FLAG_APPEND && flags & FLAG_READ)
+  if (flags & FLAG_APPEND && flags & FLAG_READ) {
     open_flags |= O_APPEND | O_RDWR;
-  else if (flags & FLAG_APPEND)
+  } else if (flags & FLAG_APPEND) {
     open_flags |= O_APPEND | O_WRONLY;
+  }
 
   static_assert(O_RDONLY == 0, "O_RDONLY must equal zero");
 
@@ -634,8 +652,9 @@
     if (descriptor < 0) {
       open_flags |= O_CREAT;
       descriptor = HANDLE_EINTR(open(path.value().c_str(), open_flags, mode));
-      if (descriptor >= 0)
+      if (descriptor >= 0) {
         created_ = true;
+      }
     }
   }
 
@@ -644,11 +663,13 @@
     return;
   }
 
-  if (flags & (FLAG_CREATE_ALWAYS | FLAG_CREATE))
+  if (flags & (FLAG_CREATE_ALWAYS | FLAG_CREATE)) {
     created_ = true;
+  }
 
-  if (flags & FLAG_DELETE_ON_CLOSE)
+  if (flags & FLAG_DELETE_ON_CLOSE) {
     unlink(path.value().c_str());
+  }
 
   async_ = ((flags & FLAG_ASYNC) == FLAG_ASYNC);
   error_details_ = FILE_OK;
diff --git a/tot/base/files/file_proxy.cc b/tot/base/files/file_proxy.cc
index ec45495..6bfee5a 100644
--- a/tot/base/files/file_proxy.cc
+++ b/tot/base/files/file_proxy.cc
@@ -19,8 +19,7 @@
 
 namespace {
 
-void FileDeleter(base::File file) {
-}
+void FileDeleter(base::File file) {}
 
 }  // namespace
 
@@ -36,11 +35,12 @@
   FileHelper& operator=(const FileHelper&) = delete;
 
   void PassFile() {
-    if (proxy_)
+    if (proxy_) {
       proxy_->SetFile(std::move(file_));
-    else if (file_.IsValid())
+    } else if (file_.IsValid()) {
       task_runner_->PostTask(FROM_HERE,
                              BindOnce(&FileDeleter, std::move(file_)));
+    }
   }
 
  protected:
@@ -72,19 +72,22 @@
   }
 
   void SetLength(int64_t length) {
-    if (file_.SetLength(length))
+    if (file_.SetLength(length)) {
       error_ = File::FILE_OK;
+    }
   }
 
   void Flush() {
-    if (file_.Flush())
+    if (file_.Flush()) {
       error_ = File::FILE_OK;
+    }
   }
 
   void Reply(FileProxy::StatusCallback callback) {
     PassFile();
-    if (!callback.is_null())
+    if (!callback.is_null()) {
       std::move(callback).Run(error_);
+    }
   }
 };
 
@@ -155,8 +158,9 @@
   GetInfoHelper& operator=(const GetInfoHelper&) = delete;
 
   void RunWork() {
-    if (file_.GetInfo(&file_info_))
-      error_  = File::FILE_OK;
+    if (file_.GetInfo(&file_info_)) {
+      error_ = File::FILE_OK;
+    }
   }
 
   void Reply(FileProxy::GetFileInfoCallback callback) {
@@ -231,8 +235,9 @@
 
   void Reply(FileProxy::WriteCallback callback) {
     PassFile();
-    if (!callback.is_null())
+    if (!callback.is_null()) {
       std::move(callback).Run(error_, bytes_written_);
+    }
   }
 
  private:
@@ -245,8 +250,9 @@
 FileProxy::FileProxy(TaskRunner* task_runner) : task_runner_(task_runner) {}
 
 FileProxy::~FileProxy() {
-  if (file_.IsValid())
+  if (file_.IsValid()) {
     task_runner_->PostTask(FROM_HERE, BindOnce(&FileDeleter, std::move(file_)));
+  }
 }
 
 bool FileProxy::CreateOrOpen(const FilePath& file_path,
@@ -316,8 +322,9 @@
 
 bool FileProxy::Read(int64_t offset, int bytes_to_read, ReadCallback callback) {
   DCHECK(file_.IsValid());
-  if (bytes_to_read < 0)
+  if (bytes_to_read < 0) {
     return false;
+  }
 
   ReadHelper* helper = new ReadHelper(weak_ptr_factory_.GetWeakPtr(),
                                       std::move(file_), bytes_to_read);
diff --git a/tot/base/files/file_proxy_unittest.cc b/tot/base/files/file_proxy_unittest.cc
index 1650682..28cde63 100644
--- a/tot/base/files/file_proxy_unittest.cc
+++ b/tot/base/files/file_proxy_unittest.cc
@@ -12,6 +12,7 @@
 #include <stddef.h>
 #include <stdint.h>
 
+#include <array>
 #include <string_view>
 #include <utility>
 
@@ -35,9 +36,7 @@
  public:
   FileProxyTest()
       : task_environment_(test::TaskEnvironment::MainThreadType::IO),
-        file_thread_("FileProxyTestFileThread"),
-        error_(File::FILE_OK),
-        bytes_written_(-1) {}
+        file_thread_("FileProxyTestFileThread") {}
 
   void SetUp() override {
     ASSERT_TRUE(dir_.CreateUniqueTempDir());
@@ -107,11 +106,11 @@
   test::TaskEnvironment task_environment_;
   Thread file_thread_;
 
-  File::Error error_;
+  File::Error error_ = File::FILE_OK;
   FilePath path_;
   File::Info file_info_;
   base::HeapArray<char> buffer_;
-  int bytes_written_;
+  int bytes_written_ = -1;
   WeakPtrFactory<FileProxyTest> weak_factory_{this};
 };
 
@@ -238,11 +237,12 @@
   // Try a few times because files may be locked by anti-virus or other.
   bool deleted_temp_file = false;
   for (int i = 0; !deleted_temp_file && i < 3; ++i) {
-    if (base::DeleteFile(path_))
+    if (base::DeleteFile(path_)) {
       deleted_temp_file = true;
-    else
+    } else {
       // Wait one second and then try again
       PlatformThread::Sleep(Seconds(1));
+    }
   }
   EXPECT_TRUE(deleted_temp_file);
 }
@@ -254,7 +254,7 @@
   EXPECT_FALSE(proxy.IsValid());
   proxy.SetFile(std::move(file));
   EXPECT_TRUE(proxy.IsValid());
-  EXPECT_FALSE(file.IsValid());
+  EXPECT_FALSE(file.IsValid());  // NOLINT(bugprone-use-after-move)
 
   file = proxy.TakeFile();
   EXPECT_FALSE(proxy.IsValid());
@@ -349,7 +349,7 @@
   EXPECT_EQ(File::FILE_OK, error_);
 
   // Verify the written data.
-  char read_buffer[10];
+  std::array<char, 10> read_buffer;
   EXPECT_GE(std::size(read_buffer), write_span.size());
   EXPECT_EQ(write_span.size(), base::ReadFile(TestPath(), read_buffer));
   for (size_t i = 0; i < write_span.size(); ++i) {
@@ -415,11 +415,12 @@
   GetFileInfo(TestPath(), &info);
   ASSERT_EQ(7, info.size);
 
-  char buffer[7];
+  std::array<char, 7> buffer;
   EXPECT_EQ(7, base::ReadFile(TestPath(), buffer));
   int i = 0;
-  for (; i < 7; ++i)
+  for (; i < 7; ++i) {
     EXPECT_EQ(kTestData[i], buffer[i]);
+  }
 }
 
 TEST_F(FileProxyTest, SetLength_Expand) {
@@ -443,13 +444,15 @@
   GetFileInfo(TestPath(), &info);
   ASSERT_EQ(53, info.size);
 
-  char buffer[53];
+  std::array<char, 53> buffer;
   EXPECT_EQ(53, base::ReadFile(TestPath(), buffer));
   int i = 0;
-  for (; i < 10; ++i)
+  for (; i < 10; ++i) {
     EXPECT_EQ(kTestData[i], buffer[i]);
-  for (; i < 53; ++i)
+  }
+  for (; i < 53; ++i) {
     EXPECT_EQ(0, buffer[i]);
+  }
 }
 
 }  // namespace base
diff --git a/tot/base/files/file_tracing.cc b/tot/base/files/file_tracing.cc
index 445e1fe..69953e5 100644
--- a/tot/base/files/file_tracing.cc
+++ b/tot/base/files/file_tracing.cc
@@ -32,21 +32,24 @@
 
 FileTracing::ScopedEnabler::ScopedEnabler() {
   FileTracing::Provider* provider = GetProvider();
-  if (provider)
+  if (provider) {
     provider->FileTracingEnable(this);
+  }
 }
 
 FileTracing::ScopedEnabler::~ScopedEnabler() {
   FileTracing::Provider* provider = GetProvider();
-  if (provider)
+  if (provider) {
     provider->FileTracingDisable(this);
+  }
 }
 
 FileTracing::ScopedTrace::~ScopedTrace() {
   if (id_) {
     FileTracing::Provider* provider = GetProvider();
-    if (provider)
+    if (provider) {
       provider->FileTracingEventEnd(name_, id_);
+    }
   }
 }
 
diff --git a/tot/base/files/file_tracing.h b/tot/base/files/file_tracing.h
index 5f2f976..5da1b05 100644
--- a/tot/base/files/file_tracing.h
+++ b/tot/base/files/file_tracing.h
@@ -13,9 +13,9 @@
 #define FILE_TRACING_PREFIX "File"
 
 #define SCOPED_FILE_TRACE_WITH_SIZE(name, size) \
-    FileTracing::ScopedTrace scoped_file_trace; \
-    if (FileTracing::IsCategoryEnabled()) \
-      scoped_file_trace.Initialize(FILE_TRACING_PREFIX "::" name, this, size)
+  FileTracing::ScopedTrace scoped_file_trace;   \
+  if (FileTracing::IsCategoryEnabled())         \
+  scoped_file_trace.Initialize(FILE_TRACING_PREFIX "::" name, this, size)
 
 #define SCOPED_FILE_TRACE(name) SCOPED_FILE_TRACE_WITH_SIZE(name, 0)
 
diff --git a/tot/base/files/file_unittest.cc b/tot/base/files/file_unittest.cc
index 057f0d5..ce44d91 100644
--- a/tot/base/files/file_unittest.cc
+++ b/tot/base/files/file_unittest.cc
@@ -384,7 +384,7 @@
 
   // Test passing the file around.
   file = std::move(file2);
-  EXPECT_FALSE(file2.IsValid());
+  EXPECT_FALSE(file2.IsValid());  // NOLINT(bugprone-use-after-move)
   ASSERT_TRUE(file.IsValid());
 
   char append_data_to_write[] = "78";
@@ -639,12 +639,12 @@
 
   std::string data("test");
   size_t first_chunk_size = data.size() / 2;
-  std::optional<size_t> result =
-      file.WriteAtCurrentPos(as_byte_span(data).first(first_chunk_size));
+  const auto [first, second] = as_byte_span(data).split_at(first_chunk_size);
+  std::optional<size_t> result = file.WriteAtCurrentPos(first);
   ASSERT_TRUE(result.has_value());
   EXPECT_EQ(first_chunk_size, result.value());
 
-  result = file.WriteAtCurrentPos(as_byte_span(data).subspan(first_chunk_size));
+  result = file.WriteAtCurrentPos(second);
   ASSERT_TRUE(result.has_value());
   EXPECT_EQ(first_chunk_size, result.value());
 
diff --git a/tot/base/files/file_util.cc b/tot/base/files/file_util.cc
index 6211201..30bdcc0 100644
--- a/tot/base/files/file_util.cc
+++ b/tot/base/files/file_util.cc
@@ -20,6 +20,7 @@
 #endif
 #include <stdio.h>
 
+#include <algorithm>
 #include <fstream>
 #include <limits>
 #include <memory>
@@ -35,9 +36,8 @@
 #include "base/functional/function_ref.h"
 #include "base/notreached.h"
 #include "base/posix/eintr_wrapper.h"
-#include "base/ranges/algorithm.h"
+#include "base/strings/string_number_conversions.h"
 #include "base/strings/string_util.h"
-#include "base/strings/stringprintf.h"
 #include "base/strings/utf_string_conversions.h"
 #include "base/task/bind_post_task.h"
 #include "base/threading/scoped_blocking_call.h"
@@ -504,15 +504,17 @@
 FilePath GetUniquePathWithSuffixFormat(const FilePath& path,
                                        base::cstring_view suffix_format) {
   DCHECK(!path.empty());
-  DCHECK_EQ(base::ranges::count(suffix_format, '%'), 1);
+  DCHECK_EQ(std::ranges::count(suffix_format, '%'), 1);
   DCHECK(base::Contains(suffix_format, "%d"));
 
   if (!PathExists(path)) {
     return path;
   }
   for (int count = 1; count <= kMaxUniqueFiles; ++count) {
-    FilePath candidate_path = path.InsertBeforeExtensionASCII(
-        StringPrintfNonConstexpr(suffix_format.data(), count));
+    std::string suffix(suffix_format);
+    base::ReplaceFirstSubstringAfterOffset(&suffix, 0, "%d",
+                                           base::NumberToString(count));
+    FilePath candidate_path = path.InsertBeforeExtensionASCII(suffix);
     if (!PathExists(candidate_path)) {
       return candidate_path;
     }
diff --git a/tot/base/files/file_util.h b/tot/base/files/file_util.h
index 0cb1885..6302caf 100644
--- a/tot/base/files/file_util.h
+++ b/tot/base/files/file_util.h
@@ -428,7 +428,7 @@
 // Returns the file name for a temporary file by using a platform-specific
 // naming scheme that incorporates |identifier|.
 BASE_EXPORT FilePath
-FormatTemporaryFileName(FilePath::StringPieceType identifier);
+FormatTemporaryFileName(FilePath::StringViewType identifier);
 
 // Create and open a temporary file stream for exclusive read, write, and delete
 // access. The full path is placed in `path`. Returns the opened file stream, or
@@ -463,14 +463,17 @@
 // Extra characters will be appended to |prefix| to ensure that the
 // new directory does not have the same name as an existing directory.
 BASE_EXPORT bool CreateTemporaryDirInDir(const FilePath& base_dir,
-                                         FilePath::StringPieceType prefix,
+                                         FilePath::StringViewType prefix,
                                          FilePath* new_dir);
 
-// Creates a directory, as well as creating any parent directories, if they
-// don't exist. Returns 'true' on successful creation, or if the directory
-// already exists.  The directory is only readable by the current user.
-// Returns true on success, leaving *error unchanged.
-// Returns false on failure and sets *error appropriately, if it is non-NULL.
+// Ensures a directory exists, if necessary, creating it and parent directories.
+// Returns true if the directory already existed or was created, leaving *error
+// unchanged.
+// Returns false on failure and sets *error appropriately if it is non-NULL.
+//
+// The created directories can only be accessed by the current user, except on
+// ChromeOS, where the directories created under `~/MyFiles` can also be
+// accessed by ChromeOS services.
 BASE_EXPORT bool CreateDirectoryAndGetError(const FilePath& full_path,
                                             File::Error* error);
 
diff --git a/tot/base/files/file_util_posix.cc b/tot/base/files/file_util_posix.cc
index c1f484b..72ed9b1 100644
--- a/tot/base/files/file_util_posix.cc
+++ b/tot/base/files/file_util_posix.cc
@@ -2,6 +2,11 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#ifdef UNSAFE_BUFFERS_BUILD
+// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
+#pragma allow_unsafe_libc_calls
+#endif
+
 #include "base/files/file_util.h"
 
 #include <dirent.h>
@@ -427,6 +432,18 @@
 }
 #endif
 
+#if BUILDFLAG(IS_CHROMEOS)
+
+// Checks if the given path is under ~/MyFiles.
+bool IsUnderMyFiles(const FilePath& path) {
+  const std::vector parts = path.GetComponents();
+  return parts.size() > 5 && parts[0] == "/" && parts[1] == "home" &&
+         parts[2] == "chronos" && parts[3].starts_with("u-") &&
+         parts[4] == "MyFiles" && !parts[5].empty();
+}
+
+#endif  // BUILDFLAG(IS_CHROMEOS)
+
 }  // namespace
 
 FilePath MakeAbsoluteFilePath(const FilePath& input) {
@@ -827,7 +844,7 @@
   return fd.is_valid();
 }
 
-FilePath FormatTemporaryFileName(FilePath::StringPieceType identifier) {
+FilePath FormatTemporaryFileName(FilePath::StringViewType identifier) {
 #if BUILDFLAG(IS_APPLE)
   std::string_view prefix = base::apple::BaseBundleID();
 #elif BUILDFLAG(GOOGLE_CHROME_BRANDING)
@@ -876,7 +893,7 @@
 }
 
 bool CreateTemporaryDirInDir(const FilePath& base_dir,
-                             FilePath::StringPieceType prefix,
+                             FilePath::StringViewType prefix,
                              FilePath* new_dir) {
   FilePath::StringType mkdtemp_template(prefix);
   mkdtemp_template.append("XXXXXX");
@@ -897,23 +914,35 @@
 bool CreateDirectoryAndGetError(const FilePath& full_path, File::Error* error) {
   ScopedBlockingCall scoped_blocking_call(
       FROM_HERE, BlockingType::MAY_BLOCK);  // For call to mkdir().
-  std::vector<FilePath> subpaths;
 
-  // Collect a list of all parent directories.
+  // Avoid checking subdirs if directory already exists.
+  if (DirectoryExists(full_path)) {
+    return true;
+  }
+
+  // Collect a list of all missing directories.
+  std::vector<FilePath> missing_subpaths({full_path});
   FilePath last_path = full_path;
-  subpaths.push_back(full_path);
   for (FilePath path = full_path.DirName(); path.value() != last_path.value();
        path = path.DirName()) {
-    subpaths.push_back(path);
+    if (DirectoryExists(path)) {
+      break;
+    }
+    missing_subpaths.push_back(path);
     last_path = path;
   }
 
-  // Iterate through the parents and create the missing ones.
-  for (const FilePath& subpath : base::Reversed(subpaths)) {
-    if (DirectoryExists(subpath)) {
-      continue;
+  // Iterate through the missing directories and create.
+  for (const FilePath& subpath : base::Reversed(missing_subpaths)) {
+    mode_t mode = S_IRWXU;
+
+#if BUILDFLAG(IS_CHROMEOS)
+    if (IsUnderMyFiles(subpath)) {
+      mode |= S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
     }
-    if (mkdir(subpath.value().c_str(), 0700) == 0) {
+#endif  // BUILDFLAG(IS_CHROMEOS)
+
+    if (mkdir(subpath.value().c_str(), mode) == 0) {
       continue;
     }
     // Mkdir failed, but it might have failed with EEXIST, or some other error
diff --git a/tot/base/files/file_util_unittest.cc b/tot/base/files/file_util_unittest.cc
index 33c8638..64038c7 100644
--- a/tot/base/files/file_util_unittest.cc
+++ b/tot/base/files/file_util_unittest.cc
@@ -1734,26 +1734,35 @@
       *test::android::GetInMemoryContentUriFromCacheDirFilePath(file);
   FilePath content_uri_dir_in_memory =
       *test::android::GetInMemoryContentUriFromCacheDirFilePath(dir);
-  FilePath content_uri_dir_tree =
+  FilePath content_uri_document =
+      *test::android::GetInMemoryContentDocumentUriFromCacheDirFilePath(file);
+  FilePath content_uri_document_tree =
       *test::android::GetInMemoryContentTreeUriFromCacheDirDirectory(dir);
 
   // GetInfo() should work the same for files and content-URIs.
   File::Info info;
   File::Info content_uri_info;
   File::Info content_uri_in_memory_info;
+  File::Info content_uri_document_info;
   EXPECT_TRUE(GetFileInfo(file, &info));
   EXPECT_TRUE(GetFileInfo(content_uri_file, &content_uri_info));
+  EXPECT_TRUE(GetFileInfo(content_uri_document, &content_uri_document_info));
   EXPECT_TRUE(
       GetFileInfo(content_uri_file_in_memory, &content_uri_in_memory_info));
   EXPECT_EQ(12u, info.size);
   EXPECT_EQ(12u, content_uri_info.size);
   EXPECT_EQ(12u, content_uri_in_memory_info.size);
+  EXPECT_EQ(12u, content_uri_document_info.size);
   EXPECT_EQ(info.last_modified, content_uri_info.last_modified);
   // Java InMemory provider sets last-modified to unix epoch.
   EXPECT_EQ(content_uri_in_memory_info.last_modified, Time::FromTimeT(0));
+  // Java DocumentProvider only does resolution to seconds.
+  EXPECT_EQ(info.last_modified.ToTimeT(),
+            content_uri_document_info.last_modified.ToTimeT());
   EXPECT_FALSE(info.is_directory);
   EXPECT_FALSE(content_uri_info.is_directory);
   EXPECT_FALSE(content_uri_in_memory_info.is_directory);
+  EXPECT_FALSE(content_uri_document_info.is_directory);
 
   // GetInfo() should work the same for dirs and content-URIs.
   EXPECT_TRUE(GetFileInfo(dir, &info));
@@ -1762,12 +1771,15 @@
   EXPECT_FALSE(
       GetFileInfo(content_uri_dir_in_memory, &content_uri_in_memory_info));
   File::Info content_uri_tree_info;
-  EXPECT_TRUE(GetFileInfo(content_uri_dir_tree, &content_uri_tree_info));
+  EXPECT_TRUE(GetFileInfo(content_uri_document_tree, &content_uri_tree_info));
   EXPECT_EQ(info.last_modified, content_uri_info.last_modified);
   // Java uses FileEnumerator::FileInfo which only does resolution to seconds.
   EXPECT_EQ(info.last_modified.ToTimeT(),
             content_uri_tree_info.last_modified.ToTimeT());
   EXPECT_TRUE(info.is_directory);
+#if BUILDFLAG(IS_WIN)
+  EXPECT_EQ(info.size, 0u);
+#endif
   EXPECT_TRUE(content_uri_info.is_directory);
   EXPECT_TRUE(content_uri_tree_info.is_directory);
 
@@ -3049,7 +3061,7 @@
 
   stream = FileToFILE(std::move(file), "w");
   EXPECT_TRUE(stream);
-  EXPECT_FALSE(file.IsValid());
+  EXPECT_FALSE(file.IsValid());  // NOLINT(bugprone-use-after-move)
   EXPECT_TRUE(CloseFile(stream));
 }
 
@@ -4477,7 +4489,21 @@
   File file(path, File::FLAG_OPEN | File::FLAG_READ);
   EXPECT_FALSE(file.IsValid());
 }
-#endif
+
+// Validate crbug.com/398066589 where CreateDirectory() fails when a user does
+// not have stat() access to all subpaths.
+TEST_F(FileUtilTest, CreateDirectoryOnlyCheckMissingSubpaths) {
+  // Apps have access to the android external-storage-dir (e.g.
+  // /storage/emulated/0), but for security will usually not have access such as
+  // stat() to its parent. In tests, DIR_ANDROID_APP_DATA is subdir
+  // chromium_tests_root. The directory should always exist before this test
+  // runs, but even if not it should create ok even though stat() would fail on
+  // some of the subpaths.
+  FilePath dir = PathService::CheckedGet(DIR_ANDROID_APP_DATA);
+  EXPECT_TRUE(CreateDirectory(dir));
+}
+
+#endif  // BUILDFLAG(IS_ANDROID)
 
 #if BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) && \
     defined(ARCH_CPU_32_BITS)
diff --git a/tot/base/files/file_util_win.cc b/tot/base/files/file_util_win.cc
index f93a90c..28a259b 100644
--- a/tot/base/files/file_util_win.cc
+++ b/tot/base/files/file_util_win.cc
@@ -115,8 +115,9 @@
     } else if (!::DeleteFile(current.value().c_str())) {
       this_result = ReturnLastErrorOrSuccessOnNotFound();
     }
-    if (result == ERROR_SUCCESS)
+    if (result == ERROR_SUCCESS) {
       result = this_result;
+    }
   }
   return result;
 }
@@ -133,8 +134,9 @@
                 const FilePath& to_path,
                 bool fail_if_exists) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
-  if (from_path.ReferencesParent() || to_path.ReferencesParent())
+  if (from_path.ReferencesParent() || to_path.ReferencesParent()) {
     return false;
+  }
 
   // NOTE: I suspect we could support longer paths, but that would involve
   // analyzing all our usage of files.
@@ -188,22 +190,27 @@
   FilePath real_to_path = to_path;
   if (PathExists(real_to_path)) {
     real_to_path = MakeAbsoluteFilePath(real_to_path);
-    if (real_to_path.empty())
+    if (real_to_path.empty()) {
       return false;
+    }
   } else {
     real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
-    if (real_to_path.empty())
+    if (real_to_path.empty()) {
       return false;
+    }
   }
   FilePath real_from_path = MakeAbsoluteFilePath(from_path);
-  if (real_from_path.empty())
+  if (real_from_path.empty()) {
     return false;
-  if (real_to_path == real_from_path || real_from_path.IsParent(real_to_path))
+  }
+  if (real_to_path == real_from_path || real_from_path.IsParent(real_to_path)) {
     return false;
+  }
 
   int traverse_type = FileEnumerator::FILES;
-  if (recursive)
+  if (recursive) {
     traverse_type |= FileEnumerator::DIRECTORIES;
+  }
   FileEnumerator traversal(from_path, recursive, traverse_type);
 
   if (!PathExists(from_path)) {
@@ -249,8 +256,9 @@
     }
 
     current = traversal.Next();
-    if (!current.empty())
+    if (!current.empty()) {
       from_is_dir = traversal.GetInfo().IsDirectory();
+    }
   }
 
   return success;
@@ -260,11 +268,13 @@
 DWORD DoDeleteFile(const FilePath& path, bool recursive) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
 
-  if (path.empty())
+  if (path.empty()) {
     return ERROR_SUCCESS;
+  }
 
-  if (path.value().length() >= MAX_PATH)
+  if (path.value().length() >= MAX_PATH) {
     return ERROR_BAD_PATHNAME;
+  }
 
   // Handle any path with wildcards.
   if (path.BaseName().value().find_first_of(FILE_PATH_LITERAL("*?")) !=
@@ -278,8 +288,9 @@
 
   // Report success if the file or path does not exist.
   const DWORD attr = ::GetFileAttributes(path.value().c_str());
-  if (attr == INVALID_FILE_ATTRIBUTES)
+  if (attr == INVALID_FILE_ATTRIBUTES) {
     return ReturnLastErrorOrSuccessOnNotFound();
+  }
 
   // Clear the read-only bit if it is set.
   if ((attr & FILE_ATTRIBUTE_READONLY) &&
@@ -301,8 +312,9 @@
         DeleteFileRecursive(path, FILE_PATH_LITERAL("*"), true);
     DCHECK_NE(static_cast<LONG>(error_code), ERROR_FILE_NOT_FOUND);
     DCHECK_NE(static_cast<LONG>(error_code), ERROR_PATH_NOT_FOUND);
-    if (error_code != ERROR_SUCCESS)
+    if (error_code != ERROR_SUCCESS) {
       return error_code;
+    }
   }
   return ::RemoveDirectory(path.value().c_str())
              ? ERROR_SUCCESS
@@ -314,8 +326,9 @@
 // code and returns false on failure.
 bool DeleteFileOrSetLastError(const FilePath& path, bool recursive) {
   const DWORD error = DoDeleteFile(path, recursive);
-  if (error == ERROR_SUCCESS)
+  if (error == ERROR_SUCCESS) {
     return true;
+  }
 
   ::SetLastError(error);
   return false;
@@ -335,16 +348,18 @@
     // Consider introducing further retries until the item has been removed from
     // the filesystem and its name is ready for reuse; see the comments in
     // chrome/installer/mini_installer/delete_with_retry.cc for details.
-    if (!reply_callback.is_null())
+    if (!reply_callback.is_null()) {
       std::move(reply_callback).Run(true);
+    }
     return;
   }
 
   ++attempt;
   DCHECK_LE(attempt, kMaxDeleteAttempts);
   if (attempt == kMaxDeleteAttempts) {
-    if (!reply_callback.is_null())
+    if (!reply_callback.is_null()) {
       std::move(reply_callback).Run(false);
+    }
     return;
   }
 
@@ -444,8 +459,9 @@
 FilePath MakeAbsoluteFilePath(const FilePath& input) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   wchar_t file_path[MAX_PATH];
-  if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH))
+  if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH)) {
     return FilePath();
+  }
   return FilePath(file_path);
 }
 
@@ -460,8 +476,9 @@
 bool DeleteFileAfterReboot(const FilePath& path) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
 
-  if (path.value().length() >= MAX_PATH)
+  if (path.value().length() >= MAX_PATH) {
     return false;
+  }
 
   return ::MoveFileEx(path.value().c_str(), nullptr,
                       MOVEFILE_DELAY_UNTIL_REBOOT);
@@ -485,8 +502,9 @@
 
   // Try a simple move next. It will only succeed when |to_path| doesn't already
   // exist.
-  if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
+  if (::MoveFile(from_path.value().c_str(), to_path.value().c_str())) {
     return true;
+  }
 
   // In the case of FILE_ERROR_NOT_FOUND from ReplaceFile, it is likely that
   // |to_path| does not exist. In this case, the more relevant error comes
@@ -525,8 +543,9 @@
 
   const wchar_t* const path_str = path.value().c_str();
   DWORD fileattr = GetFileAttributes(path_str);
-  if (fileattr == INVALID_FILE_ATTRIBUTES)
+  if (fileattr == INVALID_FILE_ATTRIBUTES) {
     return false;
+  }
 
   bool is_directory = fileattr & FILE_ATTRIBUTE_DIRECTORY;
   DWORD desired_access =
@@ -554,16 +573,18 @@
 bool DirectoryExists(const FilePath& path) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   DWORD fileattr = GetFileAttributes(path.value().c_str());
-  if (fileattr != INVALID_FILE_ATTRIBUTES)
+  if (fileattr != INVALID_FILE_ATTRIBUTES) {
     return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
+  }
   return false;
 }
 
 bool GetTempDir(FilePath* path) {
   wchar_t temp_path[MAX_PATH + 1];
   DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
-  if (path_len >= MAX_PATH || path_len <= 0)
+  if (path_len >= MAX_PATH || path_len <= 0) {
     return false;
+  }
   // TODO(evanm): the old behavior of this function was to always strip the
   // trailing slash.  We duplicate this here, but it shouldn't be necessary
   // when everyone is using the appropriate FilePath APIs.
@@ -581,8 +602,9 @@
 
   // Fall back to the temporary directory on failure.
   FilePath temp;
-  if (GetTempDir(&temp))
+  if (GetTempDir(&temp)) {
     return temp;
+  }
 
   // Last resort.
   return FilePath(FILE_PATH_LITERAL("C:\\"));
@@ -614,8 +636,9 @@
     temp_name = dir.Append(FormatTemporaryFileName(
         UTF8ToWide(Uuid::GenerateRandomV4().AsLowercaseString())));
     file.Initialize(temp_name, kFlags);
-    if (file.IsValid())
+    if (file.IsValid()) {
       break;
+    }
   }
 
   if (!file.IsValid()) {
@@ -628,7 +651,7 @@
       GetLongPathName(temp_name.value().c_str(), long_temp_name, MAX_PATH);
   if (long_name_len != 0 && long_name_len <= MAX_PATH) {
     *temp_file =
-        FilePath(FilePath::StringPieceType(long_temp_name, long_name_len));
+        FilePath(FilePath::StringViewType(long_temp_name, long_name_len));
   } else {
     // GetLongPathName() failed, but we still have a temporary file.
     *temp_file = std::move(temp_name);
@@ -641,7 +664,7 @@
   return CreateAndOpenTemporaryFileInDir(dir, temp_file).IsValid();
 }
 
-FilePath FormatTemporaryFileName(FilePath::StringPieceType identifier) {
+FilePath FormatTemporaryFileName(FilePath::StringViewType identifier) {
   return FilePath(StrCat({identifier, FILE_PATH_LITERAL(".tmp")}));
 }
 
@@ -655,7 +678,7 @@
 }
 
 bool CreateTemporaryDirInDir(const FilePath& base_dir,
-                             FilePath::StringPieceType prefix,
+                             FilePath::StringViewType prefix,
                              FilePath* new_dir) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
 
@@ -704,14 +727,14 @@
     return true;
   }
 
-  if (!GetTempDir(&parent_dir))
+  if (!GetTempDir(&parent_dir)) {
     return false;
+  }
 
   return CreateTemporaryDirInDir(parent_dir, prefix, new_temp_path);
 }
 
-bool CreateDirectoryAndGetError(const FilePath& full_path,
-                                File::Error* error) {
+bool CreateDirectoryAndGetError(const FilePath& full_path, File::Error* error) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
 
   // If the path exists, we've succeeded if it's a directory, failed otherwise.
@@ -723,8 +746,9 @@
     }
     DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
                   << "conflicts with existing file.";
-    if (error)
+    if (error) {
       *error = File::FILE_ERROR_NOT_A_DIRECTORY;
+    }
     ::SetLastError(ERROR_FILE_EXISTS);
     return false;
   }
@@ -736,8 +760,9 @@
   // directories starting with the highest-level missing parent.
   FilePath parent_path(full_path.DirName());
   if (parent_path.value() == full_path.value()) {
-    if (error)
+    if (error) {
       *error = File::FILE_ERROR_NOT_FOUND;
+    }
     ::SetLastError(ERROR_FILE_NOT_FOUND);
     return false;
   }
@@ -747,8 +772,9 @@
     return false;
   }
 
-  if (::CreateDirectory(full_path_str, NULL))
+  if (::CreateDirectory(full_path_str, NULL)) {
     return true;
+  }
 
   const DWORD error_code = ::GetLastError();
   if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
@@ -758,8 +784,9 @@
     // same directory.
     return true;
   }
-  if (error)
+  if (error) {
     *error = File::OSErrorToFileError(error_code);
+  }
   ::SetLastError(error_code);
   DPLOG(WARNING) << "Failed to create directory " << full_path_str;
   return false;
@@ -793,7 +820,7 @@
   // with the volume device path and existing code expects we return a path
   // starting 'X:\' so we need to call DevicePathToDriveLetterPath.
   if (!DevicePathToDriveLetterPath(
-          FilePath(FilePath::StringPieceType(native_file_path, used_wchars)),
+          FilePath(FilePath::StringViewType(native_file_path, used_wchars)),
           real_path)) {
     return false;
   }
@@ -857,15 +884,17 @@
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
 
   DWORD path_long_len = ::GetLongPathName(input.value().c_str(), nullptr, 0);
-  if (path_long_len == 0UL)
+  if (path_long_len == 0UL) {
     return FilePath();
+  }
 
   std::wstring path_long_str;
   path_long_len = ::GetLongPathName(input.value().c_str(),
                                     WriteInto(&path_long_str, path_long_len),
                                     path_long_len);
-  if (path_long_len == 0UL)
+  if (path_long_len == 0UL) {
     return FilePath();
+  }
 
   return FilePath(path_long_str);
 }
@@ -891,15 +920,24 @@
     return false;
   }
 
-  ULARGE_INTEGER size;
-  size.HighPart = attr.nFileSizeHigh;
-  size.LowPart = attr.nFileSizeLow;
-  // TODO(crbug.com/40227936): Change Info::size to uint64_t and eliminate this
-  // cast.
-  results->size = checked_cast<int64_t>(size.QuadPart);
-
   results->is_directory =
       (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
+
+  // According to
+  // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/ns-fileapi-win32_file_attribute_data
+  // both attr.nFileSizeHigh and attr.nFileSizeLow are meaningless if the file
+  // is a directory.
+  if (results->is_directory) {
+    results->size = 0;
+  } else {
+    ULARGE_INTEGER size;
+    size.HighPart = attr.nFileSizeHigh;
+    size.LowPart = attr.nFileSizeLow;
+    // TODO(crbug.com/40227936): Change Info::size to uint64_t and eliminate
+    // this cast.
+    results->size = checked_cast<int64_t>(size.QuadPart);
+  }
+
   results->last_modified = Time::FromFileTime(attr.ftLastWriteTime);
   results->last_accessed = Time::FromFileTime(attr.ftLastAccessTime);
   results->creation_time = Time::FromFileTime(attr.ftCreationTime);
@@ -921,22 +959,26 @@
 
 FILE* FileToFILE(File file, const char* mode) {
   DCHECK(!file.async());
-  if (!file.IsValid())
+  if (!file.IsValid()) {
     return NULL;
+  }
   int fd =
       _open_osfhandle(reinterpret_cast<intptr_t>(file.GetPlatformFile()), 0);
-  if (fd < 0)
+  if (fd < 0) {
     return NULL;
+  }
   file.TakePlatformFile();
   FILE* stream = _fdopen(fd, mode);
-  if (!stream)
+  if (!stream) {
     _close(fd);
+  }
   return stream;
 }
 
 File FILEToFile(FILE* file_stream) {
-  if (!file_stream)
+  if (!file_stream) {
     return File();
+  }
 
   int fd = _fileno(file_stream);
   DCHECK_GE(fd, 0);
@@ -1019,8 +1061,9 @@
   DWORD written;
   DWORD size = checked_cast<DWORD>(data.size());
   BOOL result = ::WriteFile(file.get(), data.data(), size, &written, nullptr);
-  if (result && written == size)
+  if (result && written == size) {
     return true;
+  }
 
   if (!result) {
     // WriteFile failed.
@@ -1043,12 +1086,13 @@
   wchar_t system_buffer[MAX_PATH];
   system_buffer[0] = 0;
   DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
-  if (len == 0 || len > MAX_PATH)
+  if (len == 0 || len > MAX_PATH) {
     return false;
+  }
   // TODO(evanm): the old behavior of this function was to always strip the
   // trailing slash.  We duplicate this here, but it shouldn't be necessary
   // when everyone is using the appropriate FilePath APIs.
-  *dir = FilePath(FilePath::StringPieceType(system_buffer))
+  *dir = FilePath(FilePath::StringViewType(system_buffer))
              .StripTrailingSeparators();
   return true;
 }
@@ -1088,8 +1132,9 @@
 bool SetNonBlocking(int fd) {
   unsigned long nonblocking = 1;
   if (ioctlsocket(static_cast<SOCKET>(fd), static_cast<long>(FIONBIO),
-                  &nonblocking) == 0)
+                  &nonblocking) == 0) {
     return true;
+  }
   return false;
 }
 
@@ -1210,8 +1255,9 @@
     return false;
   }
   if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
-                 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
+                 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0) {
     return true;
+  }
 
   // Keep the last error value from MoveFileEx around in case the below
   // fails.
@@ -1238,8 +1284,9 @@
                             const FilePath& to_path) {
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   if (CopyDirectory(from_path, to_path, true)) {
-    if (DeletePathRecursively(from_path))
+    if (DeletePathRecursively(from_path)) {
       return true;
+    }
 
     // Like Move, this function is not transactional, so we just
     // leave the copied bits behind if deleting from_path fails.
diff --git a/tot/base/files/file_win.cc b/tot/base/files/file_win.cc
index 5460967..9067950 100644
--- a/tot/base/files/file_win.cc
+++ b/tot/base/files/file_win.cc
@@ -41,8 +41,9 @@
 }
 
 void File::Close() {
-  if (!file_.is_valid())
+  if (!file_.is_valid()) {
     return;
+  }
 
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   SCOPED_FILE_TRACE("Close");
@@ -58,8 +59,9 @@
   LARGE_INTEGER distance, res;
   distance.QuadPart = offset;
   DWORD move_method = static_cast<DWORD>(whence);
-  if (!SetFilePointerEx(file_.get(), distance, &res, move_method))
+  if (!SetFilePointerEx(file_.get(), distance, &res, move_method)) {
     return -1;
+  }
   return res.QuadPart;
 }
 
@@ -67,8 +69,9 @@
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   DCHECK(IsValid());
   DCHECK(!async_);
-  if (size < 0 || offset < 0)
+  if (size < 0 || offset < 0) {
     return -1;
+  }
 
   SCOPED_FILE_TRACE_WITH_SIZE("Read", size);
 
@@ -86,8 +89,9 @@
     // and eliminate this cast.
     return checked_cast<int>(bytes_read);
   }
-  if (ERROR_HANDLE_EOF == GetLastError())
+  if (ERROR_HANDLE_EOF == GetLastError()) {
     return 0;
+  }
 
   return -1;
 }
@@ -96,8 +100,9 @@
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   DCHECK(IsValid());
   DCHECK(!async_);
-  if (size < 0)
+  if (size < 0) {
     return -1;
+  }
 
   SCOPED_FILE_TRACE_WITH_SIZE("ReadAtCurrentPos", size);
 
@@ -108,8 +113,9 @@
     // and eliminate this cast.
     return checked_cast<int>(bytes_read);
   }
-  if (ERROR_HANDLE_EOF == GetLastError())
+  if (ERROR_HANDLE_EOF == GetLastError()) {
     return 0;
+  }
 
   return -1;
 }
@@ -130,8 +136,9 @@
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   DCHECK(IsValid());
   DCHECK(!async_);
-  if (size < 0 || offset < 0)
+  if (size < 0 || offset < 0) {
     return -1;
+  }
 
   SCOPED_FILE_TRACE_WITH_SIZE("Write", size);
 
@@ -144,8 +151,9 @@
 
   DWORD bytes_written;
   if (::WriteFile(file_.get(), data, static_cast<DWORD>(size), &bytes_written,
-                  &overlapped))
+                  &overlapped)) {
     return static_cast<int>(bytes_written);
+  }
 
   return -1;
 }
@@ -154,15 +162,17 @@
   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
   DCHECK(IsValid());
   DCHECK(!async_);
-  if (size < 0)
+  if (size < 0) {
     return -1;
+  }
 
   SCOPED_FILE_TRACE_WITH_SIZE("WriteAtCurrentPos", size);
 
   DWORD bytes_written;
   if (::WriteFile(file_.get(), data, static_cast<DWORD>(size), &bytes_written,
-                  NULL))
+                  NULL)) {
     return static_cast<int>(bytes_written);
+  }
 
   return -1;
 }
@@ -179,8 +189,9 @@
   SCOPED_FILE_TRACE("GetLength");
 
   LARGE_INTEGER size;
-  if (!::GetFileSizeEx(file_.get(), &size))
+  if (!::GetFileSizeEx(file_.get(), &size)) {
     return -1;
+  }
 
   return static_cast<int64_t>(size.QuadPart);
 }
@@ -195,15 +206,17 @@
   LARGE_INTEGER file_pointer;
   LARGE_INTEGER zero;
   zero.QuadPart = 0;
-  if (!::SetFilePointerEx(file_.get(), zero, &file_pointer, FILE_CURRENT))
+  if (!::SetFilePointerEx(file_.get(), zero, &file_pointer, FILE_CURRENT)) {
     return false;
+  }
 
   LARGE_INTEGER length_li;
   length_li.QuadPart = length;
   // If length > file size, SetFilePointerEx() should extend the file
   // with zeroes on all Windows standard file systems (NTFS, FATxx).
-  if (!::SetFilePointerEx(file_.get(), length_li, NULL, FILE_BEGIN))
+  if (!::SetFilePointerEx(file_.get(), length_li, NULL, FILE_BEGIN)) {
     return false;
+  }
 
   // Set the new file length and move the file pointer to its old position.
   // This is consistent with ftruncate()'s behavior, even when the file
@@ -235,8 +248,9 @@
   SCOPED_FILE_TRACE("GetInfo");
 
   BY_HANDLE_FILE_INFORMATION file_info;
-  if (!GetFileInformationByHandle(file_.get(), &file_info))
+  if (!GetFileInformationByHandle(file_.get(), &file_info)) {
     return false;
+  }
 
   ULARGE_INTEGER size;
   size.HighPart = file_info.nFileSizeHigh;
@@ -278,8 +292,9 @@
       LockFileEx(file_.get(), LockFileFlagsForMode(mode), /*dwReserved=*/0,
                  /*nNumberOfBytesToLockLow=*/MAXDWORD,
                  /*nNumberOfBytesToLockHigh=*/MAXDWORD, &overlapped);
-  if (!result)
+  if (!result) {
     return GetLastFileError();
+  }
   return FILE_OK;
 }
 
@@ -293,14 +308,16 @@
       UnlockFileEx(file_.get(), /*dwReserved=*/0,
                    /*nNumberOfBytesToLockLow=*/MAXDWORD,
                    /*nNumberOfBytesToLockHigh=*/MAXDWORD, &overlapped);
-  if (!result)
+  if (!result) {
     return GetLastFileError();
+  }
   return FILE_OK;
 }
 
 File File::Duplicate() const {
-  if (!IsValid())
+  if (!IsValid()) {
     return File();
+  }
 
   SCOPED_FILE_TRACE("Duplicate");
 
@@ -310,7 +327,7 @@
                          GetPlatformFile(),
                          GetCurrentProcess(),  // hTargetProcessHandle
                          &other_handle,
-                         0,  // dwDesiredAccess ignored due to SAME_ACCESS
+                         0,      // dwDesiredAccess ignored due to SAME_ACCESS
                          FALSE,  // !bInheritHandle
                          DUPLICATE_SAME_ACCESS)) {
     return File(GetLastFileError());
@@ -375,8 +392,9 @@
 
   DWORD disposition = 0;
 
-  if (flags & FLAG_OPEN)
+  if (flags & FLAG_OPEN) {
     disposition = OPEN_EXISTING;
+  }
 
   if (flags & FLAG_CREATE) {
     DCHECK(!disposition);
@@ -403,44 +421,56 @@
   CHECK(disposition);
 
   DWORD access = 0;
-  if (flags & FLAG_WRITE)
+  if (flags & FLAG_WRITE) {
     access = GENERIC_WRITE;
+  }
   if (flags & FLAG_APPEND) {
     DCHECK(!access);
     access = FILE_APPEND_DATA;
   }
-  if (flags & FLAG_READ)
+  if (flags & FLAG_READ) {
     access |= GENERIC_READ;
-  if (flags & FLAG_WRITE_ATTRIBUTES)
+  }
+  if (flags & FLAG_WRITE_ATTRIBUTES) {
     access |= FILE_WRITE_ATTRIBUTES;
+  }
   if (flags & FLAG_WIN_EXECUTE) {
     // Specifying both FLAG_WIN_EXECUTE and FLAG_WIN_NO_EXECUTE would
     // constitute a security risk, so deny the access here.
     CHECK_EQ(flags & FLAG_WIN_NO_EXECUTE, 0U);
     access |= GENERIC_EXECUTE;
   }
-  if (flags & FLAG_CAN_DELETE_ON_CLOSE)
+  if (flags & FLAG_CAN_DELETE_ON_CLOSE) {
     access |= DELETE;
+  }
 
   DWORD sharing = (flags & FLAG_WIN_EXCLUSIVE_READ) ? 0 : FILE_SHARE_READ;
-  if (!(flags & FLAG_WIN_EXCLUSIVE_WRITE))
+  if (!(flags & FLAG_WIN_EXCLUSIVE_WRITE)) {
     sharing |= FILE_SHARE_WRITE;
-  if (flags & FLAG_WIN_SHARE_DELETE)
+  }
+  if (flags & FLAG_WIN_SHARE_DELETE) {
     sharing |= FILE_SHARE_DELETE;
+  }
 
   DWORD create_flags = 0;
-  if (flags & FLAG_ASYNC)
+  if (flags & FLAG_ASYNC) {
     create_flags |= FILE_FLAG_OVERLAPPED;
-  if (flags & FLAG_WIN_TEMPORARY)
+  }
+  if (flags & FLAG_WIN_TEMPORARY) {
     create_flags |= FILE_ATTRIBUTE_TEMPORARY;
-  if (flags & FLAG_WIN_HIDDEN)
+  }
+  if (flags & FLAG_WIN_HIDDEN) {
     create_flags |= FILE_ATTRIBUTE_HIDDEN;
-  if (flags & FLAG_DELETE_ON_CLOSE)
+  }
+  if (flags & FLAG_DELETE_ON_CLOSE) {
     create_flags |= FILE_FLAG_DELETE_ON_CLOSE;
-  if (flags & FLAG_WIN_BACKUP_SEMANTICS)
+  }
+  if (flags & FLAG_WIN_BACKUP_SEMANTICS) {
     create_flags |= FILE_FLAG_BACKUP_SEMANTICS;
-  if (flags & FLAG_WIN_SEQUENTIAL_SCAN)
+  }
+  if (flags & FLAG_WIN_SEQUENTIAL_SCAN) {
     create_flags |= FILE_FLAG_SEQUENTIAL_SCAN;
+  }
 
   file_.Set(CreateFile(path.value().c_str(), access, sharing, NULL, disposition,
                        create_flags, NULL));
@@ -449,10 +479,11 @@
     error_details_ = FILE_OK;
     async_ = ((flags & FLAG_ASYNC) == FLAG_ASYNC);
 
-    if (flags & (FLAG_OPEN_ALWAYS))
+    if (flags & (FLAG_OPEN_ALWAYS)) {
       created_ = (ERROR_ALREADY_EXISTS != GetLastError());
-    else if (flags & (FLAG_CREATE_ALWAYS | FLAG_CREATE))
+    } else if (flags & (FLAG_CREATE_ALWAYS | FLAG_CREATE)) {
       created_ = true;
+    }
     if (flags & FLAG_WIN_NO_EXECUTE) {
       // These two DCHECKs make sure that no callers are trying to remove
       // execute permission from a file that might need to be mapped executable
diff --git a/tot/base/files/important_file_writer.cc b/tot/base/files/important_file_writer.cc
index e0d7d75..d7f556c 100644
--- a/tot/base/files/important_file_writer.cc
+++ b/tot/base/files/important_file_writer.cc
@@ -17,6 +17,7 @@
 #include <string>
 #include <string_view>
 #include <utility>
+#include <variant>
 
 #include "base/check_op.h"
 #include "base/critical_closure.h"
@@ -40,7 +41,6 @@
 #include "base/threading/thread.h"
 #include "base/time/time.h"
 #include "build/build_config.h"
-#include "build/chromeos_buildflags.h"
 
 namespace base {
 
@@ -136,8 +136,9 @@
 #if BUILDFLAG(IS_WIN)
   // Mark the file for deletion when it is closed and then close it implicitly.
   if (tmp_file.IsValid()) {
-    if (tmp_file.DeleteOnClose(true))
+    if (tmp_file.DeleteOnClose(true)) {
       return;
+    }
     // The file was opened with exclusive r/w access, so failures are primarily
     // due to I/O errors or other phenomena out of the process's control. Go
     // ahead and close the file. The call to DeleteFile below will basically
@@ -192,8 +193,9 @@
     return;
   }
 
-  if (!before_write_callback.is_null())
+  if (!before_write_callback.is_null()) {
     std::move(before_write_callback).Run();
+  }
 
   // Calling the impl by way of the private
   // ProduceAndWriteStringToFileAtomically, which originated from an
@@ -202,8 +204,9 @@
                                               /*from_instance=*/true,
                                               std::move(replace_file_callback));
 
-  if (!after_write_callback.is_null())
+  if (!after_write_callback.is_null()) {
     std::move(after_write_callback).Run(result);
+  }
 }
 
 // static
@@ -214,8 +217,9 @@
     bool from_instance,
     ReplaceFileCallback replace_file_callback) {
   const TimeTicks write_start = TimeTicks::Now();
-  if (!from_instance)
+  if (!from_instance) {
     ImportantFileWriterCleaner::AddDirectory(path.DirName());
+  }
 
 #if BUILDFLAG(IS_WIN) && DCHECK_IS_ON()
   // In https://crbug.com/920174, we have cases where CreateTemporaryFileInDir
@@ -226,7 +230,7 @@
   base::debug::Alias(path_copy);
 #endif  // BUILDFLAG(IS_WIN) && DCHECK_IS_ON()
 
-#if BUILDFLAG(IS_CHROMEOS_ASH)
+#if BUILDFLAG(IS_CHROMEOS)
   // On Chrome OS, chrome gets killed when it cannot finish shutdown quickly,
   // and this function seems to be one of the slowest shutdown steps.
   // Include some info to the report for investigation. crbug.com/418627
@@ -442,14 +446,14 @@
 
 void ImportantFileWriter::DoScheduledWrite() {
   // One of the serializers should be set.
-  DCHECK(!absl::holds_alternative<absl::monostate>(serializer_));
+  DCHECK(!std::holds_alternative<std::monostate>(serializer_));
 
   const TimeTicks serialization_start = TimeTicks::Now();
   BackgroundDataProducerCallback data_producer_for_background_sequence;
 
-  if (absl::holds_alternative<DataSerializer*>(serializer_)) {
+  if (std::holds_alternative<DataSerializer*>(serializer_)) {
     std::optional<std::string> data;
-    data = absl::get<DataSerializer*>(serializer_)->SerializeData();
+    data = std::get<DataSerializer*>(serializer_)->SerializeData();
     if (!data) {
       DLOG(WARNING) << "Failed to serialize data to be saved in "
                     << path_.value();
@@ -463,7 +467,7 @@
         std::move(data).value());
   } else {
     data_producer_for_background_sequence =
-        absl::get<BackgroundDataSerializer*>(serializer_)
+        std::get<BackgroundDataSerializer*>(serializer_)
             ->GetSerializedDataProducerForBackgroundSequence();
 
     DCHECK(data_producer_for_background_sequence);
@@ -489,7 +493,7 @@
 
 void ImportantFileWriter::ClearPendingWrite() {
   timer().Stop();
-  serializer_.emplace<absl::monostate>();
+  serializer_.emplace<std::monostate>();
 }
 
 void ImportantFileWriter::SetTimerForTesting(OneShotTimer* timer_override) {
diff --git a/tot/base/files/important_file_writer.h b/tot/base/files/important_file_writer.h
index 61ccb7e..3054afd 100644
--- a/tot/base/files/important_file_writer.h
+++ b/tot/base/files/important_file_writer.h
@@ -9,6 +9,7 @@
 #include <optional>
 #include <string>
 #include <string_view>
+#include <variant>
 
 #include "base/base_export.h"
 #include "base/compiler_specific.h"
@@ -19,7 +20,6 @@
 #include "base/sequence_checker.h"
 #include "base/time/time.h"
 #include "base/timer/timer.h"
-#include "third_party/abseil-cpp/absl/types/variant.h"
 
 namespace base {
 
@@ -142,9 +142,7 @@
       OnceClosure before_next_write_callback,
       OnceCallback<void(bool success)> after_next_write_callback);
 
-  TimeDelta commit_interval() const {
-    return commit_interval_;
-  }
+  TimeDelta commit_interval() const { return commit_interval_; }
 
   // Overrides the timer to use for scheduling writes with |timer_override|.
   void SetTimerForTesting(OneShotTimer* timer_override);
@@ -215,7 +213,7 @@
   raw_ptr<OneShotTimer> timer_override_ = nullptr;
 
   // Serializer which will provide the data to be saved.
-  absl::variant<absl::monostate, DataSerializer*, BackgroundDataSerializer*>
+  std::variant<std::monostate, DataSerializer*, BackgroundDataSerializer*>
       serializer_;
 
   // Time delta after which scheduled data will be written to disk.
diff --git a/tot/base/files/important_file_writer_cleaner.cc b/tot/base/files/important_file_writer_cleaner.cc
index 46e1263..6d69b9a 100644
--- a/tot/base/files/important_file_writer_cleaner.cc
+++ b/tot/base/files/important_file_writer_cleaner.cc
@@ -53,8 +53,9 @@
     AutoLock scoped_lock(instance.task_runner_lock_);
     task_runner = instance.task_runner_;
   }
-  if (!task_runner)
+  if (!task_runner) {
     return;
+  }
   if (task_runner->RunsTasksInCurrentSequence()) {
     instance.AddDirectoryImpl(directory);
   } else {
@@ -82,25 +83,29 @@
 #endif
   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
 
-  if (is_started())
+  if (is_started()) {
     return;
+  }
 
   started_ = true;
 
-  if (!pending_directories_.empty())
+  if (!pending_directories_.empty()) {
     ScheduleTask();
+  }
 }
 
 void ImportantFileWriterCleaner::Stop() {
   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
 
-  if (!is_started())
+  if (!is_started()) {
     return;
+  }
 
-  if (is_running())
+  if (is_running()) {
     stop_flag_.store(true, std::memory_order_relaxed);
-  else
+  } else {
     DoStop();
+  }
 }
 
 void ImportantFileWriterCleaner::UninitializeForTesting() {
@@ -129,20 +134,23 @@
 void ImportantFileWriterCleaner::AddDirectoryImpl(const FilePath& directory) {
   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
 
-  if (!important_directories_.insert(directory).second)
+  if (!important_directories_.insert(directory).second) {
     return;  // This directory has already been seen.
+  }
 
   pending_directories_.push_back(directory);
 
-  if (!is_started())
+  if (!is_started()) {
     return;  // Nothing more to do if Start() has not been called.
+  }
 
   // Start the background task if it's not already running. If it is running, a
   // new task will be posted on completion of the current one by
   // OnBackgroundTaskFinished to handle all directories added while it was
   // running.
-  if (!is_running())
+  if (!is_running()) {
     ScheduleTask();
+  }
 }
 
 void ImportantFileWriterCleaner::ScheduleTask() {
@@ -171,24 +179,24 @@
     std::vector<FilePath> directories,
     std::atomic_bool& stop_flag) {
   DCHECK(!directories.empty());
-  for (auto scan = directories.begin(), end = directories.end(); scan != end;
-       ++scan) {
-    const auto& directory = *scan;
+  for (auto& directory : directories) {
     FileEnumerator file_enum(
         directory, /*recursive=*/false, FileEnumerator::FILES,
         FormatTemporaryFileName(FILE_PATH_LITERAL("*")).value());
     for (FilePath path = file_enum.Next(); !path.empty();
          path = file_enum.Next()) {
       const FileEnumerator::FileInfo info = file_enum.GetInfo();
-      if (info.GetLastModifiedTime() >= upper_bound_time)
+      if (info.GetLastModifiedTime() >= upper_bound_time) {
         continue;
+      }
       // Cleanup is a best-effort process, so ignore any failures here and
       // continue to clean as much as possible. Metrics tell us that ~98.4% of
       // directories are cleaned with no failures.
       DeleteFile(path);
       // Break out without checking for the next file if a stop is requested.
-      if (stop_flag.load(std::memory_order_relaxed))
+      if (stop_flag.load(std::memory_order_relaxed)) {
         return false;
+      }
     }
   }
   return true;
diff --git a/tot/base/files/important_file_writer_unittest.cc b/tot/base/files/important_file_writer_unittest.cc
index 12fbdb3..bc6b979 100644
--- a/tot/base/files/important_file_writer_unittest.cc
+++ b/tot/base/files/important_file_writer_unittest.cc
@@ -43,8 +43,7 @@
 
 class DataSerializer : public ImportantFileWriter::DataSerializer {
  public:
-  explicit DataSerializer(const std::string& data) : data_(data) {
-  }
+  explicit DataSerializer(const std::string& data) : data_(data) {}
 
   std::optional<std::string> SerializeData() override {
     EXPECT_TRUE(sequence_checker_.CalledOnValidSequence());
diff --git a/tot/base/files/memory_mapped_file.cc b/tot/base/files/memory_mapped_file.cc
index 7b3ba33..5cb1066 100644
--- a/tot/base/files/memory_mapped_file.cc
+++ b/tot/base/files/memory_mapped_file.cc
@@ -23,8 +23,9 @@
 
 #if !BUILDFLAG(IS_NACL)
 bool MemoryMappedFile::Initialize(const FilePath& file_name, Access access) {
-  if (IsValid())
+  if (IsValid()) {
     return false;
+  }
 
   uint32_t flags = 0;
   switch (access) {
@@ -103,11 +104,13 @@
 #endif
   }
 
-  if (IsValid())
+  if (IsValid()) {
     return false;
+  }
 
-  if (region != Region::kWholeFile)
+  if (region != Region::kWholeFile) {
     DCHECK_GE(region.offset, 0);
+  }
 
   file_ = std::move(file);
 
diff --git a/tot/base/files/memory_mapped_file_posix.cc b/tot/base/files/memory_mapped_file_posix.cc
index f22eb30..3e59997 100644
--- a/tot/base/files/memory_mapped_file_posix.cc
+++ b/tot/base/files/memory_mapped_file_posix.cc
@@ -38,8 +38,9 @@
       DPLOG(ERROR) << "fstat " << file_.GetPlatformFile();
       return false;
     }
-    if (!IsValueInRangeForNumericType<size_t>(file_len))
+    if (!IsValueInRangeForNumericType<size_t>(file_len)) {
       return false;
+    }
     map_size = base::checked_cast<size_t>(file_len);
     byte_size = map_size;
   } else {
@@ -49,11 +50,8 @@
     // |region| and then add up the |data_offset| displacement.
     int64_t aligned_start = 0;
     size_t aligned_size = 0u;
-    CalculateVMAlignedBoundaries(region.offset,
-                                 region.size,
-                                 &aligned_start,
-                                 &aligned_size,
-                                 &data_offset);
+    CalculateVMAlignedBoundaries(region.offset, region.size, &aligned_start,
+                                 &aligned_size, &data_offset);
 
     // Ensure that the casts in the mmap call below are sane.
     if (aligned_start < 0 ||
@@ -92,8 +90,9 @@
     case READ_WRITE_EXTEND:
       prot |= PROT_READ | PROT_WRITE;
 
-      if (!AllocateFileRegion(&file_, region.offset, region.size))
+      if (!AllocateFileRegion(&file_, region.offset, region.size)) {
         return false;
+      }
 
       break;
   }
diff --git a/tot/base/files/memory_mapped_file_unittest.cc b/tot/base/files/memory_mapped_file_unittest.cc
index b5a42b9..c06b9e0 100644
--- a/tot/base/files/memory_mapped_file_unittest.cc
+++ b/tot/base/files/memory_mapped_file_unittest.cc
@@ -32,8 +32,9 @@
 // Create a temporary buffer and fill it with a watermark sequence.
 base::HeapArray<uint8_t> CreateTestBuffer(size_t size, size_t offset) {
   auto buf = base::HeapArray<uint8_t>::Uninit(size);
-  for (size_t i = 0; i < size; ++i)
+  for (size_t i = 0; i < size; ++i) {
     buf[i] = static_cast<uint8_t>((offset + i) % 253);
+  }
   return buf;
 }
 
diff --git a/tot/base/files/memory_mapped_file_win.cc b/tot/base/files/memory_mapped_file_win.cc
index f3c3a48..44453c2 100644
--- a/tot/base/files/memory_mapped_file_win.cc
+++ b/tot/base/files/memory_mapped_file_win.cc
@@ -31,14 +31,16 @@
   // ::MapViewOfFile() need to be self consistent as far as access rights and
   // type of mapping or one or more of them will fail in non-obvious ways.
 
-  if (!file_.IsValid())
+  if (!file_.IsValid()) {
     return false;
+  }
 
   file_mapping_.Set(::CreateFileMapping(file_.GetPlatformFile(), nullptr,
                                         PAGE_READONLY | SEC_IMAGE_NO_EXECUTE, 0,
                                         0, NULL));
-  if (!file_mapping_.is_valid())
+  if (!file_mapping_.is_valid()) {
     return false;
+  }
 
   auto* ptr = static_cast<uint8_t*>(
       ::MapViewOfFile(file_mapping_.get(), FILE_MAP_READ, 0, 0, 0));
@@ -67,8 +69,9 @@
 
   DCHECK(access != READ_CODE_IMAGE || region == Region::kWholeFile);
 
-  if (!file_.IsValid())
+  if (!file_.IsValid()) {
     return false;
+  }
 
   DWORD view_access;
   DWORD flags = 0;
@@ -97,8 +100,9 @@
 
   file_mapping_.Set(::CreateFileMapping(file_.GetPlatformFile(), NULL, flags,
                                         size.HighPart, size.LowPart, NULL));
-  if (!file_mapping_.is_valid())
+  if (!file_mapping_.is_valid()) {
     return false;
+  }
 
   ULARGE_INTEGER map_start = {};
   SIZE_T map_size = 0u;
@@ -182,10 +186,12 @@
   if (!bytes_.empty()) {
     ::UnmapViewOfFile(bytes_.data());
   }
-  if (file_mapping_.is_valid())
+  if (file_mapping_.is_valid()) {
     file_mapping_.Close();
-  if (file_.IsValid())
+  }
+  if (file_.IsValid()) {
     file_.Close();
+  }
 
   bytes_ = base::span<uint8_t>();
 }
diff --git a/tot/base/files/os_validation_win_unittest.cc b/tot/base/files/os_validation_win_unittest.cc
index 8746125..e9a4093 100644
--- a/tot/base/files/os_validation_win_unittest.cc
+++ b/tot/base/files/os_validation_win_unittest.cc
@@ -224,8 +224,9 @@
     while (bits_begin < bits_end) {
       const BitAndName& bit_name = *bits_begin;
       if (bitfield & bit_name.bit) {
-        if (!result->empty())
+        if (!result->empty()) {
           result->append(" | ");
+        }
         result->append(bit_name.name);
         bitfield &= ~bit_name.bit;
       }
@@ -270,8 +271,9 @@
 // deletion.
 TEST_P(OpenFileTest, DeleteThenMove) {
   // Don't test combinations that cannot be deleted.
-  if (!CanMoveFile(access(), share_mode()))
+  if (!CanMoveFile(access(), share_mode())) {
     return;
+  }
   ASSERT_NE(::DeleteFileW(temp_file_path().value().c_str()), 0)
       << "Last error code: " << ::GetLastError();
   // Move fails with ERROR_ACCESS_DENIED (STATUS_DELETE_PENDING under the
@@ -285,8 +287,9 @@
 // deleted.
 TEST_P(OpenFileTest, MapThenDelete) {
   // There is nothing to test if the file can't be read.
-  if (!(access() & FILE_READ_DATA))
+  if (!(access() & FILE_READ_DATA)) {
     return;
+  }
 
   // Pick the protection option that matches the access rights used to open the
   // file.
diff --git a/tot/base/files/safe_base_name.cc b/tot/base/files/safe_base_name.cc
index 0b17f31..15bfb87 100644
--- a/tot/base/files/safe_base_name.cc
+++ b/tot/base/files/safe_base_name.cc
@@ -20,7 +20,7 @@
 
 // static
 std::optional<SafeBaseName> SafeBaseName::Create(
-    FilePath::StringPieceType path) {
+    FilePath::StringViewType path) {
   return Create(FilePath(path));
 }
 
diff --git a/tot/base/files/safe_base_name.h b/tot/base/files/safe_base_name.h
index a3f3114..9a67817 100644
--- a/tot/base/files/safe_base_name.h
+++ b/tot/base/files/safe_base_name.h
@@ -29,8 +29,8 @@
   // Factory method that returns a valid SafeBaseName or std::nullopt.
   static std::optional<SafeBaseName> Create(const FilePath&);
 
-  // Same as above, but takes a StringPieceType for convenience.
-  static std::optional<SafeBaseName> Create(FilePath::StringPieceType);
+  // Same as above, but takes a StringViewType for convenience.
+  static std::optional<SafeBaseName> Create(FilePath::StringViewType);
   const FilePath& path() const LIFETIME_BOUND { return path_; }
 
   // Convenience functions.
diff --git a/tot/base/files/safe_base_name_unittest.cc b/tot/base/files/safe_base_name_unittest.cc
index 6443fbd..e943d0b 100644
--- a/tot/base/files/safe_base_name_unittest.cc
+++ b/tot/base/files/safe_base_name_unittest.cc
@@ -76,4 +76,4 @@
   EXPECT_EQ(basename->path(), FilePath(FILE_PATH_LITERAL("bar")));
 }
 
-}  // namespace base
\ No newline at end of file
+}  // namespace base
diff --git a/tot/base/files/scoped_file_linux.cc b/tot/base/files/scoped_file_linux.cc
index 5074ef4..25cf35b 100644
--- a/tot/base/files/scoped_file_linux.cc
+++ b/tot/base/files/scoped_file_linux.cc
@@ -102,8 +102,9 @@
 NO_SANITIZE("cfi-icall")
 __attribute__((visibility("default"), noinline)) int close(int fd) {
   static LibcCloseFuncPtr libc_close = LoadCloseSymbol();
-  if (base::IsFDOwned(fd) && g_is_ownership_enforced)
+  if (base::IsFDOwned(fd) && g_is_ownership_enforced) {
     CrashOnFdOwnershipViolation();
+  }
   if (libc_close == nullptr) {
     RAW_LOG(ERROR, "close symbol missing\n");
     base::ImmediateCrash();
@@ -111,5 +112,5 @@
   return libc_close(fd);
 }
 
-}  // extern "C"
+}       // extern "C"
 #endif  // !defined(COMPONENT_BUILD)
diff --git a/tot/base/files/scoped_temp_dir.cc b/tot/base/files/scoped_temp_dir.cc
index 4a2ea4e..42db9c1 100644
--- a/tot/base/files/scoped_temp_dir.cc
+++ b/tot/base/files/scoped_temp_dir.cc
@@ -22,58 +22,68 @@
     : path_(other.Take()) {}
 
 ScopedTempDir& ScopedTempDir::operator=(ScopedTempDir&& other) {
-  if (!path_.empty() && !Delete())
+  if (!path_.empty() && !Delete()) {
     DLOG(WARNING) << "Could not delete temp dir in operator=().";
+  }
   path_ = other.Take();
   return *this;
 }
 
 ScopedTempDir::~ScopedTempDir() {
-  if (!path_.empty() && !Delete())
+  if (!path_.empty() && !Delete()) {
     DLOG(WARNING) << "Could not delete temp dir in dtor.";
+  }
 }
 
 bool ScopedTempDir::CreateUniqueTempDir() {
-  if (!path_.empty())
+  if (!path_.empty()) {
     return false;
+  }
 
   // This "scoped_dir" prefix is only used on Windows and serves as a template
   // for the unique name.
-  if (!CreateNewTempDirectory(kScopedDirPrefix, &path_))
+  if (!CreateNewTempDirectory(kScopedDirPrefix, &path_)) {
     return false;
+  }
 
   return true;
 }
 
 bool ScopedTempDir::CreateUniqueTempDirUnderPath(const FilePath& base_path) {
-  if (!path_.empty())
+  if (!path_.empty()) {
     return false;
+  }
 
   // If |base_path| does not exist, create it.
-  if (!CreateDirectory(base_path))
+  if (!CreateDirectory(base_path)) {
     return false;
+  }
 
   // Create a new, uniquely named directory under |base_path|.
-  if (!CreateTemporaryDirInDir(base_path, kScopedDirPrefix, &path_))
+  if (!CreateTemporaryDirInDir(base_path, kScopedDirPrefix, &path_)) {
     return false;
+  }
 
   return true;
 }
 
 bool ScopedTempDir::Set(const FilePath& path) {
-  if (!path_.empty())
+  if (!path_.empty()) {
     return false;
+  }
 
-  if (!DirectoryExists(path) && !CreateDirectory(path))
+  if (!DirectoryExists(path) && !CreateDirectory(path)) {
     return false;
+  }
 
   path_ = path;
   return true;
 }
 
 bool ScopedTempDir::Delete() {
-  if (path_.empty())
+  if (path_.empty()) {
     return false;
+  }
 
   bool ret = DeletePathRecursively(path_);
   if (ret) {
diff --git a/tot/base/files/scoped_temp_dir_unittest.cc b/tot/base/files/scoped_temp_dir_unittest.cc
index ab45404..515b9ec 100644
--- a/tot/base/files/scoped_temp_dir_unittest.cc
+++ b/tot/base/files/scoped_temp_dir_unittest.cc
@@ -2,11 +2,12 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "base/files/scoped_temp_dir.h"
+
 #include <string>
 
 #include "base/files/file.h"
 #include "base/files/file_util.h"
-#include "base/files/scoped_temp_dir.h"
 #include "base/path_service.h"
 #include "build/build_config.h"
 #include "testing/gtest/include/gtest/gtest.h"
@@ -118,7 +119,7 @@
     ScopedTempDir other_dir(std::move(dir));
     EXPECT_EQ(dir_path, other_dir.GetPath());
     EXPECT_TRUE(DirectoryExists(dir_path));
-    EXPECT_FALSE(dir.IsValid());
+    EXPECT_FALSE(dir.IsValid());  // NOLINT(bugprone-use-after-move)
   }
   EXPECT_FALSE(DirectoryExists(dir_path));
 }
@@ -131,7 +132,7 @@
             File::FLAG_CREATE_ALWAYS | File::FLAG_WRITE);
   EXPECT_TRUE(file.IsValid());
   EXPECT_EQ(File::FILE_OK, file.error_details());
-  EXPECT_FALSE(dir.Delete());  // We should not be able to delete.
+  EXPECT_FALSE(dir.Delete());           // We should not be able to delete.
   EXPECT_FALSE(dir.GetPath().empty());  // We should still have a valid path.
   file.Close();
   // Now, we should be able to delete.
diff --git a/tot/base/files/scoped_temp_file_unittest.cc b/tot/base/files/scoped_temp_file_unittest.cc
index 3686a93..b306688 100644
--- a/tot/base/files/scoped_temp_file_unittest.cc
+++ b/tot/base/files/scoped_temp_file_unittest.cc
@@ -29,7 +29,7 @@
   EXPECT_TRUE(PathExists(file1));
 
   ScopedTempFile temp2(std::move(temp1));
-  EXPECT_TRUE(temp1.path().empty());
+  EXPECT_TRUE(temp1.path().empty());  // NOLINT(bugprone-use-after-move)
   EXPECT_EQ(file1, temp2.path());
   EXPECT_TRUE(PathExists(file1));
 }
@@ -46,7 +46,7 @@
   EXPECT_TRUE(PathExists(file2));
 
   temp2 = std::move(temp1);
-  EXPECT_TRUE(temp1.path().empty());
+  EXPECT_TRUE(temp1.path().empty());  // NOLINT(bugprone-use-after-move)
   EXPECT_EQ(temp2.path(), file1);
   EXPECT_TRUE(PathExists(file1));
   EXPECT_FALSE(PathExists(file2));
diff --git a/tot/base/fuchsia/default_job.cc b/tot/base/fuchsia/default_job.cc
index 460f6d9..47b494f 100644
--- a/tot/base/fuchsia/default_job.cc
+++ b/tot/base/fuchsia/default_job.cc
@@ -15,8 +15,9 @@
 }
 
 zx::unowned_job GetDefaultJob() {
-  if (g_job == ZX_HANDLE_INVALID)
+  if (g_job == ZX_HANDLE_INVALID) {
     return zx::job::default_job();
+  }
   return zx::unowned_job(g_job);
 }
 
diff --git a/tot/base/fuchsia/filtered_service_directory.cc b/tot/base/fuchsia/filtered_service_directory.cc
index fe0642b..40ba5c7 100644
--- a/tot/base/fuchsia/filtered_service_directory.cc
+++ b/tot/base/fuchsia/filtered_service_directory.cc
@@ -4,6 +4,7 @@
 
 #include "base/fuchsia/filtered_service_directory.h"
 
+#include <fidl/fuchsia.io/cpp/common_types.h>
 #include <lib/async/default.h>
 #include <lib/vfs/cpp/pseudo_dir.h>
 #include <lib/vfs/cpp/service.h>
@@ -36,12 +37,11 @@
 
 zx_status_t FilteredServiceDirectory::ConnectClient(
     fidl::InterfaceRequest<fuchsia::io::Directory> dir_request) {
-  // sys::OutgoingDirectory puts public services under ./svc . Connect to that
-  // directory and return client handle for the connection,
+  // sys::OutgoingDirectory puts public services under /svc. Open that
+  // directory and return client handle for the connection.
   return outgoing_directory_.GetOrCreateDirectory("svc")->Serve(
-      fuchsia::io::OpenFlags::RIGHT_READABLE |
-          fuchsia::io::OpenFlags::RIGHT_WRITABLE,
-      dir_request.TakeChannel());
+      fuchsia_io::wire::kPermReadable,
+      fidl::ServerEnd<fuchsia_io::Directory>(dir_request.TakeChannel()));
 }
 
 }  // namespace base
diff --git a/tot/base/fuchsia/intl_profile_watcher.cc b/tot/base/fuchsia/intl_profile_watcher.cc
index 467a935..5b82f1d 100644
--- a/tot/base/fuchsia/intl_profile_watcher.cc
+++ b/tot/base/fuchsia/intl_profile_watcher.cc
@@ -6,6 +6,7 @@
 
 #include <fuchsia/intl/cpp/fidl.h>
 #include <lib/sys/cpp/component_context.h>
+
 #include <string>
 #include <vector>
 
diff --git a/tot/base/fuchsia/intl_profile_watcher.h b/tot/base/fuchsia/intl_profile_watcher.h
index ce9f7fd..d3a9793 100644
--- a/tot/base/fuchsia/intl_profile_watcher.h
+++ b/tot/base/fuchsia/intl_profile_watcher.h
@@ -6,6 +6,7 @@
 #define BASE_FUCHSIA_INTL_PROFILE_WATCHER_H_
 
 #include <fuchsia/intl/cpp/fidl.h>
+
 #include <string>
 
 #include "base/base_export.h"
diff --git a/tot/base/fuchsia/intl_profile_watcher_unittest.cc b/tot/base/fuchsia/intl_profile_watcher_unittest.cc
index e2194a9..7e9b733 100644
--- a/tot/base/fuchsia/intl_profile_watcher_unittest.cc
+++ b/tot/base/fuchsia/intl_profile_watcher_unittest.cc
@@ -6,6 +6,7 @@
 
 #include <fuchsia/intl/cpp/fidl_test_base.h>
 #include <lib/fidl/cpp/binding.h>
+
 #include <memory>
 #include <string>
 #include <vector>
diff --git a/tot/base/fuchsia/koid.cc b/tot/base/fuchsia/koid.cc
index 63f90c3..27a4f46 100644
--- a/tot/base/fuchsia/koid.cc
+++ b/tot/base/fuchsia/koid.cc
@@ -27,15 +27,17 @@
 
 std::optional<zx_koid_t> GetKoid(const zx::object_base& handle) {
   auto basic_info = GetBasicInfo(handle);
-  if (!basic_info)
+  if (!basic_info) {
     return {};
+  }
   return basic_info->koid;
 }
 
 std::optional<zx_koid_t> GetRelatedKoid(const zx::object_base& handle) {
   auto basic_info = GetBasicInfo(handle);
-  if (!basic_info)
+  if (!basic_info) {
     return {};
+  }
   return basic_info->related_koid;
 }
 
diff --git a/tot/base/fuchsia/mem_buffer_util.cc b/tot/base/fuchsia/mem_buffer_util.cc
index e0b5d70..448b89e 100644
--- a/tot/base/fuchsia/mem_buffer_util.cc
+++ b/tot/base/fuchsia/mem_buffer_util.cc
@@ -21,8 +21,9 @@
 std::optional<std::u16string> ReadUTF8FromVMOAsUTF16(
     const fuchsia::mem::Buffer& buffer) {
   std::optional<std::string> output_utf8 = StringFromMemBuffer(buffer);
-  if (!output_utf8)
+  if (!output_utf8) {
     return std::nullopt;
+  }
   std::u16string output;
   return UTF8ToUTF16(output_utf8->data(), output_utf8->size(), &output)
              ? std::optional<std::u16string>(std::move(output))
@@ -71,13 +72,15 @@
     return std::nullopt;
   }
 
-  if (size == 0)
+  if (size == 0) {
     return result;
+  }
 
   result.resize(size);
   status = vmo.read(&result[0], 0, size);
-  if (status == ZX_OK)
+  if (status == ZX_OK) {
     return result;
+  }
 
   ZX_LOG(ERROR, status) << "zx_vmo_read";
   return std::nullopt;
@@ -87,13 +90,15 @@
     const fuchsia::mem::Buffer& buffer) {
   std::string result;
 
-  if (buffer.size == 0)
+  if (buffer.size == 0) {
     return result;
+  }
 
   result.resize(buffer.size);
   zx_status_t status = buffer.vmo.read(&result[0], 0, buffer.size);
-  if (status == ZX_OK)
+  if (status == ZX_OK) {
     return result;
+  }
 
   ZX_LOG(ERROR, status) << "zx_vmo_read";
   return std::nullopt;
@@ -117,8 +122,9 @@
 }
 
 fuchsia::mem::Buffer MemBufferFromFile(File file) {
-  if (!file.IsValid())
+  if (!file.IsValid()) {
     return {};
+  }
 
   zx::vmo vmo;
   zx_status_t status =
diff --git a/tot/base/fuchsia/scoped_fx_logger.cc b/tot/base/fuchsia/scoped_fx_logger.cc
index 873bb91..b51abc9 100644
--- a/tot/base/fuchsia/scoped_fx_logger.cc
+++ b/tot/base/fuchsia/scoped_fx_logger.cc
@@ -107,8 +107,9 @@
                                 uint32_t line_number,
                                 std::string_view msg,
                                 logging::LogSeverity severity) {
-  if (!socket_.is_valid())
+  if (!socket_.is_valid()) {
     return;
+  }
 
   auto fuchsia_severity = LogSeverityToFuchsiaLogSeverity(severity);
 
@@ -117,15 +118,17 @@
   // global logs to the system logger.
 
   fuchsia_syslog::LogBuffer buffer;
-  buffer.BeginRecord(
-      fuchsia_severity, cpp17::string_view(file.data(), file.size()),
-      line_number, cpp17::string_view(msg.data(), msg.size()), socket_.borrow(),
-      0, base::Process::Current().Pid(), base::PlatformThread::CurrentId());
+  buffer.BeginRecord(fuchsia_severity,
+                     cpp17::string_view(file.data(), file.size()), line_number,
+                     cpp17::string_view(msg.data(), msg.size()),
+                     socket_.borrow(), 0, base::Process::Current().Pid(),
+                     base::PlatformThread::CurrentId().raw());
   for (const auto& tag : tags_) {
     buffer.WriteKeyValue("tag", tag);
   }
-  if (!buffer.FlushRecord())
+  if (!buffer.FlushRecord()) {
     fprintf(stderr, "fuchsia_syslog.LogBuffer.FlushRecord() failed\n");
+  }
 }
 
 ScopedFxLogger::ScopedFxLogger(std::vector<std::string_view> tags,
diff --git a/tot/base/fuchsia/scoped_natural_service_binding_unittest.cc b/tot/base/fuchsia/scoped_natural_service_binding_unittest.cc
index a1b6481..7d3846a 100644
--- a/tot/base/fuchsia/scoped_natural_service_binding_unittest.cc
+++ b/tot/base/fuchsia/scoped_natural_service_binding_unittest.cc
@@ -2,12 +2,11 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "base/fuchsia/scoped_service_binding.h"
-
 #include <lib/async/default.h>
 #include <lib/sys/cpp/component_context.h>
 
 #include "base/fuchsia/process_context.h"
+#include "base/fuchsia/scoped_service_binding.h"
 #include "base/fuchsia/test_component_context_for_process.h"
 #include "base/fuchsia/test_interface_natural_impl.h"
 #include "base/run_loop.h"
@@ -74,9 +73,9 @@
       fidl::CreateEndpoints<fuchsia_io::Directory>();
   ASSERT_TRUE(debug_directory_endpoints.is_ok())
       << debug_directory_endpoints.status_string();
-  debug_dir->Serve(fuchsia::io::OpenFlags::RIGHT_READABLE |
-                       fuchsia::io::OpenFlags::RIGHT_WRITABLE,
-                   debug_directory_endpoints->server.TakeChannel());
+  debug_dir->Serve(fuchsia_io::wire::kPermReadable,
+                   fidl::ServerEnd<fuchsia_io::Directory>(
+                       debug_directory_endpoints->server.TakeChannel()));
 
   // Attempt to connect via the "debug" directory.
   auto debug_stub =
diff --git a/tot/base/fuchsia/scoped_natural_service_publisher_unittest.cc b/tot/base/fuchsia/scoped_natural_service_publisher_unittest.cc
index c4e2428..f3a59a1 100644
--- a/tot/base/fuchsia/scoped_natural_service_publisher_unittest.cc
+++ b/tot/base/fuchsia/scoped_natural_service_publisher_unittest.cc
@@ -2,8 +2,6 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "base/fuchsia/scoped_service_publisher.h"
-
 #include <fidl/base.testfidl/cpp/fidl.h>
 #include <fuchsia/io/cpp/fidl.h>
 #include <lib/async/default.h>
@@ -14,6 +12,7 @@
 #include <lib/vfs/cpp/pseudo_dir.h>
 
 #include "base/fuchsia/process_context.h"
+#include "base/fuchsia/scoped_service_publisher.h"
 #include "base/fuchsia/test_component_context_for_process.h"
 #include "base/fuchsia/test_interface_natural_impl.h"
 #include "base/test/task_environment.h"
@@ -61,9 +60,9 @@
   auto pseudodir_endpoints = fidl::CreateEndpoints<fuchsia_io::Directory>();
   ASSERT_TRUE(pseudodir_endpoints.is_ok())
       << pseudodir_endpoints.status_string();
-  directory.Serve(fuchsia::io::OpenFlags::RIGHT_READABLE |
-                      fuchsia::io::OpenFlags::RIGHT_WRITABLE,
-                  pseudodir_endpoints->server.TakeChannel());
+  directory.Serve(fuchsia_io::wire::kPermReadable,
+                  fidl::ServerEnd<fuchsia_io::Directory>(
+                      pseudodir_endpoints->server.TakeChannel()));
 
   fidl::Client<base_testfidl::TestInterface> client_a;
 
diff --git a/tot/base/fuchsia/scoped_service_binding_unittest.cc b/tot/base/fuchsia/scoped_service_binding_unittest.cc
index 3af048e..edf7dd0 100644
--- a/tot/base/fuchsia/scoped_service_binding_unittest.cc
+++ b/tot/base/fuchsia/scoped_service_binding_unittest.cc
@@ -71,9 +71,9 @@
 
   // Connect a ServiceDirectory to the "debug" subdirectory.
   fidl::InterfaceHandle<fuchsia::io::Directory> debug_handle;
-  debug_dir->Serve(fuchsia::io::OpenFlags::RIGHT_READABLE |
-                       fuchsia::io::OpenFlags::RIGHT_WRITABLE,
-                   debug_handle.NewRequest().TakeChannel());
+  debug_dir->Serve(fuchsia_io::wire::kPermReadable,
+                   fidl::ServerEnd<fuchsia_io::Directory>(
+                       debug_handle.NewRequest().TakeChannel()));
   sys::ServiceDirectory debug_directory(std::move(debug_handle));
 
   // Attempt to connect via the "debug" directory.
@@ -171,9 +171,9 @@
 
   // Connect a ServiceDirectory to the "debug" subdirectory.
   fidl::InterfaceHandle<fuchsia::io::Directory> debug_handle;
-  debug_dir->Serve(fuchsia::io::OpenFlags::RIGHT_READABLE |
-                       fuchsia::io::OpenFlags::RIGHT_WRITABLE,
-                   debug_handle.NewRequest().TakeChannel());
+  debug_dir->Serve(fuchsia_io::wire::kPermReadable,
+                   fidl::ServerEnd<fuchsia_io::Directory>(
+                       debug_handle.NewRequest().TakeChannel()));
   sys::ServiceDirectory debug_directory(std::move(debug_handle));
 
   // Attempt to connect via the "debug" directory.
diff --git a/tot/base/fuchsia/scoped_service_publisher_unittest.cc b/tot/base/fuchsia/scoped_service_publisher_unittest.cc
index 7079117..2f55c43 100644
--- a/tot/base/fuchsia/scoped_service_publisher_unittest.cc
+++ b/tot/base/fuchsia/scoped_service_publisher_unittest.cc
@@ -56,9 +56,9 @@
 TEST_F(ScopedServicePublisherTest, PseudoDir) {
   vfs::PseudoDir directory;
   fidl::InterfaceHandle<fuchsia::io::Directory> directory_handle;
-  directory.Serve(fuchsia::io::OpenFlags::RIGHT_READABLE |
-                      fuchsia::io::OpenFlags::RIGHT_WRITABLE,
-                  directory_handle.NewRequest().TakeChannel());
+  directory.Serve(fuchsia_io::wire::kPermReadable,
+                  fidl::ServerEnd<fuchsia_io::Directory>(
+                      directory_handle.NewRequest().TakeChannel()));
   sys::ServiceDirectory services(std::move(directory_handle));
 
   fidl::InterfacePtr<testfidl::TestInterface> client_a;
diff --git a/tot/base/fuchsia/startup_context.cc b/tot/base/fuchsia/startup_context.cc
index 78210c5..3d384bf 100644
--- a/tot/base/fuchsia/startup_context.cc
+++ b/tot/base/fuchsia/startup_context.cc
@@ -4,13 +4,13 @@
 
 #include "base/fuchsia/startup_context.h"
 
-#include <tuple>
-#include <utility>
-
 #include <fuchsia/io/cpp/fidl.h>
 #include <lib/sys/cpp/outgoing_directory.h>
 #include <lib/sys/cpp/service_directory.h>
 
+#include <tuple>
+#include <utility>
+
 #include "base/check.h"
 #include "base/check_op.h"
 #include "base/fuchsia/file_utils.h"
diff --git a/tot/base/fuchsia/test_component_context_for_process.cc b/tot/base/fuchsia/test_component_context_for_process.cc
index d24611c..dd015cc 100644
--- a/tot/base/fuchsia/test_component_context_for_process.cc
+++ b/tot/base/fuchsia/test_component_context_for_process.cc
@@ -87,8 +87,9 @@
 
 void TestComponentContextForProcess::AddServices(
     base::span<const std::string_view> services) {
-  for (auto service : services)
+  for (auto service : services) {
     AddService(service);
+  }
 }
 
 fidl::UnownedClientEnd<fuchsia_io::Directory>
diff --git a/tot/base/fuchsia/test_component_context_for_process_unittest.cc b/tot/base/fuchsia/test_component_context_for_process_unittest.cc
index 21d1eaf..f5ef21f 100644
--- a/tot/base/fuchsia/test_component_context_for_process_unittest.cc
+++ b/tot/base/fuchsia/test_component_context_for_process_unittest.cc
@@ -142,12 +142,11 @@
 
   // If the BuildInfo service is actually connected then GetBuildInfo() will
   // return a result, otherwise the bindings will report an error.
-  provider->GetBuildInfo().Then(
-      [quit_loop = wait_loop.QuitClosure()](auto build_info) {
-        EXPECT_FALSE(build_info.is_error())
-            << build_info.error_value().status();
-        quit_loop.Run();
-      });
+  provider->GetBuildInfo().Then([quit_loop =
+                                     wait_loop.QuitClosure()](auto build_info) {
+    EXPECT_FALSE(build_info.is_error()) << build_info.error_value().status();
+    quit_loop.Run();
+  });
   wait_loop.Run();
 }
 
diff --git a/tot/base/fuchsia/test_interface_impl.cc b/tot/base/fuchsia/test_interface_impl.cc
index 3808788..51755f1 100644
--- a/tot/base/fuchsia/test_interface_impl.cc
+++ b/tot/base/fuchsia/test_interface_impl.cc
@@ -29,8 +29,9 @@
   ptr.set_error_handler(
       [quit = run_loop.QuitClosure(),
        weak_result = weak_result.GetWeakPtr()](zx_status_t status) {
-        if (weak_result)
+        if (weak_result) {
           *weak_result = status;
+        }
         std::move(quit).Run();
       });
 
@@ -38,8 +39,9 @@
            [quit = run_loop.QuitClosure(),
             weak_result = weak_result.GetWeakPtr()](int32_t value) {
              EXPECT_EQ(value, 4);
-             if (weak_result)
+             if (weak_result) {
                *weak_result = ZX_OK;
+             }
              std::move(quit).Run();
            });
 
diff --git a/tot/base/fuchsia/test_log_listener_safe.cc b/tot/base/fuchsia/test_log_listener_safe.cc
index 5f0d50a..59bfd5b 100644
--- a/tot/base/fuchsia/test_log_listener_safe.cc
+++ b/tot/base/fuchsia/test_log_listener_safe.cc
@@ -33,8 +33,9 @@
 void TestLogListenerSafe::Log(
     TestLogListenerSafe::LogRequest& request,
     TestLogListenerSafe::LogCompleter::Sync& completer) {
-  if (on_log_message_)
+  if (on_log_message_) {
     on_log_message_.Run(request.log());
+  }
   completer.Reply();
 }
 
@@ -66,7 +67,7 @@
         ZX_LOG(ERROR, info.status()) << "LogListenerSafe disconnected";
       });
 
-  ignore_before_ = zx::clock::get_monotonic();
+  ignore_before_ = zx::clock::get_boot();
   listener_.set_on_log_message(base::BindRepeating(
       &SimpleTestLogListener::PushLoggedMessage, base::Unretained(this)));
   auto listen_safe_result =
@@ -97,7 +98,7 @@
        expected_string = std::string(expected_string),
        quit_loop =
            loop.QuitClosure()](const fuchsia_logger::LogMessage& message) {
-        if (zx::time(message.time()) < ignore_before) {
+        if (message.time() < ignore_before) {
           return;
         }
         if (message.msg().find(expected_string) == std::string::npos) {
@@ -117,7 +118,7 @@
 void SimpleTestLogListener::PushLoggedMessage(
     const fuchsia_logger::LogMessage& message) {
   DVLOG(1) << "TestLogListener received: " << message.msg();
-  if (zx::time(message.time()) < ignore_before_) {
+  if (message.time() < ignore_before_) {
     return;
   }
   if (on_log_message_) {
diff --git a/tot/base/fuchsia/test_log_listener_safe.h b/tot/base/fuchsia/test_log_listener_safe.h
index 754bb92..fbd6236 100644
--- a/tot/base/fuchsia/test_log_listener_safe.h
+++ b/tot/base/fuchsia/test_log_listener_safe.h
@@ -79,7 +79,7 @@
   void PushLoggedMessage(const fuchsia_logger::LogMessage& message);
 
   // Used to ignore messages with timestamps prior to this listener's creation.
-  zx::time ignore_before_;
+  zx::time_boot ignore_before_;
 
   TestLogListenerSafe listener_;
   std::optional<fidl::ServerBinding<fuchsia_logger::LogListenerSafe>> binding_;
diff --git a/tot/base/fuchsia/time_zone_data_unittest.cc b/tot/base/fuchsia/time_zone_data_unittest.cc
index f833cf0..11afabb 100644
--- a/tot/base/fuchsia/time_zone_data_unittest.cc
+++ b/tot/base/fuchsia/time_zone_data_unittest.cc
@@ -2,9 +2,8 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "base/i18n/icu_util.h"
-
 #include "base/files/file_util.h"
+#include "base/i18n/icu_util.h"
 #include "base/logging.h"
 #include "base/strings/string_util.h"
 #include "base/test/icu_test_util.h"
diff --git a/tot/base/functional/bind_internal.h b/tot/base/functional/bind_internal.h
index 551c4a9..c52b963 100644
--- a/tot/base/functional/bind_internal.h
+++ b/tot/base/functional/bind_internal.h
@@ -19,11 +19,8 @@
 #include "base/functional/callback_internal.h"
 #include "base/functional/unretained_traits.h"
 #include "base/memory/raw_ptr.h"
-#include "base/memory/raw_ptr_asan_bound_arg_tracker.h"
 #include "base/memory/raw_ref.h"
-#include "base/memory/raw_scoped_refptr_mismatch_checker.h"
 #include "base/memory/weak_ptr.h"
-#include "base/notreached.h"
 #include "base/types/always_false.h"
 #include "base/types/is_complete.h"
 #include "base/types/is_instantiation.h"
@@ -31,6 +28,10 @@
 #include "build/build_config.h"
 #include "third_party/abseil-cpp/absl/functional/function_ref.h"
 
+#if PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
+#include "base/memory/raw_ptr_asan_bound_arg_tracker.h"
+#endif
+
 // See docs/callback.md for user documentation.
 //
 // Concepts:
@@ -329,7 +330,7 @@
 template <typename T>
 struct MethodReceiverStorage {
   using Type = std::
-      conditional_t<IsRawPointer<T>, scoped_refptr<RemoveRawPointerT<T>>, T>;
+      conditional_t<IsPointerOrRawPtr<T>, scoped_refptr<RemovePointerT<T>>, T>;
 };
 
 template <typename T, typename UnretainedTrait, RawPtrTraits PtrTraits>
@@ -595,12 +596,6 @@
   requires !IsObjCArcBlockPointer<std::decay_t<Functor>>;
 };
 
-// `HasRefCountedTypeAsRawPtr` is true when any of the `Args` is a raw pointer
-// to a `RefCounted` type.
-template <typename... Ts>
-concept HasRefCountedTypeAsRawPtr =
-    std::disjunction_v<NeedsScopedRefptrButGetsRawPtr<Ts>...>;
-
 // `ForceVoidReturn<>` converts a signature to have a `void` return type.
 template <typename Sig>
 struct ForceVoidReturn;
@@ -1077,8 +1072,8 @@
 template <typename Receiver, typename... Unused>
 void VerifyMethodReceiver(Receiver&& receiver, Unused&&...) {
   // Asserts that a callback is not the first owner of a ref-counted receiver.
-  if constexpr (IsRawPointer<std::decay_t<Receiver>> &&
-                IsRefCountedType<RemoveRawPointerT<std::decay_t<Receiver>>>) {
+  if constexpr (IsPointerOrRawPtr<std::decay_t<Receiver>> &&
+                IsRefCountedType<RemovePointerT<std::decay_t<Receiver>>>) {
     DCHECK(receiver);
 
     // It's error prone to make the implicit first reference to ref-counted
@@ -1212,6 +1207,31 @@
   }
 };
 
+template <typename... BoundArgs>
+struct ValidateBindStateTypeCommonChecks {
+ private:
+  // Refcounted parameters must be passed as `scoped_refptr` instead of raw
+  // pointers, to ensure they are not deleted before use.
+  // TODO(danakj): Ban native references and `std::reference_wrapper` too.
+  template <typename T,
+            bool v =
+                (IsRawRef<T> && IsRefCountedType<base::RemoveRawRefT<T>>) ||
+                (IsPointerOrRawPtr<T> &&
+                 IsRefCountedType<base::RemovePointerT<T>>)>
+  struct RefCountedTypeNotPassedByRawPointer {
+    static constexpr bool value = [] {
+      static_assert(
+          !v, "A parameter is a refcounted type and needs scoped_refptr.");
+      return !v;
+    }();
+  };
+
+ public:
+  using CommonCheckResult = std::conjunction<
+      RefCountedTypeNotPassedByRawPointer<std::decay_t<BoundArgs>>...,
+      ValidateStorageTraits<BoundArgs>...>;
+};
+
 // Used to determine and validate the appropriate `BindState`. The
 // specializations below cover all cases. The members are similar in intent to
 // those in `StorageTraits`; see comments there.
@@ -1231,25 +1251,13 @@
                              is_callback,
                              Functor,
                              BoundArgs...> {
- private:
-  template <bool v = !HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>>
-  struct NoRawPtrsToRefCountedTypes {
-    static constexpr bool value = [] {
-      static_assert(
-          v, "A parameter is a refcounted type and needs scoped_refptr.");
-      return v;
-    }();
-  };
-
- public:
   using Type = BindState<false,
                          is_nullable,
                          is_callback,
                          std::decay_t<Functor>,
                          typename ValidateStorageTraits<BoundArgs>::Type...>;
   static constexpr bool value =
-      std::conjunction_v<NoRawPtrsToRefCountedTypes<>,
-                         ValidateStorageTraits<BoundArgs>...>;
+      ValidateBindStateTypeCommonChecks<BoundArgs...>::CommonCheckResult::value;
 };
 
 template <bool is_nullable, bool is_callback, typename Functor>
@@ -1282,7 +1290,7 @@
     }();
   };
 
-  template <bool v = !IsRawRefV<DecayedReceiver>>
+  template <bool v = !IsRawRef<DecayedReceiver>>
   struct ReceiverIsNotRawRef {
     static constexpr bool value = [] {
       static_assert(v, "Receivers may not be raw_ref<T>. If using a raw_ref<T> "
@@ -1292,8 +1300,8 @@
     }();
   };
 
-  template <bool v = !IsRawPointer<DecayedReceiver> ||
-                     IsRefCountedType<RemoveRawPointerT<DecayedReceiver>>>
+  template <bool v = !IsPointerOrRawPtr<DecayedReceiver> ||
+                     IsRefCountedType<RemovePointerT<DecayedReceiver>>>
   struct ReceiverIsNotRawPtr {
     static constexpr bool value = [] {
       static_assert(v,
@@ -1304,15 +1312,6 @@
     }();
   };
 
-  template <bool v = !HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>>
-  struct NoRawPtrsToRefCountedTypes {
-    static constexpr bool value = [] {
-      static_assert(
-          v, "A parameter is a refcounted type and needs scoped_refptr.");
-      return v;
-    }();
-  };
-
  public:
   using Type = BindState<true,
                          is_nullable,
@@ -1324,8 +1323,8 @@
       std::conjunction_v<FirstBoundArgIsNotArray<>,
                          ReceiverIsNotRawRef<>,
                          ReceiverIsNotRawPtr<>,
-                         NoRawPtrsToRefCountedTypes<>,
-                         ValidateStorageTraits<BoundArgs>...>;
+                         typename ValidateBindStateTypeCommonChecks<
+                             BoundArgs...>::CommonCheckResult>;
 };
 
 // Transforms `T` into an unwrapped type, which is passed to the target
@@ -1439,9 +1438,9 @@
   struct ForwardedAs {
     template <typename FunctorParamType>
     struct ToParamWithType {
-      static constexpr bool kRawPtr = IsRawPtrV<FunctorParamType>;
+      static constexpr bool kRawPtr = IsRawPtr<FunctorParamType>;
       static constexpr bool kRawPtrMayBeDangling =
-          IsRawPtrMayDangleV<FunctorParamType>;
+          IsRawPtrMayDangle<FunctorParamType>;
       static constexpr bool kCanBeForwardedToBoundFunctor =
           std::is_convertible_v<ForwardingType, FunctorParamType>;
 
diff --git a/tot/base/functional/bind_unittest.cc b/tot/base/functional/bind_unittest.cc
index 2e32e52..7583652 100644
--- a/tot/base/functional/bind_unittest.cc
+++ b/tot/base/functional/bind_unittest.cc
@@ -436,7 +436,7 @@
   // After running via the rvalue-reference, the value of the OnceCallback
   // is undefined. The implementation simply clears the instance after the
   // invocation.
-  EXPECT_TRUE(c0.is_null());
+  EXPECT_TRUE(c0.is_null());  // NOLINT(bugprone-use-after-move)
 
   c0 = BindOnce(&Sum, 2, 3, 5, 7, 11);
 
@@ -1639,7 +1639,7 @@
   cb = cb3;
   std::move(cb).Run();
 
-  cb = std::move(cb2);
+  cb = std::move(cb2);  // NOLINT(bugprone-use-after-move)
 
   OnceCallback<void(int)> cb4 =
       BindOnce(&VoidPolymorphic<std::unique_ptr<int>, int>::Run,
diff --git a/tot/base/functional/callback_helpers.cc b/tot/base/functional/callback_helpers.cc
index 582043b..4cc7ada 100644
--- a/tot/base/functional/callback_helpers.cc
+++ b/tot/base/functional/callback_helpers.cc
@@ -28,8 +28,9 @@
 }
 
 void ScopedClosureRunner::RunAndReset() {
-  if (closure_)
+  if (closure_) {
     std::move(closure_).Run();
+  }
 }
 
 void ScopedClosureRunner::ReplaceClosure(OnceClosure closure) {
diff --git a/tot/base/functional/callback_helpers.h b/tot/base/functional/callback_helpers.h
index 9b484a0..f1aa11f 100644
--- a/tot/base/functional/callback_helpers.h
+++ b/tot/base/functional/callback_helpers.h
@@ -16,7 +16,6 @@
 #include <type_traits>
 #include <utility>
 
-#include "base/atomicops.h"
 #include "base/base_export.h"
 #include "base/check.h"
 #include "base/functional/bind.h"
diff --git a/tot/base/functional/callback_internal.cc b/tot/base/functional/callback_internal.cc
index 30be53c..27f6900 100644
--- a/tot/base/functional/callback_internal.cc
+++ b/tot/base/functional/callback_internal.cc
@@ -8,8 +8,7 @@
 #include "base/notreached.h"
 #include "base/types/cxx23_to_underlying.h"
 
-namespace base {
-namespace internal {
+namespace base::internal {
 
 namespace {
 
@@ -64,5 +63,4 @@
   return bind_state_->MaybeValid();
 }
 
-}  // namespace internal
-}  // namespace base
+}  // namespace base::internal
diff --git a/tot/base/functional/callback_unittest.cc b/tot/base/functional/callback_unittest.cc
index 5c1adfc..f79aa6e 100644
--- a/tot/base/functional/callback_unittest.cc
+++ b/tot/base/functional/callback_unittest.cc
@@ -144,7 +144,7 @@
   const RepeatingClosure cb2 = BindRepeating([] {});
   ASSERT_TRUE(cb2);
   std::move(cb2).Run();
-  EXPECT_TRUE(cb2);
+  EXPECT_TRUE(cb2);  // NOLINT(bugprone-use-after-move)
 
   OnceCallback<void(void*)> cb3 = BindOnce([](void* param) {
     EXPECT_TRUE(static_cast<OnceCallback<void(void*)>*>(param)->is_null());
@@ -169,7 +169,7 @@
     EXPECT_TRUE(!!orig);
     OnceClosure joined = std::move(orig).Then(base::BindOnce([] {}));
     EXPECT_TRUE(!!joined);
-    EXPECT_FALSE(!!orig);
+    EXPECT_FALSE(!!orig);  // NOLINT(bugprone-use-after-move)
   }
   {
     // RepeatingCallback::Then() destroys the original callback if it's an
@@ -178,7 +178,7 @@
     EXPECT_TRUE(!!orig);
     RepeatingClosure joined = std::move(orig).Then(base::BindRepeating([] {}));
     EXPECT_TRUE(!!joined);
-    EXPECT_FALSE(!!orig);
+    EXPECT_FALSE(!!orig);  // NOLINT(bugprone-use-after-move)
   }
   {
     // RepeatingCallback::Then() doesn't destroy the original callback if it's
@@ -705,8 +705,9 @@
             // Check that MaybeValid() _eventually_ returns false.
             const TimeDelta timeout = TestTimeouts::tiny_timeout();
             const TimeTicks begin = TimeTicks::Now();
-            while (cb.MaybeValid() && (TimeTicks::Now() - begin) < timeout)
+            while (cb.MaybeValid() && (TimeTicks::Now() - begin) < timeout) {
               PlatformThread::YieldCurrentThread();
+            }
             EXPECT_FALSE(cb.MaybeValid());
           },
           cb));
diff --git a/tot/base/functional/function_ref.h b/tot/base/functional/function_ref.h
index ed778e2..9ee9363 100644
--- a/tot/base/functional/function_ref.h
+++ b/tot/base/functional/function_ref.h
@@ -6,7 +6,6 @@
 #define BASE_FUNCTIONAL_FUNCTION_REF_H_
 
 #include <concepts>
-#include <string_view>
 #include <type_traits>
 #include <utility>
 
@@ -91,12 +90,10 @@
              // we could teach our trampoline to deal with this, but this may be
              // the sign of an object lifetime bug, and again it's not clear
              // that this isn't just a mistake on the part of the user.
-             (!internal::is_instantiation_v<FunctionRef,
-                                            std::decay_t<Functor>>) &&
+             (!is_instantiation<FunctionRef, std::decay_t<Functor>>) &&
              // For the same reason as the second case above, prevent
              // construction from `absl::FunctionRef`.
-             (!internal::is_instantiation_v<absl::FunctionRef,
-                                            std::decay_t<Functor>>)
+             (!is_instantiation<absl::FunctionRef, std::decay_t<Functor>>)
   // NOLINTNEXTLINE(google-explicit-constructor)
   FunctionRef(const Functor& functor LIFETIME_BOUND)
       : wrapped_func_ref_(functor) {}
diff --git a/tot/base/functional/overloaded.h b/tot/base/functional/overloaded.h
index 0e1b336..20168d4 100644
--- a/tot/base/functional/overloaded.h
+++ b/tot/base/functional/overloaded.h
@@ -7,7 +7,7 @@
 
 namespace base {
 
-// absl::visit() needs to be called with a functor object, such as
+// std::visit() needs to be called with a functor object, such as
 //
 //  struct Visitor {
 //    std::string operator()(const PackageA& source) {
@@ -19,12 +19,12 @@
 //    }
 //  };
 //
-//  absl::variant<PackageA, PackageB> var = PackageA();
-//  return absl::visit(Visitor(), var);
+//  std::variant<PackageA, PackageB> var = PackageA();
+//  return std::visit(Visitor(), var);
 //
 // `Overloaded` enables the above code to be written as:
 //
-//  absl::visit(
+//  std::visit(
 //     Overloaded{
 //         [](const PackageA& pack) { return "PackageA"; },
 //         [](const PackageB& pack) { return "PackageB"; },
diff --git a/tot/base/functional/overloaded_nocompile.nc b/tot/base/functional/overloaded_nocompile.nc
index 94bdc7d..5d82863 100644
--- a/tot/base/functional/overloaded_nocompile.nc
+++ b/tot/base/functional/overloaded_nocompile.nc
@@ -7,17 +7,20 @@
 
 #include "base/functional/overloaded.h"
 
-#include "third_party/abseil-cpp/absl/types/variant.h"
+#include <variant>
 
 namespace base {
 
 void LambdaMissingForVariantElement() {
-  // `absl::visit()` may only be called on an `Overloaded` that can actually
+  // `std::visit()` may only be called on an `Overloaded` that can actually
   // handle all potential input variant types.
   struct A {};
   struct B {};
-  absl::variant<A, B> var = A{};
-  absl::visit(Overloaded{[](A& pack) { return "A"; }}, var);  // expected-error-re@*:* {{no type named 'type' in 'absl::type_traits_internal::result_of<base::Overloaded<(lambda at {{.*}})> (B &)>'}}
+  std::variant<A, B> var = A{};
+  std::visit(Overloaded{[](A& pack) { return "A"; }}, var);  // expected-error-re@*:* {{static assertion failed due to requirement {{.*}} `std::visit` requires the visitor to be exhaustive}}
+  // expected-error@*:* {{attempt to use a deleted function}}
+  // expected-error@*:* {{attempt to use a deleted function}}
+  // expected-error@*:* {{cannot deduce return type 'auto' from returned value of type '<overloaded function type>'}}
 }
 
 }  // namespace base
diff --git a/tot/base/functional/overloaded_unittest.cc b/tot/base/functional/overloaded_unittest.cc
index 16482b5..e01afe7 100644
--- a/tot/base/functional/overloaded_unittest.cc
+++ b/tot/base/functional/overloaded_unittest.cc
@@ -5,9 +5,9 @@
 #include "base/functional/overloaded.h"
 
 #include <string>
+#include <variant>
 
 #include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/abseil-cpp/absl/types/variant.h"
 
 namespace base {
 
@@ -15,12 +15,12 @@
   struct PackageA {};
   struct PackageB {};
 
-  absl::variant<PackageA, PackageB> var = PackageA();
+  std::variant<PackageA, PackageB> var = PackageA();
 
   const std::string output =
-      absl::visit(Overloaded{[](const PackageA& pack) { return "PackageA"; },
-                             [](const PackageB& pack) { return "PackageB"; }},
-                  var);
+      std::visit(Overloaded{[](const PackageA& pack) { return "PackageA"; },
+                            [](const PackageB& pack) { return "PackageB"; }},
+                 var);
   EXPECT_EQ(output, "PackageA");
 }
 
diff --git a/tot/base/gmock_unittest.cc b/tot/base/gmock_unittest.cc
index 649054d..3602d53 100644
--- a/tot/base/gmock_unittest.cc
+++ b/tot/base/gmock_unittest.cc
@@ -7,15 +7,16 @@
 // the basic mock features.
 
 #include "testing/gmock/include/gmock/gmock.h"
+
 #include "testing/gtest/include/gtest/gtest.h"
 
 // Gmock matchers and actions that we use below.
+using testing::_;
 using testing::AnyOf;
 using testing::Eq;
 using testing::Return;
 using testing::SetArgPointee;
 using testing::WithArg;
-using testing::_;
 
 namespace {
 
@@ -26,19 +27,13 @@
   SampleClass() = default;
   virtual ~SampleClass() = default;
 
-  virtual int ReturnSomething() {
-    return -1;
-  }
+  virtual int ReturnSomething() { return -1; }
 
-  virtual void ReturnNothingConstly() const {
-  }
+  virtual void ReturnNothingConstly() const {}
 
-  virtual void OutputParam(int* a) {
-  }
+  virtual void OutputParam(int* a) {}
 
-  virtual int ReturnSecond(int a, int b) {
-    return b;
-  }
+  virtual int ReturnSecond(int a, int b) { return b; }
 };
 
 // Declare a mock for the class.
diff --git a/tot/base/gtest_prod_util.h b/tot/base/gtest_prod_util.h
index 921f77d..21adcfe 100644
--- a/tot/base/gtest_prod_util.h
+++ b/tot/base/gtest_prod_util.h
@@ -20,8 +20,8 @@
 //   FRIEND_TEST_ALL_PREFIXES(MyClassTest, TestName);
 // };
 #define FRIEND_TEST_ALL_PREFIXES(test_case_name, test_name) \
-  FRIEND_TEST(test_case_name, test_name); \
-  FRIEND_TEST(test_case_name, DISABLED_##test_name); \
+  FRIEND_TEST(test_case_name, test_name);                   \
+  FRIEND_TEST(test_case_name, DISABLED_##test_name);        \
   FRIEND_TEST(test_case_name, FLAKY_##test_name)
 
 // C++ compilers will refuse to compile the following code:
@@ -60,7 +60,7 @@
 // }
 
 #define FORWARD_DECLARE_TEST(test_case_name, test_name) \
-  class test_case_name##_##test_name##_Test; \
+  class test_case_name##_##test_name##_Test;            \
   class test_case_name##_##DISABLED_##test_name##_Test; \
   class test_case_name##_##FLAKY_##test_name##_Test
 
diff --git a/tot/base/hash/hash.cc b/tot/base/hash/hash.cc
index 9a23491..98f8ded 100644
--- a/tot/base/hash/hash.cc
+++ b/tot/base/hash/hash.cc
@@ -51,8 +51,9 @@
   uint64_t value1_64 = value1;
   uint64_t hash64 = (value1_64 << 32) | value2;
 
-  if (sizeof(size_t) >= sizeof(uint64_t))
+  if (sizeof(size_t) >= sizeof(uint64_t)) {
     return static_cast<size_t>(hash64);
+  }
 
   uint64_t odd_random = 481046412LL << 32 | 1025306955LL;
   uint32_t shift_random = 10121U << 16;
@@ -86,8 +87,9 @@
 
   uint64_t hash64 = product1 + product2 + product3 + product4;
 
-  if (sizeof(size_t) >= sizeof(uint64_t))
+  if (sizeof(size_t) >= sizeof(uint64_t)) {
     return static_cast<size_t>(hash64);
+  }
 
   uint64_t odd_random = 1578233944LL << 32 | 194370989LL;
   uint32_t shift_random = 20591U << 16;
diff --git a/tot/base/hash/hash.h b/tot/base/hash/hash.h
index 3464d61..8732425 100644
--- a/tot/base/hash/hash.h
+++ b/tot/base/hash/hash.h
@@ -55,8 +55,9 @@
 inline size_t HashInts(T1 value1, T2 value2) {
   // This condition is expected to be compile-time evaluated and optimised away
   // in release builds.
-  if (sizeof(T1) > sizeof(uint32_t) || (sizeof(T2) > sizeof(uint32_t)))
+  if (sizeof(T1) > sizeof(uint32_t) || (sizeof(T2) > sizeof(uint32_t))) {
     return HashInts64(value1, value2);
+  }
 
   return HashInts32(static_cast<uint32_t>(value1),
                     static_cast<uint32_t>(value2));
diff --git a/tot/base/hash/hash_perftest.cc b/tot/base/hash/hash_perftest.cc
index 6e14766..1d7d829 100644
--- a/tot/base/hash/hash_perftest.cc
+++ b/tot/base/hash/hash_perftest.cc
@@ -7,13 +7,13 @@
 #include <stddef.h>
 #include <stdint.h>
 
+#include <algorithm>
 #include <string>
 #include <vector>
 
 #include "base/containers/span.h"
 #include "base/hash/sha1.h"
 #include "base/rand_util.h"
-#include "base/ranges/algorithm.h"
 #include "base/strings/string_number_conversions.h"
 #include "base/strings/string_util.h"
 #include "base/time/time.h"
@@ -59,7 +59,7 @@
       utime[i] = TimeTicks::Now() - start;
       total_test_time += utime[i];
     }
-    ranges::sort(utime);
+    std::ranges::sort(utime);
   }
 
   reporter.AddResult(kMetricRuntime, total_test_time.InMicrosecondsF());
@@ -78,8 +78,9 @@
 
   // Convert to a comma-separated string so we can report every data point.
   std::vector<std::string> rate_strings(utime.size());
-  ranges::transform(utime, rate_strings.begin(),
-                    [rate](const auto& t) { return NumberToString(rate(t)); });
+  std::ranges::transform(utime, rate_strings.begin(), [rate](const auto& t) {
+    return NumberToString(rate(t));
+  });
   reporter.AddResultList(kMetricThroughput, JoinString(rate_strings, ","));
 }
 
diff --git a/tot/base/hash/hash_unittest.cc b/tot/base/hash/hash_unittest.cc
index 00f8ca3..189360e 100644
--- a/tot/base/hash/hash_unittest.cc
+++ b/tot/base/hash/hash_unittest.cc
@@ -41,8 +41,9 @@
   // Extremely long string.
   // Also tests strings with high bit set, and null byte.
   std::vector<char> long_string_buffer;
-  for (int i = 0; i < 4096; ++i)
+  for (int i = 0; i < 4096; ++i) {
     long_string_buffer.push_back((i % 256) - 128);
+  }
   str.assign(&long_string_buffer.front(), long_string_buffer.size());
   EXPECT_EQ(2797962408u, Hash(str));
 
diff --git a/tot/base/hash/legacy_hash.cc b/tot/base/hash/legacy_hash.cc
index 40953fe..563c056 100644
--- a/tot/base/hash/legacy_hash.cc
+++ b/tot/base/hash/legacy_hash.cc
@@ -9,8 +9,7 @@
 #include "base/containers/span.h"
 #include "base/third_party/cityhash_v103/src/city_v103.h"
 
-namespace base {
-namespace legacy {
+namespace base::legacy {
 
 uint64_t CityHash64(base::span<const uint8_t> data) {
   return internal::cityhash_v103::CityHash64(
@@ -22,5 +21,4 @@
       reinterpret_cast<const char*>(data.data()), data.size(), seed);
 }
 
-}  // namespace legacy
-}  // namespace base
+}  // namespace base::legacy
diff --git a/tot/base/hash/legacy_hash_unittest.cc b/tot/base/hash/legacy_hash_unittest.cc
index 353a6c4..fc836a2 100644
--- a/tot/base/hash/legacy_hash_unittest.cc
+++ b/tot/base/hash/legacy_hash_unittest.cc
@@ -11,8 +11,7 @@
 #include "base/containers/span.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
-namespace base {
-namespace legacy {
+namespace base::legacy {
 
 TEST(LegacyHashTest, CityHashV103) {
   constexpr struct {
@@ -35,5 +34,4 @@
   }
 }
 
-}  // namespace legacy
-}  // namespace base
+}  // namespace base::legacy
diff --git a/tot/base/hash/md5_constexpr.h b/tot/base/hash/md5_constexpr.h
index 6473f38..dd23959 100644
--- a/tot/base/hash/md5_constexpr.h
+++ b/tot/base/hash/md5_constexpr.h
@@ -5,10 +5,10 @@
 #ifndef BASE_HASH_MD5_CONSTEXPR_H_
 #define BASE_HASH_MD5_CONSTEXPR_H_
 
-#include "base/hash/md5_constexpr_internal.h" // IWYU pragma: export
-
 #include <string_view>
 
+#include "base/hash/md5_constexpr_internal.h"  // IWYU pragma: export
+
 namespace base {
 
 // Calculates the first 32/64 bits of the MD5 digest of the provided data,
diff --git a/tot/base/hash/md5_constexpr_internal.h b/tot/base/hash/md5_constexpr_internal.h
index 49e7174..cf9534e 100644
--- a/tot/base/hash/md5_constexpr_internal.h
+++ b/tot/base/hash/md5_constexpr_internal.h
@@ -222,8 +222,9 @@
     for (uint32_t offset = 0; offset < m; offset += 64) {
       RoundData data = GetRoundData(message, m, offset);
       IntermediateData intermediate1 = intermediate0;
-      for (uint32_t i = 0; i < 64; ++i)
+      for (uint32_t i = 0; i < 64; ++i) {
         intermediate1 = ApplyStep(i, data, intermediate1);
+      }
       intermediate0 = Add(intermediate0, intermediate1);
     }
     return intermediate0;
diff --git a/tot/base/hash/md5_nacl.cc b/tot/base/hash/md5_nacl.cc
index 280b7eb..120f209 100644
--- a/tot/base/hash/md5_nacl.cc
+++ b/tot/base/hash/md5_nacl.cc
@@ -186,8 +186,9 @@
   /* Update bitcount */
 
   uint32_t t = ctx->bits[0];
-  if ((ctx->bits[0] = t + (static_cast<uint32_t>(len) << 3)) < t)
+  if ((ctx->bits[0] = t + (static_cast<uint32_t>(len) << 3)) < t) {
     ctx->bits[1]++; /* Carry from low to high */
+  }
   ctx->bits[1] += static_cast<uint32_t>(len >> 29);
 
   t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
diff --git a/tot/base/hash/sha1_nacl.cc b/tot/base/hash/sha1_nacl.cc
index 8de9aa5..a6c3681 100644
--- a/tot/base/hash/sha1_nacl.cc
+++ b/tot/base/hash/sha1_nacl.cc
@@ -2,13 +2,14 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "base/hash/sha1.h"
+
 #include <stddef.h>
 #include <stdint.h>
 #include <string.h>
 
 #include <string_view>
 
-#include "base/hash/sha1.h"
 #include "base/numerics/byte_conversions.h"
 
 namespace base {
@@ -30,12 +31,15 @@
 // to reuse the instance of sha, call sha.Init();
 
 static inline uint32_t f(uint32_t t, uint32_t B, uint32_t C, uint32_t D) {
-  if (t < 20)
+  if (t < 20) {
     return (B & C) | ((~B) & D);
-  if (t < 40)
+  }
+  if (t < 40) {
     return B ^ C ^ D;
-  if (t < 60)
+  }
+  if (t < 60) {
     return (B & C) | (B & D) | (C & D);
+  }
   return B ^ C ^ D;
 }
 
@@ -44,12 +48,15 @@
 }
 
 static inline uint32_t K(uint32_t t) {
-  if (t < 20)
+  if (t < 20) {
     return 0x5a827999;
-  if (t < 40)
+  }
+  if (t < 40) {
     return 0x6ed9eba1;
-  if (t < 60)
+  }
+  if (t < 60) {
     return 0x8f1bbcdc;
+  }
   return 0xca62c1d6;
 }
 
diff --git