Merge "Add make target for cts-interactive." into main
diff --git a/backported_fixes/Android.bp b/backported_fixes/Android.bp
index a20f3fc..243e77e 100644
--- a/backported_fixes/Android.bp
+++ b/backported_fixes/Android.bp
@@ -19,19 +19,24 @@
 
 genrule {
     name: "applied_backported_fixes",
-    tools: ["applied_backported_fixes_main"],
+    tools: ["applied_backported_fixes_property_writer"],
     srcs: [":applied_backported_fix_binpbs"],
     out: ["applied_backported_fixes.prop"],
-    cmd: "$(location applied_backported_fixes_main)" +
+    cmd: "$(location applied_backported_fixes_property_writer)" +
         " -p $(location applied_backported_fixes.prop)" +
         " $(in)",
 }
 
-java_library {
-    name: "backported_fixes_proto",
+filegroup {
+    name: "backported_fixes_proto_file",
     srcs: [
         "backported_fixes.proto",
     ],
+}
+
+java_library {
+    name: "backported_fixes_proto",
+    srcs: ["backported_fixes.proto"],
     host_supported: true,
 }
 
@@ -63,7 +68,7 @@
 }
 
 java_library {
-    name: "applied_backported_fixes_lib",
+    name: "backported_fixes_main_lib",
     srcs: ["src/java/com/android/build/backportedfixes/*.java"],
     static_libs: [
         "backported_fixes_common",
@@ -75,18 +80,35 @@
 }
 
 java_binary_host {
-    name: "applied_backported_fixes_main",
-    main_class: "com.android.build.backportedfixes.Main",
+    name: "applied_backported_fixes_property_writer",
+    main_class: "com.android.build.backportedfixes.WriteBackportedFixesPropFile",
     static_libs: [
-        "applied_backported_fixes_lib",
+        "backported_fixes_main_lib",
     ],
 }
 
+java_binary_host {
+    name: "backported_fixes_combiner",
+    main_class: "com.android.build.backportedfixes.CombineBackportedFixes",
+    static_libs: [
+        "backported_fixes_main_lib",
+    ],
+}
+
+// Combines BackportedFix binary proto files into a single BackportedFixes binary proto file.
+genrule_defaults {
+    name: "default_backported_fixes_combiner",
+    tools: ["backported_fixes_combiner"],
+    cmd: "$(location backported_fixes_combiner)" +
+        " -o $(out)" +
+        " $(in)",
+}
+
 java_test_host {
-    name: "applied_backported_fixes_test",
+    name: "backported_fixes_main_lib_test",
     srcs: ["tests/java/com/android/build/backportedfixes/*.java"],
     static_libs: [
-        "applied_backported_fixes_lib",
+        "backported_fixes_main_lib",
         "backported_fixes_proto",
         "junit",
         "truth",
@@ -97,19 +119,25 @@
     test_suites: ["general-tests"],
 }
 
+// Converts BackprotedFix text protos to binary protos
+genrule_defaults {
+    name: "default_backported_fix_binpbs",
+    tools: ["aprotoc"],
+    tool_files: [
+        ":backported_fixes_proto_file",
+    ],
+    cmd: "$(location aprotoc)  " +
+        " --encode=com.android.build.backportedfixes.BackportedFix" +
+        "  $(location :backported_fixes_proto_file)" +
+        " < $(in)" +
+        " > $(out); echo $(out)",
+}
+
 gensrcs {
     name: "applied_backported_fix_binpbs",
-    tools: ["aprotoc"],
+    defaults: ["default_backported_fix_binpbs"],
+    output_extension: "binpb",
     srcs: [
         "applied_fixes/*.txtpb",
     ],
-    tool_files: [
-        "backported_fixes.proto",
-    ],
-    output_extension: "binpb",
-    cmd: "$(location aprotoc)  " +
-        " --encode=com.android.build.backportedfixes.BackportedFix" +
-        "  $(location backported_fixes.proto)" +
-        " < $(in)" +
-        " > $(out); echo $(out)",
 }
diff --git a/backported_fixes/src/java/com/android/build/backportedfixes/CombineBackportedFixes.java b/backported_fixes/src/java/com/android/build/backportedfixes/CombineBackportedFixes.java
new file mode 100644
index 0000000..0592cc1
--- /dev/null
+++ b/backported_fixes/src/java/com/android/build/backportedfixes/CombineBackportedFixes.java
@@ -0,0 +1,65 @@
+
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.build.backportedfixes;
+
+import com.android.build.backportedfixes.common.Parser;
+
+import com.beust.jcommander.JCommander;
+import com.beust.jcommander.Parameter;
+import com.beust.jcommander.converters.FileConverter;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.List;
+
+
+/** Creates a BackportedFixes binary proto file from a list of BackportedFix proto binary files. */
+public final class CombineBackportedFixes {
+
+    @Parameter(description = "BackportedFix proto binary files",
+            converter = FileConverter.class,
+            required = true)
+    List<File> fixFiles;
+    @Parameter(description = "Write the BackportedFixes proto binary to this file",
+            names = {"--out","-o"},
+            converter = FileConverter.class,
+            required = true)
+    File outFile;
+
+    public static void main(String... argv) throws Exception {
+        CombineBackportedFixes main = new CombineBackportedFixes();
+        JCommander.newBuilder().addObject(main).build().parse(argv);
+        main.run();
+    }
+
+    CombineBackportedFixes() {
+    }
+
+    private void run() throws Exception {
+        try (var out = new FileOutputStream(outFile)) {
+            var fixes = Parser.parseBackportedFixFiles(fixFiles);
+            writeBackportedFixes(fixes, out);
+        }
+    }
+
+    static void writeBackportedFixes(BackportedFixes fixes, OutputStream out)
+            throws IOException {
+        fixes.writeTo(out);
+    }
+}
diff --git a/backported_fixes/src/java/com/android/build/backportedfixes/Main.java b/backported_fixes/src/java/com/android/build/backportedfixes/WriteBackportedFixesPropFile.java
similarity index 74%
rename from backported_fixes/src/java/com/android/build/backportedfixes/Main.java
rename to backported_fixes/src/java/com/android/build/backportedfixes/WriteBackportedFixesPropFile.java
index 79148cc..0ffb4ac 100644
--- a/backported_fixes/src/java/com/android/build/backportedfixes/Main.java
+++ b/backported_fixes/src/java/com/android/build/backportedfixes/WriteBackportedFixesPropFile.java
@@ -18,7 +18,6 @@
 
 import static java.nio.charset.StandardCharsets.UTF_8;
 
-import com.android.build.backportedfixes.common.ClosableCollection;
 import com.android.build.backportedfixes.common.Parser;
 
 import com.beust.jcommander.JCommander;
@@ -33,27 +32,38 @@
 import java.util.List;
 import java.util.stream.Collectors;
 
-public final class Main {
-    @Parameter(description = "BackportedFix proto binary files", converter = FileConverter.class,
+
+/**
+ * Creates backported fix properties file.
+ *
+ * <p>Writes BitSet of backported fix aliases from a list of BackportedFix proto binary files and
+ * writes the property {@value PROPERTY_NAME} to a file.
+ */
+public final class WriteBackportedFixesPropFile {
+
+    private static final String PROPERTY_NAME = "ro.build.backported_fixes.alias_bitset.long_list";
+    @Parameter(description = "BackportedFix proto binary files",
+            converter = FileConverter.class,
             required = true)
     List<File> fixFiles;
     @Parameter(description = "The file to write the property value to.",
-            names = {"--property_file", "-p"}, converter = FileConverter.class, required = true)
+            names = {"--property_file", "-p"},
+            converter = FileConverter.class,
+            required = true)
     File propertyFile;
 
     public static void main(String... argv) throws Exception {
-        Main main = new Main();
+        WriteBackportedFixesPropFile main = new WriteBackportedFixesPropFile();
         JCommander.newBuilder().addObject(main).build().parse(argv);
         main.run();
     }
 
-    Main() {
+    WriteBackportedFixesPropFile() {
     }
 
     private void run() throws Exception {
-        try (var fixStreams = ClosableCollection.wrap(Parser.getFileInputStreams(fixFiles));
-             var out = Files.newWriter(propertyFile, UTF_8)) {
-            var fixes = Parser.parseBackportedFixes(fixStreams.getCollection());
+        try (var out = Files.newWriter(propertyFile, UTF_8)) {
+            var fixes = Parser.parseBackportedFixFiles(fixFiles);
             writeFixesAsAliasBitSet(fixes, out);
         }
     }
@@ -70,7 +80,7 @@
                 fixes.getFixesList().stream().mapToInt(BackportedFix::getAlias).toArray());
         String bsString = Arrays.stream(bsArray).mapToObj(Long::toString).collect(
                 Collectors.joining(","));
-        printWriter.printf("ro.build.backported_fixes.alias_bitset.long_list=%s", bsString);
+        printWriter.printf("%s=%s", PROPERTY_NAME, bsString);
         printWriter.println();
         if (printWriter.checkError()) {
             throw new RuntimeException("There was an error writing to " + out.toString());
diff --git a/backported_fixes/src/java/com/android/build/backportedfixes/common/ClosableCollection.java b/backported_fixes/src/java/com/android/build/backportedfixes/common/ClosableCollection.java
deleted file mode 100644
index 75b6730..0000000
--- a/backported_fixes/src/java/com/android/build/backportedfixes/common/ClosableCollection.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2024 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.build.backportedfixes.common;
-
-import com.google.common.collect.ImmutableList;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-/** An AutoCloseable holder for a collection of AutoCloseables. */
-public final class ClosableCollection<T extends AutoCloseable, C extends Collection<T>> implements
-        AutoCloseable {
-    C source;
-
-    /** Makes the collection AutoCloseable. */
-    public static <T extends AutoCloseable, C extends Collection<T>> ClosableCollection<T, C> wrap(
-            C source) {
-        return new ClosableCollection<>(source);
-    }
-
-    private ClosableCollection(C source) {
-        this.source = source;
-    }
-
-    /** Get the source collection. */
-    public C getCollection() {
-        return source;
-    }
-
-    /**
-     * Closes each item in the collection.
-     *
-     * @throws Exception if any close throws an an exception, a new exception is thrown with
-     *                   all the exceptions thrown closing the streams added as a suppressed
-     *                   exceptions.
-     */
-    @Override
-    public void close() throws Exception {
-        var failures = new ArrayList<Exception>();
-        for (T t : source) {
-            try {
-                t.close();
-            } catch (Exception e) {
-                failures.add(e);
-            }
-        }
-        if (!failures.isEmpty()) {
-            Exception e = new Exception(
-                    "%d of %d failed while closing".formatted(failures.size(), source.size()));
-            failures.forEach(e::addSuppressed);
-            throw e;
-        }
-    }
-}
diff --git a/backported_fixes/src/java/com/android/build/backportedfixes/common/Parser.java b/backported_fixes/src/java/com/android/build/backportedfixes/common/Parser.java
index 6b08b8f..6180fdc 100644
--- a/backported_fixes/src/java/com/android/build/backportedfixes/common/Parser.java
+++ b/backported_fixes/src/java/com/android/build/backportedfixes/common/Parser.java
@@ -15,9 +15,12 @@
  */
 package com.android.build.backportedfixes.common;
 
+import static com.google.common.base.Preconditions.checkNotNull;
+
 import com.android.build.backportedfixes.BackportedFix;
 import com.android.build.backportedfixes.BackportedFixes;
 
+import com.google.common.base.Throwables;
 import com.google.common.collect.ImmutableList;
 
 import java.io.File;
@@ -26,7 +29,10 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.BitSet;
+import java.util.Comparator;
 import java.util.List;
+import java.util.stream.Collector;
+import java.util.stream.Collectors;
 
 
 /** Static utilities for working with {@link BackportedFixes}. */
@@ -54,16 +60,79 @@
     /**
      * Creates a {@link BackportedFixes} from a list of {@link BackportedFix} binary proto streams.
      */
-    public static BackportedFixes parseBackportedFixes(List<? extends InputStream> fixStreams)
-            throws
-            IOException {
-        var fixes = BackportedFixes.newBuilder();
-        for (var s : fixStreams) {
-            BackportedFix fix = BackportedFix.parseFrom(s);
-            fixes.addFixes(fix);
-            s.close();
+    public static BackportedFixes parseBackportedFixFiles(List<File> fixFiles)
+            throws IOException {
+        try {
+            return fixFiles.stream().map(Parser::tunelFileInputStream)
+                    .map(Parser::tunnelParse)
+                    .sorted(Comparator.comparing(BackportedFix::getKnownIssue))
+                    .collect(fixCollector());
+
+        } catch (TunnelException e) {
+            throw e.rethrow(FileNotFoundException.class, IOException.class);
         }
-        return fixes.build();
+    }
+
+
+    private static Collector<BackportedFix, ?, BackportedFixes> fixCollector() {
+        return Collectors.collectingAndThen(Collectors.toList(), fixList -> {
+            var result = BackportedFixes.newBuilder();
+            result.addAllFixes(fixList);
+            return result.build();
+        });
+    }
+
+    private static FileInputStream tunelFileInputStream(File file) throws TunnelException {
+        try {
+            return new FileInputStream(file);
+        } catch (FileNotFoundException e) {
+            throw new TunnelException(e);
+        }
+    }
+
+    private static BackportedFix tunnelParse(InputStream s) throws TunnelException {
+        try {
+            var fix = BackportedFix.parseFrom(s);
+            s.close();
+            return fix;
+        } catch (IOException e) {
+            throw new TunnelException(e);
+        }
+    }
+
+    private static class TunnelException extends RuntimeException {
+        TunnelException(Exception cause) {
+            super("If you see this TunnelException something went wrong.  It should always be rethrown as the cause.", cause);
+        }
+
+        <X extends Exception> RuntimeException rethrow(Class<X> exceptionClazz) throws X {
+            checkNotNull(exceptionClazz);
+            Throwables.throwIfInstanceOf(getCause(), exceptionClazz);
+            throw exception(
+                    getCause(),
+                    "rethrow(%s) doesn't match underlying exception", exceptionClazz);
+        }
+
+        public <X1 extends Exception, X2 extends Exception> RuntimeException rethrow(
+                Class<X1> exceptionClazz1, Class<X2> exceptionClazz2) throws X1, X2 {
+            checkNotNull(exceptionClazz1);
+            checkNotNull(exceptionClazz2);
+            Throwables.throwIfInstanceOf(getCause(), exceptionClazz1);
+            Throwables.throwIfInstanceOf(getCause(), exceptionClazz2);
+            throw exception(
+                    getCause(),
+                    "rethrow(%s, %s) doesn't match underlying exception",
+                    exceptionClazz1,
+                    exceptionClazz2);
+        }
+
+        private static ClassCastException exception(
+                Throwable cause, String message, Object... formatArgs) {
+            ClassCastException result = new ClassCastException(String.format(message, formatArgs));
+            result.initCause(cause);
+            return result;
+        }
+
     }
 
     private Parser() {
diff --git a/backported_fixes/tests/java/com/android/build/backportedfixes/CombineBackportedFixesTest.java b/backported_fixes/tests/java/com/android/build/backportedfixes/CombineBackportedFixesTest.java
new file mode 100644
index 0000000..21d5f1e
--- /dev/null
+++ b/backported_fixes/tests/java/com/android/build/backportedfixes/CombineBackportedFixesTest.java
@@ -0,0 +1,41 @@
+
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.build.backportedfixes;
+
+import com.google.common.truth.Truth;
+
+import org.junit.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+/** Tests for {@link CombineBackportedFixes}. */
+public class CombineBackportedFixesTest {
+
+
+    @Test
+    public void writeBackportedFixes_default() throws IOException {
+        // Not much of a test, but there is not much to test.
+        BackportedFixes fixes = BackportedFixes.newBuilder()
+                .addFixes(BackportedFix.newBuilder().setKnownIssue(123).build())
+                .build();
+        var result = new ByteArrayOutputStream();
+        CombineBackportedFixes.writeBackportedFixes(fixes, result);
+        Truth.assertThat(BackportedFixes.parseFrom(result.toByteArray()))
+                .isEqualTo(fixes);
+    }
+}
diff --git a/backported_fixes/tests/java/com/android/build/backportedfixes/MainTest.java b/backported_fixes/tests/java/com/android/build/backportedfixes/WriteBackportedFixesPropFileTest.java
similarity index 87%
rename from backported_fixes/tests/java/com/android/build/backportedfixes/MainTest.java
rename to backported_fixes/tests/java/com/android/build/backportedfixes/WriteBackportedFixesPropFileTest.java
index 84061e1..3209c15 100644
--- a/backported_fixes/tests/java/com/android/build/backportedfixes/MainTest.java
+++ b/backported_fixes/tests/java/com/android/build/backportedfixes/WriteBackportedFixesPropFileTest.java
@@ -23,8 +23,8 @@
 import java.io.PrintWriter;
 import java.io.StringWriter;
 
-/** Tests for {@link Main}. */
-public class MainTest {
+/** Tests for {@link WriteBackportedFixesPropFile}. */
+public class WriteBackportedFixesPropFileTest {
 
 
     @Test
@@ -32,7 +32,7 @@
         BackportedFixes fixes = BackportedFixes.newBuilder().build();
         var result = new StringWriter();
 
-        Main.writeFixesAsAliasBitSet(fixes, new PrintWriter(result));
+        WriteBackportedFixesPropFile.writeFixesAsAliasBitSet(fixes, new PrintWriter(result));
 
         Truth.assertThat(result.toString())
                 .isEqualTo("""
@@ -50,7 +50,7 @@
                 .build();
         var result = new StringWriter();
 
-        Main.writeFixesAsAliasBitSet(fixes, new PrintWriter(result));
+        WriteBackportedFixesPropFile.writeFixesAsAliasBitSet(fixes, new PrintWriter(result));
 
         Truth.assertThat(result.toString())
                 .isEqualTo("""
diff --git a/backported_fixes/tests/java/com/android/build/backportedfixes/common/CloseableCollectionTest.java b/backported_fixes/tests/java/com/android/build/backportedfixes/common/CloseableCollectionTest.java
deleted file mode 100644
index d3d84a8..0000000
--- a/backported_fixes/tests/java/com/android/build/backportedfixes/common/CloseableCollectionTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2024 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.build.backportedfixes.common;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.common.truth.Correspondence;
-import com.google.common.truth.Truth;
-
-import org.junit.Test;
-
-/** Tests for {@link ClosableCollection}. */
-public class CloseableCollectionTest {
-
-    private static class FakeCloseable implements AutoCloseable {
-        private final boolean throwOnClose;
-        private final String name;
-
-
-        private boolean isClosed = false;
-
-        private FakeCloseable(String name, boolean throwOnClose) {
-            this.name = name;
-            this.throwOnClose = throwOnClose;
-
-        }
-
-        private static FakeCloseable named(String name) {
-            return new FakeCloseable(name, false);
-        }
-
-        private static FakeCloseable failing(String name) {
-            return new FakeCloseable(name, true);
-        }
-
-        public boolean isClosed() {
-            return isClosed;
-        }
-
-        @Override
-        public void close() throws Exception {
-            if (throwOnClose) {
-                throw new Exception(name + " close failed");
-            }
-            isClosed = true;
-        }
-    }
-
-
-    @Test
-    public void bothClosed() throws Exception {
-        var c = ImmutableSet.of(FakeCloseable.named("foo"), FakeCloseable.named("bar"));
-        try (var cc = ClosableCollection.wrap(c);) {
-            Truth.assertThat(cc.getCollection()).isSameInstanceAs(c);
-        }
-        Truth.assertThat(c)
-                .comparingElementsUsing(
-                        Correspondence.transforming(FakeCloseable::isClosed, "is closed"))
-                .containsExactly(true, true);
-    }
-
-    @Test
-    public void bothFailed() {
-        var c = ImmutableSet.of(FakeCloseable.failing("foo"), FakeCloseable.failing("bar"));
-
-        try {
-            try (var cc = ClosableCollection.wrap(c);) {
-                Truth.assertThat(cc.getCollection()).isSameInstanceAs(c);
-            }
-        } catch (Exception e) {
-            Truth.assertThat(e).hasMessageThat().isEqualTo("2 of 2 failed while closing");
-            Truth.assertThat(e.getSuppressed())
-                    .asList()
-                    .comparingElementsUsing(
-                            Correspondence.transforming(Exception::getMessage, "has a message of "))
-                    .containsExactly("foo close failed", "bar close failed");
-        }
-    }
-}
diff --git a/backported_fixes/tests/java/com/android/build/backportedfixes/common/ParserTest.java b/backported_fixes/tests/java/com/android/build/backportedfixes/common/ParserTest.java
index 444e694..57a0a40 100644
--- a/backported_fixes/tests/java/com/android/build/backportedfixes/common/ParserTest.java
+++ b/backported_fixes/tests/java/com/android/build/backportedfixes/common/ParserTest.java
@@ -23,15 +23,21 @@
 
 import com.google.common.collect.ImmutableList;
 
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
 
-import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileOutputStream;
 import java.io.IOException;
 import java.nio.file.Files;
 
 /** Tests for {@link Parser}.*/
 public class ParserTest {
 
+    @Rule
+    public TemporaryFolder mTempFolder = new TemporaryFolder();
+
     @Test
     public void getFileInputStreams() throws IOException {
         var results = Parser.getFileInputStreams(
@@ -53,15 +59,15 @@
     }
 
     @Test
-    public void parseBackportedFixes_empty() throws IOException {
-        var result = Parser.parseBackportedFixes(ImmutableList.of());
+    public void parseBackportedFixFiles_empty() throws IOException {
+        var result = Parser.parseBackportedFixFiles(ImmutableList.of());
         assertThat(result).isEqualTo(BackportedFixes.getDefaultInstance());
     }
 
+
     @Test
-    public void parseBackportedFixes_oneBlank() throws IOException {
-        var result = Parser.parseBackportedFixes(
-                ImmutableList.of(inputStream(BackportedFix.getDefaultInstance())));
+    public void parseBackportedFixFiles_oneBlank() throws IOException {
+        var result = Parser.parseBackportedFixFiles(ImmutableList.of(mTempFolder.newFile()));
 
         assertThat(result).isEqualTo(
                 BackportedFixes.newBuilder()
@@ -70,7 +76,7 @@
     }
 
     @Test
-    public void parseBackportedFixes_two() throws IOException {
+    public void parseBackportedFixFiles_two() throws IOException {
         BackportedFix ki123 = BackportedFix.newBuilder()
                 .setKnownIssue(123)
                 .setAlias(1)
@@ -79,8 +85,8 @@
                 .setKnownIssue(456)
                 .setAlias(2)
                 .build();
-        var result = Parser.parseBackportedFixes(
-                ImmutableList.of(inputStream(ki123), inputStream(ki456)));
+        var result = Parser.parseBackportedFixFiles(
+                ImmutableList.of(tempFile(ki456), tempFile(ki123)));
         assertThat(result).isEqualTo(
                 BackportedFixes.newBuilder()
                         .addFixes(ki123)
@@ -88,7 +94,11 @@
                         .build());
     }
 
-    private static ByteArrayInputStream inputStream(BackportedFix f) {
-        return new ByteArrayInputStream(f.toByteArray());
+    private File tempFile(BackportedFix fix) throws IOException {
+        File f = mTempFolder.newFile();
+        try (FileOutputStream out = new FileOutputStream(f)) {
+            fix.writeTo(out);
+            return f;
+        }
     }
 }
diff --git a/core/Makefile b/core/Makefile
index 1180073..38f8d8a 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -3556,7 +3556,7 @@
   PATH=$(INTERNAL_USERIMAGES_BINARY_PATHS):$$PATH \
       $(BUILD_IMAGE) \
           $(if $(BUILD_BROKEN_INCORRECT_PARTITION_IMAGES),,--input-directory-filter-file $(systemimage_intermediates)/file_list.txt) \
-          $(TARGET_OUT) $(systemimage_intermediates)/system_image_info.txt $(1) $(TARGET_OUT) \
+          $(TARGET_OUT) $(systemimage_intermediates)/system_image_info.txt $(1) $(TARGET_OUT) --build_datetime_file $(BUILD_DATETIME_FILE) \
           || ( mkdir -p $${DIST_DIR}; \
                cp $(INSTALLED_FILES_FILE) $${DIST_DIR}/installed-files-rescued.txt; \
                exit 1 )
@@ -3707,7 +3707,7 @@
   PATH=$(INTERNAL_USERIMAGES_BINARY_PATHS):$$PATH \
       $(BUILD_IMAGE) \
           $(if $(BUILD_BROKEN_INCORRECT_PARTITION_IMAGES),,--input-directory-filter-file $(userdataimage_intermediates)/file_list.txt) \
-          $(TARGET_OUT_DATA) $(userdataimage_intermediates)/userdata_image_info.txt \
+          $(TARGET_OUT_DATA) $(userdataimage_intermediates)/userdata_image_info.txt --build_datetime_file $(BUILD_DATETIME_FILE) \
           $(INSTALLED_USERDATAIMAGE_TARGET) $(TARGET_OUT)
   $(call assert-max-image-size,$(INSTALLED_USERDATAIMAGE_TARGET),$(BOARD_USERDATAIMAGE_PARTITION_SIZE))
 endef
@@ -3769,7 +3769,7 @@
   PATH=$(INTERNAL_USERIMAGES_BINARY_PATHS):$$PATH \
       $(BUILD_IMAGE) \
           $(if $(BUILD_BROKEN_INCORRECT_PARTITION_IMAGES),,--input-directory-filter-file $(cacheimage_intermediates)/file_list.txt) \
-          $(TARGET_OUT_CACHE) $(cacheimage_intermediates)/cache_image_info.txt \
+          $(TARGET_OUT_CACHE) $(cacheimage_intermediates)/cache_image_info.txt --build_datetime_file $(BUILD_DATETIME_FILE) \
           $(INSTALLED_CACHEIMAGE_TARGET) $(TARGET_OUT)
   $(call assert-max-image-size,$(INSTALLED_CACHEIMAGE_TARGET),$(BOARD_CACHEIMAGE_PARTITION_SIZE))
 endef
@@ -3856,7 +3856,7 @@
   PATH=$(INTERNAL_USERIMAGES_BINARY_PATHS):$$PATH \
       $(BUILD_IMAGE) \
           $(if $(BUILD_BROKEN_INCORRECT_PARTITION_IMAGES),,--input-directory-filter-file $(systemotherimage_intermediates)/file_list.txt) \
-          $(TARGET_OUT_SYSTEM_OTHER) $(systemotherimage_intermediates)/system_other_image_info.txt \
+          $(TARGET_OUT_SYSTEM_OTHER) $(systemotherimage_intermediates)/system_other_image_info.txt --build_datetime_file $(BUILD_DATETIME_FILE) \
           $(INSTALLED_SYSTEMOTHERIMAGE_TARGET) $(TARGET_OUT)
   $(call assert-max-image-size,$(INSTALLED_SYSTEMOTHERIMAGE_TARGET),$(BOARD_SYSTEMIMAGE_PARTITION_SIZE))
 endef
@@ -3962,7 +3962,7 @@
   PATH=$(INTERNAL_USERIMAGES_BINARY_PATHS):$$PATH \
       $(BUILD_IMAGE) \
           $(if $(BUILD_BROKEN_INCORRECT_PARTITION_IMAGES),,--input-directory-filter-file $(vendorimage_intermediates)/file_list.txt) \
-          $(TARGET_OUT_VENDOR) $(vendorimage_intermediates)/vendor_image_info.txt \
+          $(TARGET_OUT_VENDOR) $(vendorimage_intermediates)/vendor_image_info.txt --build_datetime_file $(BUILD_DATETIME_FILE) \
           $(INSTALLED_VENDORIMAGE_TARGET) $(TARGET_OUT)
   $(call assert-max-image-size,$(INSTALLED_VENDORIMAGE_TARGET) $(RECOVERY_FROM_BOOT_PATCH),$(BOARD_VENDORIMAGE_PARTITION_SIZE))
 endef
@@ -4050,7 +4050,7 @@
   PATH=$(INTERNAL_USERIMAGES_BINARY_PATHS):$$PATH \
       $(BUILD_IMAGE) \
           $(if $(BUILD_BROKEN_INCORRECT_PARTITION_IMAGES),,--input-directory-filter-file $(productimage_intermediates)/file_list.txt) \
-          $(TARGET_OUT_PRODUCT) $(productimage_intermediates)/product_image_info.txt \
+          $(TARGET_OUT_PRODUCT) $(productimage_intermediates)/product_image_info.txt --build_datetime_file $(BUILD_DATETIME_FILE) \
           $(INSTALLED_PRODUCTIMAGE_TARGET) $(TARGET_OUT)
   $(call assert-max-image-size,$(INSTALLED_PRODUCTIMAGE_TARGET),$(BOARD_PRODUCTIMAGE_PARTITION_SIZE))
 endef
@@ -4119,7 +4119,7 @@
       $(BUILD_IMAGE) \
           $(if $(BUILD_BROKEN_INCORRECT_PARTITION_IMAGES),,--input-directory-filter-file $(system_extimage_intermediates)/file_list.txt) \
           $(TARGET_OUT_SYSTEM_EXT) \
-          $(system_extimage_intermediates)/system_ext_image_info.txt \
+          $(system_extimage_intermediates)/system_ext_image_info.txt --build_datetime_file $(BUILD_DATETIME_FILE) \
           $(INSTALLED_SYSTEM_EXTIMAGE_TARGET) \
           $(TARGET_OUT)
   $(call assert-max-image-size,$(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET),$(BOARD_PRODUCT_SERVICESIMAGE_PARTITION_SIZE))
@@ -4209,7 +4209,7 @@
   PATH=$(INTERNAL_USERIMAGES_BINARY_PATHS):$$PATH \
       $(BUILD_IMAGE) \
           $(if $(BUILD_BROKEN_INCORRECT_PARTITION_IMAGES),,--input-directory-filter-file $(odmimage_intermediates)/file_list.txt) \
-          $(TARGET_OUT_ODM) $(odmimage_intermediates)/odm_image_info.txt \
+          $(TARGET_OUT_ODM) $(odmimage_intermediates)/odm_image_info.txt --build_datetime_file $(BUILD_DATETIME_FILE) \
           $(INSTALLED_ODMIMAGE_TARGET) $(TARGET_OUT)
   $(call assert-max-image-size,$(INSTALLED_ODMIMAGE_TARGET),$(BOARD_ODMIMAGE_PARTITION_SIZE))
 endef
@@ -4278,7 +4278,7 @@
   PATH=$(INTERNAL_USERIMAGES_BINARY_PATHS):$$PATH \
       $(BUILD_IMAGE) \
           $(if $(BUILD_BROKEN_INCORRECT_PARTITION_IMAGES),,--input-directory-filter-file $(vendor_dlkmimage_intermediates)/file_list.txt) \
-          $(TARGET_OUT_VENDOR_DLKM) $(vendor_dlkmimage_intermediates)/vendor_dlkm_image_info.txt \
+          $(TARGET_OUT_VENDOR_DLKM) $(vendor_dlkmimage_intermediates)/vendor_dlkm_image_info.txt --build_datetime_file $(BUILD_DATETIME_FILE) \
           $(INSTALLED_VENDOR_DLKMIMAGE_TARGET) $(TARGET_OUT)
   $(call assert-max-image-size,$(INSTALLED_VENDOR_DLKMIMAGE_TARGET),$(BOARD_VENDOR_DLKMIMAGE_PARTITION_SIZE))
 endef
@@ -4347,7 +4347,7 @@
   PATH=$(INTERNAL_USERIMAGES_BINARY_PATHS):$$PATH \
       $(BUILD_IMAGE) \
           $(if $(BUILD_BROKEN_INCORRECT_PARTITION_IMAGES),,--input-directory-filter-file $(odm_dlkmimage_intermediates)/file_list.txt) \
-          $(TARGET_OUT_ODM_DLKM) $(odm_dlkmimage_intermediates)/odm_dlkm_image_info.txt \
+          $(TARGET_OUT_ODM_DLKM) $(odm_dlkmimage_intermediates)/odm_dlkm_image_info.txt --build_datetime_file $(BUILD_DATETIME_FILE) \
           $(INSTALLED_ODM_DLKMIMAGE_TARGET) $(TARGET_OUT)
   $(call assert-max-image-size,$(INSTALLED_ODM_DLKMIMAGE_TARGET),$(BOARD_ODM_DLKMIMAGE_PARTITION_SIZE))
 endef
@@ -4418,7 +4418,7 @@
   PATH=$(INTERNAL_USERIMAGES_BINARY_PATHS):$$PATH \
       $(BUILD_IMAGE) \
           $(if $(BUILD_BROKEN_INCORRECT_PARTITION_IMAGES),,--input-directory-filter-file $(system_dlkmimage_intermediates)/file_list.txt) \
-          $(TARGET_OUT_SYSTEM_DLKM) $(system_dlkmimage_intermediates)/system_dlkm_image_info.txt \
+          $(TARGET_OUT_SYSTEM_DLKM) $(system_dlkmimage_intermediates)/system_dlkm_image_info.txt --build_datetime_file $(BUILD_DATETIME_FILE) \
           $(INSTALLED_SYSTEM_DLKMIMAGE_TARGET) $(TARGET_OUT)
   $(call assert-max-image-size,$(INSTALLED_SYSTEM_DLKMIMAGE_TARGET),$(BOARD_SYSTEM_DLKMIMAGE_PARTITION_SIZE))
 endef
diff --git a/core/android_soong_config_vars.mk b/core/android_soong_config_vars.mk
index 729b4f8..34d758b 100644
--- a/core/android_soong_config_vars.mk
+++ b/core/android_soong_config_vars.mk
@@ -81,6 +81,7 @@
 $(call soong_config_set_bool,chre,chre_daemon_lama_enabled,$(if $(filter true,$(CHRE_DAEMON_LPMA_ENABLED)),true,false))
 $(call soong_config_set_bool,chre,chre_dedicated_transport_channel_enabled,$(if $(filter true,$(CHRE_DEDICATED_TRANSPORT_CHANNEL_ENABLED)),true,false))
 $(call soong_config_set_bool,chre,chre_log_atom_extension_enabled,$(if $(filter true,$(CHRE_LOG_ATOM_EXTENSION_ENABLED)),true,false))
+$(call soong_config_set_bool,chre,building_vendor_image,$(if $(filter true,$(BUILDING_VENDOR_IMAGE)),true,false))
 
 ifdef TARGET_BOARD_AUTO
   $(call add_soong_config_var_value, ANDROID, target_board_auto, $(TARGET_BOARD_AUTO))
diff --git a/core/main.mk b/core/main.mk
index 624df49..4b76971 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -277,10 +277,7 @@
 # Include all of the makefiles in the system
 #
 
-subdir_makefiles := \
-    $(SOONG_OUT_DIR)/installs-$(TARGET_PRODUCT)$(COVERAGE_SUFFIX).mk \
-    $(SOONG_ANDROID_MK) \
-    build/make/target/board/android-info.mk
+subdir_makefiles := $(SOONG_OUT_DIR)/installs-$(TARGET_PRODUCT)$(COVERAGE_SUFFIX).mk $(SOONG_ANDROID_MK)
 
 # Android.mk files are only used on Linux builds, Mac only supports Android.bp
 ifeq ($(HOST_OS),linux)
diff --git a/core/release_config.mk b/core/release_config.mk
index fe2170e..68e115f 100644
--- a/core/release_config.mk
+++ b/core/release_config.mk
@@ -146,6 +146,9 @@
         # This will also set ALL_RELEASE_CONFIGS_FOR_PRODUCT and _used_files for us.
         $(eval include $(_flags_file))
         $(KATI_extra_file_deps $(OUT_DIR)/release-config $(protobuf_map_files) $(_flags_file))
+        ifneq (,$(_disallow_lunch_use))
+            $(error Release config ${TARGET_RELEASE} is disallowed for build.  Please use one of: $(ALL_RELEASE_CONFIGS_FOR_PRODUCT))
+        endif
     else
         # This is the first pass of product config.
         $(eval include $(_flags_varmk))
diff --git a/core/soong_config.mk b/core/soong_config.mk
index a007888..ace025e 100644
--- a/core/soong_config.mk
+++ b/core/soong_config.mk
@@ -447,6 +447,10 @@
   $(call add_json_str, BootSecurityPatch, $(BOOT_SECURITY_PATCH))
   $(call add_json_str, InitBootSecurityPatch, $(INIT_BOOT_SECURITY_PATCH))
   $(call add_json_str, VendorSecurityPatch, $(VENDOR_SECURITY_PATCH))
+  $(call add_json_str, OdmSecurityPatch, $(ODM_SECURITY_PATCH))
+  $(call add_json_str, SystemDlkmSecurityPatch, $(SYSTEM_DLKM_SECURITY_PATCH))
+  $(call add_json_str, VendorDlkmSecurityPatch, $(VENDOR_DLKM_SECURITY_PATCH))
+  $(call add_json_str, OdmDlkmSecurityPatch, $(ODM_DLKM_SECURITY_PATCH))
   $(call add_json_bool, BoardIncludeDtbInBootimg, $(BOARD_INCLUDE_DTB_IN_BOOTIMG))
   $(call add_json_list, InternalKernelCmdline, $(INTERNAL_KERNEL_CMDLINE))
   $(call add_json_list, InternalBootconfig, $(INTERNAL_BOOTCONFIG))
@@ -525,6 +529,22 @@
   # Used to generate recovery partition
   $(call add_json_str, TargetScreenDensity, $(TARGET_SCREEN_DENSITY))
 
+  # Used to generate /recovery/root/build.prop
+  $(call add_json_map, PrivateRecoveryUiProperties)
+    $(call add_json_str, animation_fps, $(TARGET_RECOVERY_UI_ANIMATION_FPS))
+    $(call add_json_str, margin_height, $(TARGET_RECOVERY_UI_MARGIN_HEIGHT))
+    $(call add_json_str, margin_width, $(TARGET_RECOVERY_UI_MARGIN_WIDTH))
+    $(call add_json_str, menu_unusable_rows, $(TARGET_RECOVERY_UI_MENU_UNUSABLE_ROWS))
+    $(call add_json_str, progress_bar_baseline, $(TARGET_RECOVERY_UI_PROGRESS_BAR_BASELINE))
+    $(call add_json_str, touch_low_threshold, $(TARGET_RECOVERY_UI_TOUCH_LOW_THRESHOLD))
+    $(call add_json_str, touch_high_threshold, $(TARGET_RECOVERY_UI_TOUCH_HIGH_THRESHOLD))
+    $(call add_json_str, vr_stereo_offset, $(TARGET_RECOVERY_UI_VR_STEREO_OFFSET))
+    $(call add_json_str, brightness_file, $(TARGET_RECOVERY_UI_BRIGHTNESS_FILE))
+    $(call add_json_str, max_brightness_file, $(TARGET_RECOVERY_UI_MAX_BRIGHTNESS_FILE))
+    $(call add_json_str, brightness_normal_percent, $(TARGET_RECOVERY_UI_BRIGHTNESS_NORMAL))
+    $(call add_json_str, brightness_dimmed_percent, $(TARGET_RECOVERY_UI_BRIGHTNESS_DIMMED))
+  $(call end_json_map)
+
 $(call end_json_map)
 
 # For converting vintf_data
diff --git a/core/sysprop.mk b/core/sysprop.mk
index dcde71b..aba6f8b 100644
--- a/core/sysprop.mk
+++ b/core/sysprop.mk
@@ -123,11 +123,19 @@
 ifneq ($(strip $(7)), true)
 	$(hide) $$(call generate-common-build-props,$(call to-lower,$(strip $(1))),$$@)
 endif
+        # Make and Soong use different intermediate files to build vendor/build.prop.
+        # Although the sysprop contents are same, the absolute paths of android_info.prop are different.
+        # Print the filename for the intermediate files (files in OUT_DIR).
+        # This helps with validating mk->soong migration of android partitions.
 	$(hide) $(foreach file,$(strip $(3)),\
 	    if [ -f "$(file)" ]; then\
 	        echo "" >> $$@;\
 	        echo "####################################" >> $$@;\
-	        echo "# from $(file)" >> $$@;\
+	        $(if $(filter $(OUT_DIR)/%,$(file)), \
+		echo "# from $(notdir $(file))" >> $$@;\
+		,\
+		echo "# from $(file)" >> $$@;\
+		)\
 	        echo "####################################" >> $$@;\
 	        cat $(file) >> $$@;\
 	    fi;)
diff --git a/target/board/android-info.mk b/target/board/Android.mk
similarity index 100%
rename from target/board/android-info.mk
rename to target/board/Android.mk
diff --git a/tools/aconfig/aconfig_flags/flags.aconfig b/tools/aconfig/aconfig_flags/flags.aconfig
index 0a004ca..367a2d0 100644
--- a/tools/aconfig/aconfig_flags/flags.aconfig
+++ b/tools/aconfig/aconfig_flags/flags.aconfig
@@ -14,3 +14,10 @@
   bug: "369808805"
   description: "When enabled, launch aconfigd from config infra module."
 }
+
+flag {
+  name: "tools_read_from_new_storage"
+  namespace: "core_experiments_team_internal"
+  bug: "370499640"
+  description: "When enabled, tools read directly from the new aconfig storage."
+}
\ No newline at end of file
diff --git a/tools/aconfig/aconfig_storage_read_api/Android.bp b/tools/aconfig/aconfig_storage_read_api/Android.bp
index 6214e2c..fa41ff0 100644
--- a/tools/aconfig/aconfig_storage_read_api/Android.bp
+++ b/tools/aconfig/aconfig_storage_read_api/Android.bp
@@ -154,7 +154,6 @@
 java_library {
     name: "aconfig_storage_reader_java",
     srcs: [
-        "srcs/android/aconfig/storage/StorageInternalReader.java",
         "srcs/android/os/flagging/PlatformAconfigPackageInternal.java",
     ],
     libs: [
diff --git a/tools/aconfig/aconfig_storage_read_api/srcs/android/aconfig/storage/StorageInternalReader.java b/tools/aconfig/aconfig_storage_read_api/srcs/android/aconfig/storage/StorageInternalReader.java
deleted file mode 100644
index 6fbcdb3..0000000
--- a/tools/aconfig/aconfig_storage_read_api/srcs/android/aconfig/storage/StorageInternalReader.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2024 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.aconfig.storage;
-
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.StrictMode;
-
-import java.io.Closeable;
-import java.nio.MappedByteBuffer;
-import java.nio.channels.FileChannel;
-import java.nio.file.Paths;
-import java.nio.file.StandardOpenOption;
-
-/** @hide */
-public class StorageInternalReader {
-
-    private static final String MAP_PATH = "/metadata/aconfig/maps/";
-    private static final String BOOT_PATH = "/metadata/aconfig/boot/";
-
-    private PackageTable mPackageTable;
-    private FlagValueList mFlagValueList;
-
-    private int mPackageBooleanStartOffset;
-
-    @UnsupportedAppUsage
-    public StorageInternalReader(String container, String packageName) {
-        this(packageName, MAP_PATH + container + ".package.map", BOOT_PATH + container + ".val");
-    }
-
-    @UnsupportedAppUsage
-    public StorageInternalReader(String packageName, String packageMapFile, String flagValueFile) {
-        StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
-        mPackageTable = PackageTable.fromBytes(mapStorageFile(packageMapFile));
-        mFlagValueList = FlagValueList.fromBytes(mapStorageFile(flagValueFile));
-        StrictMode.setThreadPolicy(oldPolicy);
-        mPackageBooleanStartOffset = getPackageBooleanStartOffset(packageName);
-    }
-
-    @UnsupportedAppUsage
-    public boolean getBooleanFlagValue(int index) {
-        index += mPackageBooleanStartOffset;
-        return mFlagValueList.getBoolean(index);
-    }
-
-    private int getPackageBooleanStartOffset(String packageName) {
-        PackageTable.Node pNode = mPackageTable.get(packageName);
-        if (pNode == null) {
-            PackageTable.Header header = mPackageTable.getHeader();
-            throw new AconfigStorageException(
-                    String.format(
-                            "Fail to get package %s from container %s",
-                            packageName, header.getContainer()));
-        }
-        return pNode.getBooleanStartIndex();
-    }
-
-    // Map a storage file given file path
-    private static MappedByteBuffer mapStorageFile(String file) {
-        FileChannel channel = null;
-        try {
-            channel = FileChannel.open(Paths.get(file), StandardOpenOption.READ);
-            return channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
-        } catch (Exception e) {
-            throw new AconfigStorageException(
-                    String.format("Fail to mmap storage file %s", file), e);
-        } finally {
-            quietlyDispose(channel);
-        }
-    }
-
-    private static void quietlyDispose(Closeable closable) {
-        try {
-            if (closable != null) {
-                closable.close();
-            }
-        } catch (Exception e) {
-            // no need to care, at least as of now
-        }
-    }
-}
diff --git a/tools/aconfig/aconfig_storage_read_api/srcs/android/os/flagging/PlatformAconfigPackageInternal.java b/tools/aconfig/aconfig_storage_read_api/srcs/android/os/flagging/PlatformAconfigPackageInternal.java
index d73d9eb..854e68b 100644
--- a/tools/aconfig/aconfig_storage_read_api/srcs/android/os/flagging/PlatformAconfigPackageInternal.java
+++ b/tools/aconfig/aconfig_storage_read_api/srcs/android/os/flagging/PlatformAconfigPackageInternal.java
@@ -84,15 +84,13 @@
         try {
             pNode = fileProvider.getPackageTable(container).get(packageName);
             vList = fileProvider.getFlagValueList(container);
-        } catch (AconfigStorageException e) {
-            throw new AconfigStorageReadException(e.getErrorCode(), e.toString());
         } finally {
             StrictMode.setThreadPolicy(oldPolicy);
         }
 
         if (pNode == null || vList == null) {
-            throw new AconfigStorageReadException(
-                    AconfigStorageReadException.ERROR_PACKAGE_NOT_FOUND,
+            throw new AconfigStorageException(
+                    AconfigStorageException.ERROR_PACKAGE_NOT_FOUND,
                     String.format(
                             "package "
                                     + packageName
@@ -102,8 +100,8 @@
         }
 
         if (pNode.hasPackageFingerprint() && packageFingerprint != pNode.getPackageFingerprint()) {
-            throw new AconfigStorageReadException(
-                    5, // AconfigStorageReadException.ERROR_FILE_FINGERPRINT_MISMATCH,
+            throw new AconfigStorageException(
+                    AconfigStorageException.ERROR_FILE_FINGERPRINT_MISMATCH,
                     String.format(
                             "package "
                                     + packageName
diff --git a/tools/aconfig/aconfig_storage_read_api/tests/functional/srcs/AconfigStorageReadAPITest.java b/tools/aconfig/aconfig_storage_read_api/tests/functional/srcs/AconfigStorageReadAPITest.java
index 6dd1bce..2557048 100644
--- a/tools/aconfig/aconfig_storage_read_api/tests/functional/srcs/AconfigStorageReadAPITest.java
+++ b/tools/aconfig/aconfig_storage_read_api/tests/functional/srcs/AconfigStorageReadAPITest.java
@@ -26,7 +26,6 @@
 import android.aconfig.storage.FlagReadContext.StoredFlagType;
 import android.aconfig.storage.PackageReadContext;
 import android.aconfig.storage.SipHasher13;
-import android.aconfig.storage.StorageInternalReader;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -225,46 +224,4 @@
             assertEquals(rHash, jHash);
         }
     }
-
-    @Test
-    public void testRustJavaEqualFlag() throws IOException {
-        List<parsed_flag> flags = DeviceProtos.loadAndParseFlagProtos();
-
-        String mapPath = "/metadata/aconfig/maps/";
-        String flagsPath = "/metadata/aconfig/boot/";
-
-        for (parsed_flag flag : flags) {
-
-            String container = flag.container;
-            String packageName = flag.package_;
-            String flagName = flag.name;
-            String fullFlagName = packageName + "/" + flagName;
-
-            MappedByteBuffer packageMap =
-                    AconfigStorageReadAPI.mapStorageFile(mapPath + container + ".package.map");
-            MappedByteBuffer flagMap =
-                    AconfigStorageReadAPI.mapStorageFile(mapPath + container + ".flag.map");
-            MappedByteBuffer flagValList =
-                    AconfigStorageReadAPI.mapStorageFile(flagsPath + container + ".val");
-
-            PackageReadContext packageContext =
-                    AconfigStorageReadAPI.getPackageReadContext(packageMap, packageName);
-
-            FlagReadContext flagContext =
-                    AconfigStorageReadAPI.getFlagReadContext(
-                            flagMap, packageContext.mPackageId, flagName);
-
-            boolean rVal =
-                    AconfigStorageReadAPI.getBooleanFlagValue(
-                            flagValList,
-                            packageContext.mBooleanStartIndex + flagContext.mFlagIndex);
-
-            StorageInternalReader reader = new StorageInternalReader(container, packageName);
-            boolean jVal = reader.getBooleanFlagValue(flagContext.mFlagIndex);
-
-            long rHash = AconfigStorageReadAPI.hash(packageName);
-            long jHash = SipHasher13.hash(packageName.getBytes());
-            assertEquals(rVal, jVal);
-        }
-    }
-}
\ No newline at end of file
+}
diff --git a/tools/aconfig/aconfig_storage_read_api/tests/functional/srcs/PlatformAconfigPackageInternalTest.java b/tools/aconfig/aconfig_storage_read_api/tests/functional/srcs/PlatformAconfigPackageInternalTest.java
index 69e224b..2b0aeae 100644
--- a/tools/aconfig/aconfig_storage_read_api/tests/functional/srcs/PlatformAconfigPackageInternalTest.java
+++ b/tools/aconfig/aconfig_storage_read_api/tests/functional/srcs/PlatformAconfigPackageInternalTest.java
@@ -26,7 +26,7 @@
 import android.aconfig.storage.FlagValueList;
 import android.aconfig.storage.PackageTable;
 import android.aconfig.storage.StorageFileProvider;
-import android.os.flagging.AconfigStorageReadException;
+import android.internal.aconfig.storage.AconfigStorageException;
 import android.os.flagging.PlatformAconfigPackageInternal;
 
 import org.junit.Test;
@@ -84,20 +84,20 @@
     @Test
     public void testAconfigPackage_load_withError() throws IOException {
         // container not found fake_container
-        AconfigStorageReadException e =
+        AconfigStorageException e =
                 assertThrows(
-                        AconfigStorageReadException.class,
+                        AconfigStorageException.class,
                         () ->
                                 PlatformAconfigPackageInternal.load(
                                         "fake_container", "fake_package", 0));
-        assertEquals(AconfigStorageReadException.ERROR_CANNOT_READ_STORAGE_FILE, e.getErrorCode());
+        assertEquals(AconfigStorageException.ERROR_CANNOT_READ_STORAGE_FILE, e.getErrorCode());
 
         // package not found
         e =
                 assertThrows(
-                        AconfigStorageReadException.class,
+                        AconfigStorageException.class,
                         () -> PlatformAconfigPackageInternal.load("system", "fake_container", 0));
-        assertEquals(AconfigStorageReadException.ERROR_PACKAGE_NOT_FOUND, e.getErrorCode());
+        assertEquals(AconfigStorageException.ERROR_PACKAGE_NOT_FOUND, e.getErrorCode());
 
         // fingerprint doesn't match
         List<parsed_flag> flags = DeviceProtos.loadAndParseFlagProtos();
@@ -116,13 +116,11 @@
             long fingerprint = pNode.getPackageFingerprint();
             e =
                     assertThrows(
-                            AconfigStorageReadException.class,
+                            AconfigStorageException.class,
                             () ->
                                     PlatformAconfigPackageInternal.load(
                                             container, packageName, fingerprint + 1));
-            assertEquals(
-                    // AconfigStorageException.ERROR_FILE_FINGERPRINT_MISMATCH,
-                    5, e.getErrorCode());
+            assertEquals(AconfigStorageException.ERROR_FILE_FINGERPRINT_MISMATCH, e.getErrorCode());
         }
     }
 }
diff --git a/tools/aconfig/aconfig_storage_read_api/tests/functional/srcs/StorageInternalReaderTest.java b/tools/aconfig/aconfig_storage_read_api/tests/functional/srcs/StorageInternalReaderTest.java
deleted file mode 100644
index 8a8f054..0000000
--- a/tools/aconfig/aconfig_storage_read_api/tests/functional/srcs/StorageInternalReaderTest.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2024 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.aconfig.storage.test;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import android.aconfig.storage.StorageInternalReader;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class StorageInternalReaderTest {
-
-    private String mStorageDir = "/data/local/tmp/aconfig_java_api_test";
-
-    @Test
-    public void testStorageInternalReader_getFlag() {
-
-        String packageMapFile = mStorageDir + "/maps/mockup.package.map";
-        String flagValueFile = mStorageDir + "/boot/mockup.val";
-
-        StorageInternalReader reader =
-                new StorageInternalReader(
-                        "com.android.aconfig.storage.test_1", packageMapFile, flagValueFile);
-        assertFalse(reader.getBooleanFlagValue(0));
-        assertTrue(reader.getBooleanFlagValue(1));
-    }
-}
\ No newline at end of file
diff --git a/tools/aconfig/aconfig_storage_read_api/tests/unit/srcs/PlatformAconfigPackageInternalTest.java b/tools/aconfig/aconfig_storage_read_api/tests/unit/srcs/PlatformAconfigPackageInternalTest.java
index 961f0ea..cac3de2 100644
--- a/tools/aconfig/aconfig_storage_read_api/tests/unit/srcs/PlatformAconfigPackageInternalTest.java
+++ b/tools/aconfig/aconfig_storage_read_api/tests/unit/srcs/PlatformAconfigPackageInternalTest.java
@@ -21,9 +21,9 @@
 import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 
+import android.aconfig.storage.AconfigStorageException;
 import android.aconfig.storage.PackageTable;
 import android.aconfig.storage.StorageFileProvider;
-import android.os.flagging.AconfigStorageReadException;
 import android.os.flagging.PlatformAconfigPackageInternal;
 
 import org.junit.Before;
@@ -62,44 +62,44 @@
         PackageTable.Node node1 = packageTable.get("com.android.aconfig.storage.test_1");
         long fingerprint = node1.getPackageFingerprint();
         // cannot find package
-        AconfigStorageReadException e =
+        AconfigStorageException e =
                 assertThrows(
-                        AconfigStorageReadException.class,
+                        AconfigStorageException.class,
                         () ->
                                 PlatformAconfigPackageInternal.load(
                                         "mockup",
                                         "com.android.aconfig.storage.test_10",
                                         fingerprint,
                                         pr));
-        assertEquals(AconfigStorageReadException.ERROR_PACKAGE_NOT_FOUND, e.getErrorCode());
+        assertEquals(AconfigStorageException.ERROR_PACKAGE_NOT_FOUND, e.getErrorCode());
 
         // cannot find container
         e =
                 assertThrows(
-                        AconfigStorageReadException.class,
+                        AconfigStorageException.class,
                         () ->
                                 PlatformAconfigPackageInternal.load(
                                         null,
                                         "com.android.aconfig.storage.test_1",
                                         fingerprint,
                                         pr));
-        assertEquals(AconfigStorageReadException.ERROR_CANNOT_READ_STORAGE_FILE, e.getErrorCode());
+        assertEquals(AconfigStorageException.ERROR_CANNOT_READ_STORAGE_FILE, e.getErrorCode());
 
         e =
                 assertThrows(
-                        AconfigStorageReadException.class,
+                        AconfigStorageException.class,
                         () ->
                                 PlatformAconfigPackageInternal.load(
                                         "test",
                                         "com.android.aconfig.storage.test_1",
                                         fingerprint,
                                         pr));
-        assertEquals(AconfigStorageReadException.ERROR_CANNOT_READ_STORAGE_FILE, e.getErrorCode());
+        assertEquals(AconfigStorageException.ERROR_CANNOT_READ_STORAGE_FILE, e.getErrorCode());
 
         // fingerprint doesn't match
         e =
                 assertThrows(
-                        AconfigStorageReadException.class,
+                        AconfigStorageException.class,
                         () ->
                                 PlatformAconfigPackageInternal.load(
                                         "mockup",
@@ -114,27 +114,27 @@
         pr = new StorageFileProvider("fake/path/", "fake/path/");
         e =
                 assertThrows(
-                        AconfigStorageReadException.class,
+                        AconfigStorageException.class,
                         () ->
                                 PlatformAconfigPackageInternal.load(
                                         "mockup",
                                         "com.android.aconfig.storage.test_1",
                                         fingerprint,
                                         pr));
-        assertEquals(AconfigStorageReadException.ERROR_CANNOT_READ_STORAGE_FILE, e.getErrorCode());
+        assertEquals(AconfigStorageException.ERROR_CANNOT_READ_STORAGE_FILE, e.getErrorCode());
 
         // file read issue
         pr = new StorageFileProvider(TESTDATA_PATH, "fake/path/");
         e =
                 assertThrows(
-                        AconfigStorageReadException.class,
+                        AconfigStorageException.class,
                         () ->
                                 PlatformAconfigPackageInternal.load(
                                         "mockup",
                                         "com.android.aconfig.storage.test_1",
                                         fingerprint,
                                         pr));
-        assertEquals(AconfigStorageReadException.ERROR_CANNOT_READ_STORAGE_FILE, e.getErrorCode());
+        assertEquals(AconfigStorageException.ERROR_CANNOT_READ_STORAGE_FILE, e.getErrorCode());
     }
 
     @Test
diff --git a/tools/aconfig/aflags/src/aconfig_storage_source.rs b/tools/aconfig/aflags/src/aconfig_storage_source.rs
index aef7d7e..766807a 100644
--- a/tools/aconfig/aflags/src/aconfig_storage_source.rs
+++ b/tools/aconfig/aflags/src/aconfig_storage_source.rs
@@ -17,6 +17,23 @@
 
 pub struct AconfigStorageSource {}
 
+static ACONFIGD_SYSTEM_SOCKET_NAME: &str = "/dev/socket/aconfigd_system";
+static ACONFIGD_MAINLINE_SOCKET_NAME: &str = "/dev/socket/aconfigd_mainline";
+
+enum AconfigdSocket {
+    System,
+    Mainline,
+}
+
+impl AconfigdSocket {
+    pub fn name(&self) -> &str {
+        match self {
+            AconfigdSocket::System => ACONFIGD_SYSTEM_SOCKET_NAME,
+            AconfigdSocket::Mainline => ACONFIGD_MAINLINE_SOCKET_NAME,
+        }
+    }
+}
+
 fn load_flag_to_container() -> Result<HashMap<String, String>> {
     Ok(load_protos::load()?.into_iter().map(|p| (p.qualified_name(), p.container)).collect())
 }
@@ -81,7 +98,7 @@
     })
 }
 
-fn read_from_socket() -> Result<Vec<ProtoFlagQueryReturnMessage>> {
+fn read_from_socket(socket: AconfigdSocket) -> Result<Vec<ProtoFlagQueryReturnMessage>> {
     let messages = ProtoStorageRequestMessages {
         msgs: vec![ProtoStorageRequestMessage {
             msg: Some(ProtoStorageRequestMessageMsg::ListStorageMessage(ProtoListStorageMessage {
@@ -93,8 +110,7 @@
         special_fields: SpecialFields::new(),
     };
 
-    let socket_name = "/dev/socket/aconfigd_system";
-    let mut socket = UnixStream::connect(socket_name)?;
+    let mut socket = UnixStream::connect(socket.name())?;
 
     let message_buffer = messages.write_to_bytes()?;
     let mut message_length_buffer: [u8; 4] = [0; 4];
@@ -128,14 +144,20 @@
 impl FlagSource for AconfigStorageSource {
     fn list_flags() -> Result<Vec<Flag>> {
         let containers = load_flag_to_container()?;
-        read_from_socket()
-            .map(|query_messages| {
-                query_messages
-                    .iter()
-                    .map(|message| convert(message.clone(), &containers))
-                    .collect::<Vec<_>>()
-            })?
+        let system_messages = read_from_socket(AconfigdSocket::System);
+        let mainline_messages = read_from_socket(AconfigdSocket::Mainline);
+
+        let mut all_messages = vec![];
+        if let Ok(system_messages) = system_messages {
+            all_messages.extend_from_slice(&system_messages);
+        }
+        if let Ok(mainline_messages) = mainline_messages {
+            all_messages.extend_from_slice(&mainline_messages);
+        }
+
+        all_messages
             .into_iter()
+            .map(|query_message| convert(query_message.clone(), &containers))
             .collect()
     }
 
diff --git a/tools/finalization/build-step-0.sh b/tools/finalization/build-step-0.sh
index 8826b35..bc41a19 100755
--- a/tools/finalization/build-step-0.sh
+++ b/tools/finalization/build-step-0.sh
@@ -25,8 +25,8 @@
     fi;
 
     if [ "$need_vintf_finalize" = true ] ; then        # VINTF finalization
-        source $top/build/make/tools/finalization/finalize-vintf-resources.sh
+        source $top/build/make/tools/finalization/finalize-vintf-resources.sh $@
     fi;
 }
 
-finalize_main_step0
+finalize_main_step0 $@
diff --git a/tools/finalization/finalize-vintf-resources.sh b/tools/finalization/finalize-vintf-resources.sh
index 45efc10..2a92959 100755
--- a/tools/finalization/finalize-vintf-resources.sh
+++ b/tools/finalization/finalize-vintf-resources.sh
@@ -3,6 +3,21 @@
 set -ex
 
 function finalize_vintf_resources() {
+    if [ $# -gt 1 ]; then
+        echo "No argument or '--steps_for_build_test_only' is allowed"
+        exit 1
+    fi
+    if [ $# -eq 1 ]; then
+        if [ "$1" == "--steps_for_build_test_only" ]; then
+            echo "This is only to verify building a target."
+            echo "Skip LLNDK ABI dump and VINTF check."
+            local build_test_only=true
+        else
+            echo "Unknown argument $1"
+            exit 1
+        fi
+    fi
+
     local top="$(dirname "$0")"/../../../..
     source $top/build/make/tools/finalization/environment.sh
     # environment needed to build dependencies and run scripts
@@ -26,18 +41,21 @@
     # system/sepolicy
     "$top/system/sepolicy/tools/finalize-vintf-resources.sh" "$top" "$FINAL_BOARD_API_LEVEL"
 
-    create_new_compat_matrix_and_kernel_configs
+    create_new_compat_matrix_and_kernel_configs $build_test_only
 
     # pre-finalization build target (trunk)
     local aidl_m="$top/build/soong/soong_ui.bash --make-mode"
     AIDL_TRANSITIVE_FREEZE=true $aidl_m aidl-freeze-api create_reference_dumps
 
-    # Generate LLNDK ABI dumps
-    # This command depends on ANDROID_BUILD_TOP
-    "$ANDROID_HOST_OUT/bin/create_reference_dumps" -release "$TARGET_RELEASE" --build-variant "$TARGET_BUILD_VARIANT" --lib-variant LLNDK
+    if ! [ "$build_test_only" = "true" ]; then
+        # Generate LLNDK ABI dumps
+        # This command depends on ANDROID_BUILD_TOP
+        "$ANDROID_HOST_OUT/bin/create_reference_dumps" -release "$TARGET_RELEASE" --build-variant "$TARGET_BUILD_VARIANT" --lib-variant LLNDK
+    fi
 }
 
 function create_new_compat_matrix_and_kernel_configs() {
+    local build_test_only=$1
     # The compatibility matrix versions are bumped during vFRC
     # These will change every time we have a new vFRC
     local CURRENT_COMPATIBILITY_MATRIX_LEVEL="$FINAL_BOARD_API_LEVEL"
@@ -53,10 +71,12 @@
 
     "$top/prebuilts/build-tools/path/linux-x86/python3" "$top/hardware/interfaces/compatibility_matrices/bump.py" "$CURRENT_COMPATIBILITY_MATRIX_LEVEL" "$NEXT_COMPATIBILITY_MATRIX_LEVEL" "$CURRENT_RELEASE_LETTER" "$NEXT_RELEASE_LETTER" "$FINAL_CORRESPONDING_PLATFORM_VERSION"
 
-    # Freeze the current framework manifest file. This relies on the
-    # aosp_cf_x86_64-trunk_staging build target to get the right manifest
-    # fragments installed.
-    "$top/system/libhidl/vintfdata/freeze.sh" "$CURRENT_COMPATIBILITY_MATRIX_LEVEL"
+    if ! [ "$build_test_only" = "true" ]; then
+        # Freeze the current framework manifest file. This relies on the
+        # aosp_cf_x86_64-trunk_staging build target to get the right manifest
+        # fragments installed.
+        "$top/system/libhidl/vintfdata/freeze.sh" "$CURRENT_COMPATIBILITY_MATRIX_LEVEL"
+    fi
 }
 
 function freeze_framework_manifest() {
@@ -65,5 +85,5 @@
 }
 
 
-finalize_vintf_resources
+finalize_vintf_resources $@
 
diff --git a/tools/releasetools/build_image.py b/tools/releasetools/build_image.py
index 464ad9b..25bcb52 100755
--- a/tools/releasetools/build_image.py
+++ b/tools/releasetools/build_image.py
@@ -677,6 +677,21 @@
       glob_dict["fingerprint"] = fingerprint
       return
 
+def TryParseFingerprintAndTimestamp(glob_dict):
+  """Helper function that parses fingerprint and timestamp from the global dictionary.
+
+  Args:
+    glob_dict: the global dictionary from the build system.
+  """
+  TryParseFingerprint(glob_dict)
+
+  # Set fixed timestamp for building the OTA package.
+  if "use_fixed_timestamp" in glob_dict:
+    glob_dict["timestamp"] = FIXED_FILE_TIMESTAMP
+  if "build.prop" in glob_dict:
+    timestamp = glob_dict["build.prop"].GetProp("ro.build.date.utc")
+    if timestamp:
+      glob_dict["timestamp"] = timestamp
 
 def ImagePropFromGlobalDict(glob_dict, mount_point):
   """Build an image property dictionary from the global dictionary.
@@ -686,15 +701,7 @@
     mount_point: such as "system", "data" etc.
   """
   d = {}
-  TryParseFingerprint(glob_dict)
-
-  # Set fixed timestamp for building the OTA package.
-  if "use_fixed_timestamp" in glob_dict:
-    d["timestamp"] = FIXED_FILE_TIMESTAMP
-  if "build.prop" in glob_dict:
-    timestamp = glob_dict["build.prop"].GetProp("ro.build.date.utc")
-    if timestamp:
-      d["timestamp"] = timestamp
+  TryParseFingerprintAndTimestamp(glob_dict)
 
   def copy_prop(src_p, dest_p):
     """Copy a property from the global dictionary.
@@ -730,6 +737,7 @@
       "avb_avbtool",
       "use_dynamic_partition_size",
       "fingerprint",
+      "timestamp",
   )
   for p in common_props:
     copy_prop(p, p)
@@ -969,6 +977,8 @@
     "will install in by default, so there could be files in the input_directory that are not "
     "actually supposed to be part of the partition. The paths in this file must be relative to "
     "input_directory.")
+  parser.add_argument("--build_datetime_file",
+                      help="a file containing the build id timestamp")
   parser.add_argument("input_directory",
     help="the staging directory to be converted to an image file")
   parser.add_argument("properties_file",
@@ -988,10 +998,16 @@
   common.InitLogging()
 
   glob_dict = LoadGlobalDict(args.properties_file)
+  if args.build_datetime_file:
+    # Parse the timestamp from build_datetime_file.
+    with open(args.build_datetime_file, "r") as f:
+      glob_dict["timestamp"] = int(f.read())
+
   if "mount_point" in glob_dict:
     # The caller knows the mount point and provides a dictionary needed by
     # BuildImage().
     image_properties = glob_dict
+    TryParseFingerprintAndTimestamp(image_properties)
   else:
     image_filename = os.path.basename(args.out_file)
     mount_point = ""