Merge "libgui: use flag MACRO for BQ_SETFRAMERATE" into main
diff --git a/cmds/installd/otapreopt.cpp b/cmds/installd/otapreopt.cpp
index 822ab7f..8eb7458 100644
--- a/cmds/installd/otapreopt.cpp
+++ b/cmds/installd/otapreopt.cpp
@@ -514,6 +514,8 @@
         // Make sure dex2oat is run with background priority.
         dexopt_flags |= DEXOPT_BOOTCOMPLETE | DEXOPT_IDLE_BACKGROUND_JOB;
 
+        parameters_.compilation_reason = "ab-ota";
+
         int res = dexopt(parameters_.apk_path,
                          parameters_.uid,
                          parameters_.pkgName,
diff --git a/include/input/VelocityTracker.h b/include/input/VelocityTracker.h
index 2e99495..ee74455 100644
--- a/include/input/VelocityTracker.h
+++ b/include/input/VelocityTracker.h
@@ -98,7 +98,7 @@
     void addMovement(nsecs_t eventTime, int32_t pointerId, int32_t axis, float position);
 
     // Adds movement information for all pointers in a MotionEvent, including historical samples.
-    void addMovement(const MotionEvent* event);
+    void addMovement(const MotionEvent& event);
 
     // Returns the velocity of the specified pointer id and axis in position units per second.
     // Returns empty optional if there is insufficient movement information for the pointer, or if
diff --git a/libs/binder/tests/unit_fuzzers/RecordedTransactionFileFuzz.cpp b/libs/binder/tests/unit_fuzzers/RecordedTransactionFileFuzz.cpp
index e494366..f3006cd 100644
--- a/libs/binder/tests/unit_fuzzers/RecordedTransactionFileFuzz.cpp
+++ b/libs/binder/tests/unit_fuzzers/RecordedTransactionFileFuzz.cpp
@@ -35,7 +35,7 @@
     if (transaction.has_value()) {
         intermediateFile = std::tmpfile();
 
-        android::base::unique_fd fdForWriting(fileno(intermediateFile));
+        android::base::unique_fd fdForWriting(dup(fileno(intermediateFile)));
         auto writeStatus ATTRIBUTE_UNUSED = transaction.value().dumpToFile(fdForWriting);
 
         std::fclose(intermediateFile);
diff --git a/libs/input/VelocityTracker.cpp b/libs/input/VelocityTracker.cpp
index 116b778..613a0df 100644
--- a/libs/input/VelocityTracker.cpp
+++ b/libs/input/VelocityTracker.cpp
@@ -275,10 +275,10 @@
     }
 }
 
-void VelocityTracker::addMovement(const MotionEvent* event) {
+void VelocityTracker::addMovement(const MotionEvent& event) {
     // Stores data about which axes to process based on the incoming motion event.
     std::set<int32_t> axesToProcess;
-    int32_t actionMasked = event->getActionMasked();
+    int32_t actionMasked = event.getActionMasked();
 
     switch (actionMasked) {
         case AMOTION_EVENT_ACTION_DOWN:
@@ -291,7 +291,7 @@
             // Start a new movement trace for a pointer that just went down.
             // We do this on down instead of on up because the client may want to query the
             // final velocity for a pointer that just went up.
-            clearPointer(event->getPointerId(event->getActionIndex()));
+            clearPointer(event.getPointerId(event.getActionIndex()));
             axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end());
             break;
         }
@@ -300,8 +300,14 @@
             axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end());
             break;
         case AMOTION_EVENT_ACTION_POINTER_UP:
+            if (event.getFlags() & AMOTION_EVENT_FLAG_CANCELED) {
+                clearPointer(event.getPointerId(event.getActionIndex()));
+                return;
+            }
+            // Continue to ACTION_UP to ensure that the POINTER_STOPPED logic is triggered.
+            [[fallthrough]];
         case AMOTION_EVENT_ACTION_UP: {
-            std::chrono::nanoseconds delaySinceLastEvent(event->getEventTime() - mLastEventTime);
+            std::chrono::nanoseconds delaySinceLastEvent(event.getEventTime() - mLastEventTime);
             if (delaySinceLastEvent > ASSUME_POINTER_STOPPED_TIME) {
                 ALOGD_IF(DEBUG_VELOCITY,
                          "VelocityTracker: stopped for %s, clearing state upon pointer liftoff.",
@@ -325,21 +331,26 @@
         case AMOTION_EVENT_ACTION_SCROLL:
             axesToProcess.insert(AMOTION_EVENT_AXIS_SCROLL);
             break;
+        case AMOTION_EVENT_ACTION_CANCEL: {
+            clear();
+            return;
+        }
+
         default:
             // Ignore all other actions.
             return;
     }
 
-    const size_t historySize = event->getHistorySize();
+    const size_t historySize = event.getHistorySize();
     for (size_t h = 0; h <= historySize; h++) {
-        const nsecs_t eventTime = event->getHistoricalEventTime(h);
-        for (size_t i = 0; i < event->getPointerCount(); i++) {
-            if (event->isResampled(i, h)) {
+        const nsecs_t eventTime = event.getHistoricalEventTime(h);
+        for (size_t i = 0; i < event.getPointerCount(); i++) {
+            if (event.isResampled(i, h)) {
                 continue; // skip resampled samples
             }
-            const int32_t pointerId = event->getPointerId(i);
+            const int32_t pointerId = event.getPointerId(i);
             for (int32_t axis : axesToProcess) {
-                const float position = event->getHistoricalAxisValue(axis, i, h);
+                const float position = event.getHistoricalAxisValue(axis, i, h);
                 addMovement(eventTime, pointerId, axis, position);
             }
         }
diff --git a/libs/input/rust/input_verifier.rs b/libs/input/rust/input_verifier.rs
index bbc6d98..5f05a0f 100644
--- a/libs/input/rust/input_verifier.rs
+++ b/libs/input/rust/input_verifier.rs
@@ -118,18 +118,17 @@
 
         match action.into() {
             MotionAction::Down => {
+                if self.touching_pointer_ids_by_device.contains_key(&device_id) {
+                    return Err(format!(
+                        "{}: Invalid DOWN event - pointers already down for device {:?}: {:?}",
+                        self.name, device_id, self.touching_pointer_ids_by_device
+                    ));
+                }
                 let it = self
                     .touching_pointer_ids_by_device
                     .entry(device_id)
                     .or_insert_with(HashSet::new);
-                let pointer_id = pointer_properties[0].id;
-                if it.contains(&pointer_id) {
-                    return Err(format!(
-                        "{}: Invalid DOWN event - pointers already down for device {:?}: {:?}",
-                        self.name, device_id, it
-                    ));
-                }
-                it.insert(pointer_id);
+                it.insert(pointer_properties[0].id);
             }
             MotionAction::PointerDown { action_index } => {
                 if !self.touching_pointer_ids_by_device.contains_key(&device_id) {
@@ -353,6 +352,56 @@
     }
 
     #[test]
+    fn two_pointer_stream() {
+        let mut verifier = InputVerifier::new("Test", /*should_log*/ false);
+        let pointer_properties = Vec::from([RustPointerProperties { id: 0 }]);
+        assert!(verifier
+            .process_movement(
+                DeviceId(1),
+                Source::Touchscreen,
+                input_bindgen::AMOTION_EVENT_ACTION_DOWN,
+                &pointer_properties,
+                MotionFlags::empty(),
+            )
+            .is_ok());
+        // POINTER 1 DOWN
+        let two_pointer_properties =
+            Vec::from([RustPointerProperties { id: 0 }, RustPointerProperties { id: 1 }]);
+        assert!(verifier
+            .process_movement(
+                DeviceId(1),
+                Source::Touchscreen,
+                input_bindgen::AMOTION_EVENT_ACTION_POINTER_DOWN
+                    | (1 << input_bindgen::AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
+                &two_pointer_properties,
+                MotionFlags::empty(),
+            )
+            .is_ok());
+        // POINTER 0 UP
+        assert!(verifier
+            .process_movement(
+                DeviceId(1),
+                Source::Touchscreen,
+                input_bindgen::AMOTION_EVENT_ACTION_POINTER_UP
+                    | (0 << input_bindgen::AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
+                &two_pointer_properties,
+                MotionFlags::empty(),
+            )
+            .is_ok());
+        // ACTION_UP for pointer id=1
+        let pointer_1_properties = Vec::from([RustPointerProperties { id: 1 }]);
+        assert!(verifier
+            .process_movement(
+                DeviceId(1),
+                Source::Touchscreen,
+                input_bindgen::AMOTION_EVENT_ACTION_UP,
+                &pointer_1_properties,
+                MotionFlags::empty(),
+            )
+            .is_ok());
+    }
+
+    #[test]
     fn multi_device_stream() {
         let mut verifier = InputVerifier::new("Test", /*should_log*/ false);
         let pointer_properties = Vec::from([RustPointerProperties { id: 0 }]);
diff --git a/libs/input/tests/VelocityTracker_test.cpp b/libs/input/tests/VelocityTracker_test.cpp
index 1c8ec90..f9ca280 100644
--- a/libs/input/tests/VelocityTracker_test.cpp
+++ b/libs/input/tests/VelocityTracker_test.cpp
@@ -229,41 +229,23 @@
     return events;
 }
 
-static std::optional<float> computePlanarVelocity(
-        const VelocityTracker::Strategy strategy,
-        const std::vector<PlanarMotionEventEntry>& motions, int32_t axis,
-        uint32_t pointerId = DEFAULT_POINTER_ID) {
+static std::optional<float> computeVelocity(const VelocityTracker::Strategy strategy,
+                                            const std::vector<MotionEvent>& events, int32_t axis,
+                                            uint32_t pointerId = DEFAULT_POINTER_ID) {
     VelocityTracker vt(strategy);
 
-    std::vector<MotionEvent> events = createTouchMotionEventStream(motions);
-    for (MotionEvent event : events) {
-        vt.addMovement(&event);
+    for (const MotionEvent& event : events) {
+        vt.addMovement(event);
     }
 
     return vt.getVelocity(axis, pointerId);
 }
 
-static std::vector<MotionEvent> createMotionEventStream(
-        int32_t axis, const std::vector<std::pair<std::chrono::nanoseconds, float>>& motion) {
-    switch (axis) {
-        case AMOTION_EVENT_AXIS_SCROLL:
-            return createAxisScrollMotionEventStream(motion);
-        default:
-            ADD_FAILURE() << "Axis " << axis << " is not supported";
-            return {};
-    }
-}
-
-static std::optional<float> computeVelocity(
+static std::optional<float> computePlanarVelocity(
         const VelocityTracker::Strategy strategy,
-        const std::vector<std::pair<std::chrono::nanoseconds, float>>& motions, int32_t axis) {
-    VelocityTracker vt(strategy);
-
-    for (const MotionEvent& event : createMotionEventStream(axis, motions)) {
-        vt.addMovement(&event);
-    }
-
-    return vt.getVelocity(axis, DEFAULT_POINTER_ID);
+        const std::vector<PlanarMotionEventEntry>& motions, int32_t axis, uint32_t pointerId) {
+    std::vector<MotionEvent> events = createTouchMotionEventStream(motions);
+    return computeVelocity(strategy, events, axis, pointerId);
 }
 
 static void computeAndCheckVelocity(const VelocityTracker::Strategy strategy,
@@ -277,23 +259,23 @@
         const VelocityTracker::Strategy strategy,
         const std::vector<std::pair<std::chrono::nanoseconds, float>>& motions,
         std::optional<float> targetVelocity) {
-    checkVelocity(computeVelocity(strategy, motions, AMOTION_EVENT_AXIS_SCROLL), targetVelocity);
+    std::vector<MotionEvent> events = createAxisScrollMotionEventStream(motions);
+    checkVelocity(computeVelocity(strategy, events, AMOTION_EVENT_AXIS_SCROLL), targetVelocity);
     // The strategy LSQ2 is not compatible with AXIS_SCROLL. In those situations, we should fall
     // back to a strategy that supports differential axes.
-    checkVelocity(computeVelocity(VelocityTracker::Strategy::LSQ2, motions,
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::LSQ2, events,
                                   AMOTION_EVENT_AXIS_SCROLL),
                   targetVelocity);
 }
 
 static void computeAndCheckQuadraticVelocity(const std::vector<PlanarMotionEventEntry>& motions,
                                              float velocity) {
-    VelocityTracker vt(VelocityTracker::Strategy::LSQ2);
-    std::vector<MotionEvent> events = createTouchMotionEventStream(motions);
-    for (MotionEvent event : events) {
-        vt.addMovement(&event);
-    }
-    std::optional<float> velocityX = vt.getVelocity(AMOTION_EVENT_AXIS_X, 0);
-    std::optional<float> velocityY = vt.getVelocity(AMOTION_EVENT_AXIS_Y, 0);
+    std::optional<float> velocityX =
+            computePlanarVelocity(VelocityTracker::Strategy::LSQ2, motions, AMOTION_EVENT_AXIS_X,
+                                  DEFAULT_POINTER_ID);
+    std::optional<float> velocityY =
+            computePlanarVelocity(VelocityTracker::Strategy::LSQ2, motions, AMOTION_EVENT_AXIS_Y,
+                                  DEFAULT_POINTER_ID);
     ASSERT_TRUE(velocityX);
     ASSERT_TRUE(velocityY);
 
@@ -330,12 +312,14 @@
                                                    {30ms, {{6, 20}}},
                                                    {40ms, {{10, 30}}}};
 
-    EXPECT_EQ(computePlanarVelocity(VelocityTracker::Strategy::LSQ2, motions, AMOTION_EVENT_AXIS_X),
+    EXPECT_EQ(computePlanarVelocity(VelocityTracker::Strategy::LSQ2, motions, AMOTION_EVENT_AXIS_X,
+                                    DEFAULT_POINTER_ID),
               computePlanarVelocity(VelocityTracker::Strategy::DEFAULT, motions,
-                                    AMOTION_EVENT_AXIS_X));
-    EXPECT_EQ(computePlanarVelocity(VelocityTracker::Strategy::LSQ2, motions, AMOTION_EVENT_AXIS_Y),
+                                    AMOTION_EVENT_AXIS_X, DEFAULT_POINTER_ID));
+    EXPECT_EQ(computePlanarVelocity(VelocityTracker::Strategy::LSQ2, motions, AMOTION_EVENT_AXIS_Y,
+                                    DEFAULT_POINTER_ID),
               computePlanarVelocity(VelocityTracker::Strategy::DEFAULT, motions,
-                                    AMOTION_EVENT_AXIS_Y));
+                                    AMOTION_EVENT_AXIS_Y, DEFAULT_POINTER_ID));
 }
 
 TEST_F(VelocityTrackerTest, TestComputedVelocity) {
@@ -431,7 +415,7 @@
     VelocityTracker vt(VelocityTracker::Strategy::IMPULSE);
     std::vector<MotionEvent> events = createTouchMotionEventStream(motions);
     for (const MotionEvent& event : events) {
-        vt.addMovement(&event);
+        vt.addMovement(event);
     }
 
     float maxFloat = std::numeric_limits<float>::max();
@@ -509,6 +493,89 @@
     computeAndCheckVelocity(VelocityTracker::Strategy::LSQ2, motions, AMOTION_EVENT_AXIS_X, 500);
 }
 
+/**
+ * When the stream is terminated with ACTION_CANCEL, the resulting velocity should be 0.
+ */
+TEST_F(VelocityTrackerTest, ActionCancelResultsInZeroVelocity) {
+    std::vector<PlanarMotionEventEntry> motions = {
+            {0ms, {{0, 0}}},    // DOWN
+            {10ms, {{5, 10}}},  // MOVE
+            {20ms, {{10, 20}}}, // MOVE
+            {20ms, {{10, 20}}}, // ACTION_UP
+    };
+    std::vector<MotionEvent> events = createTouchMotionEventStream(motions);
+    // By default, `createTouchMotionEventStream` produces an event stream that terminates with
+    // ACTION_UP. We need to manually change it to ACTION_CANCEL.
+    MotionEvent& lastEvent = events.back();
+    lastEvent.setAction(AMOTION_EVENT_ACTION_CANCEL);
+    lastEvent.setFlags(lastEvent.getFlags() | AMOTION_EVENT_FLAG_CANCELED);
+    const int32_t pointerId = lastEvent.getPointerId(0);
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::IMPULSE, events, AMOTION_EVENT_AXIS_X,
+                                  pointerId),
+                  /*targetVelocity*/ std::nullopt);
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::IMPULSE, events, AMOTION_EVENT_AXIS_Y,
+                                  pointerId),
+                  /*targetVelocity*/ std::nullopt);
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::LSQ2, events, AMOTION_EVENT_AXIS_X,
+                                  pointerId),
+                  /*targetVelocity*/ std::nullopt);
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::LSQ2, events, AMOTION_EVENT_AXIS_Y,
+                                  pointerId),
+                  /*targetVelocity*/ std::nullopt);
+}
+
+/**
+ * When the stream is terminated with ACTION_CANCEL, the resulting velocity should be 0.
+ */
+TEST_F(VelocityTrackerTest, ActionPointerCancelResultsInZeroVelocityForThatPointer) {
+    std::vector<PlanarMotionEventEntry> motions = {
+            {0ms, {{0, 5}, {NAN, NAN}}},    // DOWN
+            {0ms, {{0, 5}, {10, 15}}},      // POINTER_DOWN
+            {10ms, {{5, 10}, {15, 20}}},    // MOVE
+            {20ms, {{10, 15}, {20, 25}}},   // MOVE
+            {30ms, {{10, 15}, {20, 25}}},   // POINTER_UP
+            {30ms, {{10, 15}, {NAN, NAN}}}, // UP
+    };
+    std::vector<MotionEvent> events = createTouchMotionEventStream(motions);
+    // Cancel the lifting pointer of the ACTION_POINTER_UP event
+    MotionEvent& pointerUpEvent = events.rbegin()[1];
+    pointerUpEvent.setFlags(pointerUpEvent.getFlags() | AMOTION_EVENT_FLAG_CANCELED);
+    const int32_t pointerId = pointerUpEvent.getPointerId(pointerUpEvent.getActionIndex());
+    // Double check the stream
+    ASSERT_EQ(1, pointerId);
+    ASSERT_EQ(AMOTION_EVENT_ACTION_POINTER_UP, pointerUpEvent.getActionMasked());
+    ASSERT_EQ(AMOTION_EVENT_ACTION_UP, events.back().getActionMasked());
+
+    // Ensure the velocity of the lifting pointer is zero
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::IMPULSE, events, AMOTION_EVENT_AXIS_X,
+                                  pointerId),
+                  /*targetVelocity*/ std::nullopt);
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::IMPULSE, events, AMOTION_EVENT_AXIS_Y,
+                                  pointerId),
+                  /*targetVelocity*/ std::nullopt);
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::LSQ2, events, AMOTION_EVENT_AXIS_X,
+                                  pointerId),
+                  /*targetVelocity*/ std::nullopt);
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::LSQ2, events, AMOTION_EVENT_AXIS_Y,
+                                  pointerId),
+                  /*targetVelocity*/ std::nullopt);
+
+    // The remaining pointer should have the correct velocity.
+    const int32_t remainingPointerId = events.back().getPointerId(0);
+    ASSERT_EQ(0, remainingPointerId);
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::IMPULSE, events, AMOTION_EVENT_AXIS_X,
+                                  remainingPointerId),
+                  /*targetVelocity*/ 500);
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::IMPULSE, events, AMOTION_EVENT_AXIS_Y,
+                                  remainingPointerId),
+                  /*targetVelocity*/ 500);
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::LSQ2, events, AMOTION_EVENT_AXIS_X,
+                                  remainingPointerId),
+                  /*targetVelocity*/ 500);
+    checkVelocity(computeVelocity(VelocityTracker::Strategy::LSQ2, events, AMOTION_EVENT_AXIS_Y,
+                                  remainingPointerId),
+                  /*targetVelocity*/ 500);
+}
 
 /**
  * ================== VelocityTracker tests generated by recording real events =====================
@@ -1336,9 +1403,10 @@
             {40ms, 100},
     };
 
-    EXPECT_EQ(computeVelocity(VelocityTracker::Strategy::IMPULSE, motions,
+    std::vector<MotionEvent> events = createAxisScrollMotionEventStream(motions);
+    EXPECT_EQ(computeVelocity(VelocityTracker::Strategy::IMPULSE, events,
                               AMOTION_EVENT_AXIS_SCROLL),
-              computeVelocity(VelocityTracker::Strategy::DEFAULT, motions,
+              computeVelocity(VelocityTracker::Strategy::DEFAULT, events,
                               AMOTION_EVENT_AXIS_SCROLL));
 }
 
diff --git a/services/inputflinger/dispatcher/InputDispatcher.cpp b/services/inputflinger/dispatcher/InputDispatcher.cpp
index 7dfbf94..991d3e6 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.cpp
+++ b/services/inputflinger/dispatcher/InputDispatcher.cpp
@@ -2864,8 +2864,13 @@
         it = inputTargets.end() - 1;
     }
 
-    LOG_ALWAYS_FATAL_IF(it->flags != targetFlags);
-    LOG_ALWAYS_FATAL_IF(it->globalScaleFactor != windowInfo->globalScaleFactor);
+    if (it->flags != targetFlags) {
+        LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
+    }
+    if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
+        LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
+                   << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
+    }
 }
 
 void InputDispatcher::addPointerWindowTargetLocked(
@@ -2910,8 +2915,13 @@
         it = inputTargets.end() - 1;
     }
 
-    LOG_ALWAYS_FATAL_IF(it->flags != targetFlags);
-    LOG_ALWAYS_FATAL_IF(it->globalScaleFactor != windowInfo->globalScaleFactor);
+    if (it->flags != targetFlags) {
+        LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
+    }
+    if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
+        LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
+                   << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
+    }
 
     it->addPointers(pointerIds, windowInfo->transform);
 }
diff --git a/services/surfaceflinger/DisplayHardware/DisplayMode.h b/services/surfaceflinger/DisplayHardware/DisplayMode.h
index 1775a7a..f32fb3a 100644
--- a/services/surfaceflinger/DisplayHardware/DisplayMode.h
+++ b/services/surfaceflinger/DisplayHardware/DisplayMode.h
@@ -30,8 +30,8 @@
 #include <scheduler/Fps.h>
 
 #include "DisplayHardware/Hal.h"
+#include "FlagManager.h"
 #include "Scheduler/StrongTyping.h"
-#include "Utils/FlagUtils.h"
 
 namespace android {
 
@@ -50,7 +50,6 @@
 
 using DisplayModes = ftl::SmallMap<DisplayModeId, DisplayModePtr, 3>;
 using DisplayModeIterator = DisplayModes::const_iterator;
-using namespace com::android::graphics::surfaceflinger;
 
 class DisplayMode {
 public:
@@ -140,7 +139,7 @@
     // Peak refresh rate represents the highest refresh rate that can be used
     // for the presentation.
     Fps getPeakFps() const {
-        return flagutils::vrrConfigEnabled() && mVrrConfig
+        return FlagManager::getInstance().vrr_config() && mVrrConfig
                 ? Fps::fromPeriodNsecs(mVrrConfig->minFrameIntervalNs)
                 : mVsyncRate;
     }
diff --git a/services/surfaceflinger/FlagManager.cpp b/services/surfaceflinger/FlagManager.cpp
index f8ad8f6..a8f05bb 100644
--- a/services/surfaceflinger/FlagManager.cpp
+++ b/services/surfaceflinger/FlagManager.cpp
@@ -26,37 +26,21 @@
 #include <server_configurable_flags/get_flags.h>
 #include <cinttypes>
 
-namespace android {
-static constexpr const char* kExperimentNamespace = "surface_flinger_native_boot";
-static constexpr const int64_t kDemoFlag = -1;
+#include <com_android_graphics_surfaceflinger_flags.h>
 
+namespace android {
+using namespace com::android::graphics::surfaceflinger;
+
+static constexpr const char* kExperimentNamespace = "surface_flinger_native_boot";
+
+std::unique_ptr<FlagManager> FlagManager::mInstance;
+std::once_flag FlagManager::mOnce;
+
+FlagManager::FlagManager(ConstructorTag) {}
 FlagManager::~FlagManager() = default;
 
-void FlagManager::dump(std::string& result) const {
-    base::StringAppendF(&result, "FlagManager values: \n");
-    base::StringAppendF(&result, "demo_flag: %" PRId64 "\n", demo_flag());
-    base::StringAppendF(&result, "use_adpf_cpu_hint: %s\n", use_adpf_cpu_hint() ? "true" : "false");
-    base::StringAppendF(&result, "use_skia_tracing: %s\n", use_skia_tracing() ? "true" : "false");
-}
-
 namespace {
-template <typename T>
-std::optional<T> doParse(const char* str);
-
-template <>
-[[maybe_unused]] std::optional<int32_t> doParse(const char* str) {
-    int32_t ret;
-    return base::ParseInt(str, &ret) ? std::make_optional(ret) : std::nullopt;
-}
-
-template <>
-[[maybe_unused]] std::optional<int64_t> doParse(const char* str) {
-    int64_t ret;
-    return base::ParseInt(str, &ret) ? std::make_optional(ret) : std::nullopt;
-}
-
-template <>
-[[maybe_unused]] std::optional<bool> doParse(const char* str) {
+std::optional<bool> parseBool(const char* str) {
     base::ParseBoolResult parseResult = base::ParseBool(str);
     switch (parseResult) {
         case base::ParseBoolResult::kTrue:
@@ -67,44 +51,129 @@
             return std::nullopt;
     }
 }
+
+bool getFlagValue(std::function<bool()> getter, std::optional<bool> overrideValue) {
+    if (overrideValue.has_value()) {
+        return *overrideValue;
+    }
+
+    return getter();
+}
+
+void dumpFlag(std::string& result, const char* name, std::function<bool()> getter) {
+    base::StringAppendF(&result, "%s: %s\n", name, getter() ? "true" : "false");
+}
+
 } // namespace
 
-std::string FlagManager::getServerConfigurableFlag(const std::string& experimentFlagName) const {
-    return server_configurable_flags::GetServerConfigurableFlag(kExperimentNamespace,
-                                                                experimentFlagName, "");
+const FlagManager& FlagManager::getInstance() {
+    return getMutableInstance();
 }
 
-template int32_t FlagManager::getValue<int32_t>(const std::string&, std::optional<int32_t>,
-                                                int32_t) const;
-template int64_t FlagManager::getValue<int64_t>(const std::string&, std::optional<int64_t>,
-                                                int64_t) const;
-template bool FlagManager::getValue<bool>(const std::string&, std::optional<bool>, bool) const;
-template <typename T>
-T FlagManager::getValue(const std::string& experimentFlagName, std::optional<T> systemPropertyOpt,
-                        T defaultValue) const {
-    // System property takes precedence over the experiment config server value.
-    if (systemPropertyOpt.has_value()) {
-        return *systemPropertyOpt;
+FlagManager& FlagManager::getMutableInstance() {
+    std::call_once(mOnce, [&] {
+        LOG_ALWAYS_FATAL_IF(mInstance, "Instance already created");
+        mInstance = std::make_unique<FlagManager>(ConstructorTag{});
+    });
+
+    return *mInstance;
+}
+
+void FlagManager::markBootCompleted() {
+    mBootCompleted = true;
+}
+
+void FlagManager::setUnitTestMode() {
+    mUnitTestMode = true;
+
+    // Also set boot completed as we don't really care about it in unit testing
+    mBootCompleted = true;
+}
+
+void FlagManager::dump(std::string& result) const {
+#define DUMP_FLAG(name) dumpFlag(result, #name, std::bind(&FlagManager::name, this))
+
+    base::StringAppendF(&result, "FlagManager values: \n");
+    DUMP_FLAG(use_adpf_cpu_hint);
+    DUMP_FLAG(use_skia_tracing);
+    DUMP_FLAG(connected_display);
+    DUMP_FLAG(dont_skip_on_early);
+    DUMP_FLAG(enable_small_area_detection);
+    DUMP_FLAG(misc1);
+    DUMP_FLAG(late_boot_misc2);
+    DUMP_FLAG(vrr_config);
+
+#undef DUMP_FLAG
+}
+
+std::optional<bool> FlagManager::getBoolProperty(const char* property) const {
+    return parseBool(base::GetProperty(property, "").c_str());
+}
+
+bool FlagManager::getServerConfigurableFlag(const char* experimentFlagName) const {
+    const auto value = server_configurable_flags::GetServerConfigurableFlag(kExperimentNamespace,
+                                                                            experimentFlagName, "");
+    const auto res = parseBool(value.c_str());
+    return res.has_value() && res.value();
+}
+
+#define FLAG_MANAGER_LEGACY_SERVER_FLAG(name, syspropOverride, serverFlagName)              \
+    bool FlagManager::name() const {                                                        \
+        LOG_ALWAYS_FATAL_IF(!mBootCompleted,                                                \
+                            "Can't read %s before boot completed as it is server writable", \
+                            __func__);                                                      \
+        const auto debugOverride = getBoolProperty(syspropOverride);                        \
+        if (debugOverride.has_value()) return debugOverride.value();                        \
+        return getServerConfigurableFlag(serverFlagName);                                   \
     }
-    std::string str = getServerConfigurableFlag(experimentFlagName);
-    return str.empty() ? defaultValue : doParse<T>(str.c_str()).value_or(defaultValue);
-}
 
-int64_t FlagManager::demo_flag() const {
-    std::optional<int64_t> sysPropVal = std::nullopt;
-    return getValue("DemoFeature__demo_flag", sysPropVal, kDemoFlag);
-}
+#define FLAG_MANAGER_FLAG_INTERNAL(name, syspropOverride, checkForBootCompleted)                \
+    bool FlagManager::name() const {                                                            \
+        if (checkForBootCompleted) {                                                            \
+            LOG_ALWAYS_FATAL_IF(!mBootCompleted,                                                \
+                                "Can't read %s before boot completed as it is server writable", \
+                                __func__);                                                      \
+        }                                                                                       \
+        static std::optional<bool> debugOverride = getBoolProperty(syspropOverride);            \
+        static bool value = getFlagValue([] { return flags::name(); }, debugOverride);          \
+        if (mUnitTestMode) {                                                                    \
+            /*                                                                                  \
+             * When testing, we don't want to rely on the cached values stored in the static    \
+             * variables.                                                                       \
+             */                                                                                 \
+            debugOverride = getBoolProperty(syspropOverride);                                   \
+            value = getFlagValue([] { return flags::name(); }, debugOverride);                  \
+        }                                                                                       \
+        return value;                                                                           \
+    }
 
-bool FlagManager::use_adpf_cpu_hint() const {
-    std::optional<bool> sysPropVal =
-            doParse<bool>(base::GetProperty("debug.sf.enable_adpf_cpu_hint", "").c_str());
-    return getValue("AdpfFeature__adpf_cpu_hint", sysPropVal, false);
-}
+#define FLAG_MANAGER_SERVER_FLAG(name, syspropOverride) \
+    FLAG_MANAGER_FLAG_INTERNAL(name, syspropOverride, true)
 
-bool FlagManager::use_skia_tracing() const {
-    std::optional<bool> sysPropVal =
-            doParse<bool>(base::GetProperty(PROPERTY_SKIA_ATRACE_ENABLED, "").c_str());
-    return getValue("SkiaTracingFeature__use_skia_tracing", sysPropVal, false);
+#define FLAG_MANAGER_READ_ONLY_FLAG(name, syspropOverride) \
+    FLAG_MANAGER_FLAG_INTERNAL(name, syspropOverride, false)
+
+/// Legacy server flags ///
+FLAG_MANAGER_LEGACY_SERVER_FLAG(test_flag, "", "")
+FLAG_MANAGER_LEGACY_SERVER_FLAG(use_adpf_cpu_hint, "debug.sf.enable_adpf_cpu_hint",
+                                "AdpfFeature__adpf_cpu_hint")
+FLAG_MANAGER_LEGACY_SERVER_FLAG(use_skia_tracing, PROPERTY_SKIA_ATRACE_ENABLED,
+                                "SkiaTracingFeature__use_skia_tracing")
+
+/// Trunk stable readonly flags ///
+FLAG_MANAGER_READ_ONLY_FLAG(connected_display, "")
+FLAG_MANAGER_READ_ONLY_FLAG(enable_small_area_detection, "")
+FLAG_MANAGER_READ_ONLY_FLAG(misc1, "")
+FLAG_MANAGER_READ_ONLY_FLAG(vrr_config, "debug.sf.enable_vrr_config")
+
+/// Trunk stable server flags ///
+FLAG_MANAGER_SERVER_FLAG(late_boot_misc2, "")
+
+/// Exceptions ///
+bool FlagManager::dont_skip_on_early() const {
+    // Even though this is a server writable flag, we do call it before boot completed, but that's
+    // fine since the decision is done per frame. We can't do caching though.
+    return flags::dont_skip_on_early();
 }
 
 } // namespace android
diff --git a/services/surfaceflinger/FlagManager.h b/services/surfaceflinger/FlagManager.h
index e834142..5a353bb 100644
--- a/services/surfaceflinger/FlagManager.h
+++ b/services/surfaceflinger/FlagManager.h
@@ -17,32 +17,59 @@
 #pragma once
 
 #include <cstdint>
+#include <mutex>
 #include <optional>
 #include <string>
 
 namespace android {
 // Manages flags for SurfaceFlinger, including default values, system properties, and Mendel
-// experiment configuration values.
+// experiment configuration values. Can be called from any thread.
 class FlagManager {
+private:
+    // Effectively making the constructor private, while allowing std::make_unique to work
+    struct ConstructorTag {};
+
 public:
-    FlagManager() = default;
+    static const FlagManager& getInstance();
+    static FlagManager& getMutableInstance();
+
+    FlagManager(ConstructorTag);
     virtual ~FlagManager();
+
+    void markBootCompleted();
     void dump(std::string& result) const;
 
-    int64_t demo_flag() const;
+    void setUnitTestMode();
 
+    /// Legacy server flags ///
+    bool test_flag() const;
     bool use_adpf_cpu_hint() const;
-
     bool use_skia_tracing() const;
 
+    /// Trunk stable readonly flags ///
+    bool connected_display() const;
+    bool enable_small_area_detection() const;
+    bool misc1() const;
+    bool vrr_config() const;
+
+    /// Trunk stable server flags ///
+    bool late_boot_misc2() const;
+    bool dont_skip_on_early() const;
+
+protected:
+    // overridden for unit tests
+    virtual std::optional<bool> getBoolProperty(const char*) const;
+    virtual bool getServerConfigurableFlag(const char*) const;
+
 private:
-    friend class FlagManagerTest;
+    friend class TestableFlagManager;
 
-    // Wrapper for mocking in test.
-    virtual std::string getServerConfigurableFlag(const std::string& experimentFlagName) const;
+    FlagManager(const FlagManager&) = delete;
 
-    template <typename T>
-    T getValue(const std::string& experimentFlagName, std::optional<T> systemPropertyOpt,
-               T defaultValue) const;
+    std::atomic_bool mBootCompleted = false;
+    std::atomic_bool mUnitTestMode = false;
+
+    static std::unique_ptr<FlagManager> mInstance;
+    static std::once_flag mOnce;
 };
 } // namespace android
diff --git a/services/surfaceflinger/RefreshRateOverlay.cpp b/services/surfaceflinger/RefreshRateOverlay.cpp
index 42676c6..2ac7319 100644
--- a/services/surfaceflinger/RefreshRateOverlay.cpp
+++ b/services/surfaceflinger/RefreshRateOverlay.cpp
@@ -17,9 +17,9 @@
 #include <algorithm>
 
 #include "Client.h"
+#include "FlagManager.h"
 #include "Layer.h"
 #include "RefreshRateOverlay.h"
-#include "Utils/FlagUtils.h"
 
 #include <SkSurface.h>
 
@@ -268,7 +268,8 @@
 }
 
 void RefreshRateOverlay::changeRenderRate(Fps renderFps) {
-    if (mFeatures.test(Features::RenderRate) && mVsyncRate && flagutils::vrrConfigEnabled()) {
+    if (mFeatures.test(Features::RenderRate) && mVsyncRate &&
+        FlagManager::getInstance().vrr_config()) {
         mRenderFps = renderFps;
         const auto buffer = getOrCreateBuffers(*mVsyncRate, renderFps)[mFrame];
         createTransaction().setBuffer(mSurfaceControl->get(), buffer).apply();
diff --git a/services/surfaceflinger/Scheduler/EventThread.cpp b/services/surfaceflinger/Scheduler/EventThread.cpp
index 9a55c94..7f627f8 100644
--- a/services/surfaceflinger/Scheduler/EventThread.cpp
+++ b/services/surfaceflinger/Scheduler/EventThread.cpp
@@ -45,6 +45,7 @@
 
 #include <scheduler/VsyncConfig.h>
 #include "DisplayHardware/DisplayMode.h"
+#include "FlagManager.h"
 #include "FrameTimeline.h"
 #include "VSyncDispatch.h"
 #include "VSyncTracker.h"
@@ -308,7 +309,7 @@
     auto connection = sp<EventThreadConnection>::make(const_cast<EventThread*>(this),
                                                       IPCThreadState::self()->getCallingUid(),
                                                       eventRegistration);
-    if (flags::misc1()) {
+    if (FlagManager::getInstance().misc1()) {
         const int policy = SCHED_FIFO;
         connection->setMinSchedulerPolicy(policy, sched_get_priority_min(policy));
     }
diff --git a/services/surfaceflinger/Scheduler/LayerHistory.cpp b/services/surfaceflinger/Scheduler/LayerHistory.cpp
index ff82914..21bbb08 100644
--- a/services/surfaceflinger/Scheduler/LayerHistory.cpp
+++ b/services/surfaceflinger/Scheduler/LayerHistory.cpp
@@ -21,7 +21,6 @@
 #include "LayerHistory.h"
 
 #include <android-base/stringprintf.h>
-#include <com_android_graphics_surfaceflinger_flags.h>
 #include <cutils/properties.h>
 #include <gui/TraceUtils.h>
 #include <utils/Log.h>
@@ -34,16 +33,15 @@
 
 #include "../Layer.h"
 #include "EventThread.h"
+#include "FlagManager.h"
 #include "LayerInfo.h"
 
 namespace android::scheduler {
 
 namespace {
 
-using namespace com::android::graphics::surfaceflinger;
-
 bool isLayerActive(const LayerInfo& info, nsecs_t threshold) {
-    if (flags::misc1() && !info.isVisible()) {
+    if (FlagManager::getInstance().misc1() && !info.isVisible()) {
         return false;
     }
 
diff --git a/services/surfaceflinger/Scheduler/RefreshRateSelector.cpp b/services/surfaceflinger/Scheduler/RefreshRateSelector.cpp
index eb69d0b..5892b2b 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateSelector.cpp
+++ b/services/surfaceflinger/Scheduler/RefreshRateSelector.cpp
@@ -38,7 +38,6 @@
 
 #include "../SurfaceFlingerProperties.h"
 #include "RefreshRateSelector.h"
-#include "Utils/FlagUtils.h"
 
 #include <com_android_graphics_surfaceflinger_flags.h>
 
@@ -115,7 +114,7 @@
     using fps_approx_ops::operator/;
     // use signed type as `fps / range.max` might be 0
     auto start = std::max(1, static_cast<int>(peakFps / range.max) - 1);
-    if (flagutils::vrrConfigEnabled()) {
+    if (FlagManager::getInstance().vrr_config()) {
         start = std::max(1,
                          static_cast<int>(vsyncRate /
                                           std::min(range.max, peakFps, fps_approx_ops::operator<)) -
diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp
index 5b36a5e..1a8713d 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.cpp
+++ b/services/surfaceflinger/Scheduler/Scheduler.cpp
@@ -47,6 +47,7 @@
 
 #include "../Layer.h"
 #include "EventThread.h"
+#include "FlagManager.h"
 #include "FrameRateOverrideMappings.h"
 #include "FrontEnd/LayerHandle.h"
 #include "OneShotTimer.h"
@@ -210,7 +211,7 @@
         targeters.try_emplace(id, &targeter);
     }
 
-    if (flagutils::vrrConfigEnabled() &&
+    if (FlagManager::getInstance().vrr_config() &&
         CC_UNLIKELY(mPacesetterFrameDurationFractionToSkip > 0.f)) {
         const auto period = pacesetterTargeter.target().expectedFrameDuration();
         const auto skipDuration = Duration::fromNs(
diff --git a/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp b/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp
index f467670..186a6bc 100644
--- a/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp
+++ b/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp
@@ -25,16 +25,14 @@
 
 #include <scheduler/TimeKeeper.h>
 
+#include "FlagManager.h"
 #include "VSyncDispatchTimerQueue.h"
 #include "VSyncTracker.h"
 
-#include <com_android_graphics_surfaceflinger_flags.h>
-
 #undef LOG_TAG
 #define LOG_TAG "VSyncDispatch"
 
 namespace android::scheduler {
-using namespace com::android::graphics::surfaceflinger;
 
 using base::StringAppendF;
 
@@ -43,7 +41,8 @@
 nsecs_t getExpectedCallbackTime(nsecs_t now, nsecs_t nextVsyncTime,
                                 const VSyncDispatch::ScheduleTiming& timing) {
     const auto expectedCallbackTime = nextVsyncTime - timing.readyDuration - timing.workDuration;
-    const auto baseTime = flags::dont_skip_on_early() ? now : expectedCallbackTime;
+    const auto baseTime =
+            FlagManager::getInstance().dont_skip_on_early() ? now : expectedCallbackTime;
     return std::max(baseTime, expectedCallbackTime);
 }
 
@@ -105,7 +104,7 @@
             mArmedInfo && (nextVsyncTime > (mArmedInfo->mActualVsyncTime + mMinVsyncDistance));
     bool const wouldSkipAWakeup =
             mArmedInfo && ((nextWakeupTime > (mArmedInfo->mActualWakeupTime + mMinVsyncDistance)));
-    if (flags::dont_skip_on_early()) {
+    if (FlagManager::getInstance().dont_skip_on_early()) {
         if (wouldSkipAVsyncTarget || wouldSkipAWakeup) {
             return getExpectedCallbackTime(now, mArmedInfo->mActualVsyncTime, timing);
         }
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 48be33c..62eb17d 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -157,15 +157,12 @@
 #include "TimeStats/TimeStats.h"
 #include "TunnelModeEnabledReporter.h"
 #include "Utils/Dumper.h"
-#include "Utils/FlagUtils.h"
 #include "WindowInfosListenerInvoker.h"
 
 #include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
 #include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
 #include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
 
-#include <com_android_graphics_surfaceflinger_flags.h>
-
 #undef NO_THREAD_SAFETY_ANALYSIS
 #define NO_THREAD_SAFETY_ANALYSIS \
     _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
@@ -175,8 +172,6 @@
 #define DOES_CONTAIN_BORDER false
 
 namespace android {
-using namespace com::android::graphics::surfaceflinger;
-
 using namespace std::chrono_literals;
 using namespace std::string_literals;
 using namespace std::string_view_literals;
@@ -509,11 +504,6 @@
             base::GetBoolProperty("persist.debug.sf.enable_layer_lifecycle_manager"s, true);
     mLegacyFrontEndEnabled = !mLayerLifecycleManagerEnabled ||
             base::GetBoolProperty("persist.debug.sf.enable_legacy_frontend"s, false);
-
-    // Trunk-Stable flags
-    mMiscFlagValue = flags::misc1();
-    mConnectedDisplayFlagValue = flags::connected_display();
-    mMisc2FlagEarlyBootValue = flags::late_boot_misc2();
 }
 
 LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
@@ -689,6 +679,7 @@
         return;
     }
     mBootFinished = true;
+    FlagManager::getMutableInstance().markBootCompleted();
     if (mStartPropertySetThread->join() != NO_ERROR) {
         ALOGE("Join StartPropertySetThread failed!");
     }
@@ -702,7 +693,7 @@
 
     mFrameTracer->initialize();
     mFrameTimeline->onBootFinished();
-    getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
+    getRenderEngine().setEnableTracing(FlagManager::getInstance().use_skia_tracing());
 
     // wait patiently for the window manager death
     const String16 name("window");
@@ -731,7 +722,7 @@
 
         readPersistentProperties();
         mPowerAdvisor->onBootFinished();
-        const bool hintSessionEnabled = mFlagManager.use_adpf_cpu_hint();
+        const bool hintSessionEnabled = FlagManager::getInstance().use_adpf_cpu_hint();
         mPowerAdvisor->enablePowerHintSession(hintSessionEnabled);
         const bool hintSessionUsed = mPowerAdvisor->usePowerHintSession();
         ALOGD("Power hint is %s",
@@ -755,10 +746,6 @@
             enableRefreshRateOverlay(true);
         }
     }));
-
-    LOG_ALWAYS_FATAL_IF(flags::misc1() != mMiscFlagValue, "misc1 flag is not boot stable!");
-
-    mMisc2FlagLateBootValue = flags::late_boot_misc2();
 }
 
 static std::optional<renderengine::RenderEngine::RenderEngineType>
@@ -2101,7 +2088,7 @@
 
 void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
                                         std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
-    if (mConnectedDisplayFlagValue) {
+    if (FlagManager::getInstance().connected_display()) {
         // use ~0 instead of -1 as AidlComposerHal.cpp passes the param as unsigned int32
         if (mIsHotplugErrViaNegVsync && timestamp < 0 && vsyncPeriod.has_value() &&
             vsyncPeriod.value() == ~0) {
@@ -4065,7 +4052,7 @@
 
     if (sysprop::use_content_detection_for_refresh_rate(false)) {
         features |= Feature::kContentDetection;
-        if (flags::enable_small_area_detection()) {
+        if (FlagManager::getInstance().enable_small_area_detection()) {
             features |= Feature::kSmallDirtyContentDetection;
         }
     }
@@ -6475,17 +6462,6 @@
     result.append("SurfaceFlinger global state:\n");
     colorizer.reset(result);
 
-    StringAppendF(&result, "MiscFlagValue: %s\n", mMiscFlagValue ? "true" : "false");
-    StringAppendF(&result, "ConnectedDisplayFlagValue: %s\n",
-                  mConnectedDisplayFlagValue ? "true" : "false");
-    StringAppendF(&result, "Misc2FlagValue: %s (%s after boot)\n",
-                  mMisc2FlagLateBootValue ? "true" : "false",
-                  mMisc2FlagEarlyBootValue == mMisc2FlagLateBootValue ? "stable" : "modified");
-    StringAppendF(&result, "VrrConfigFlagValue: %s\n",
-                  flagutils::vrrConfigEnabled() ? "true" : "false");
-    StringAppendF(&result, "DontSkipOnEarlyFlagValue: %s\n",
-                  flags::dont_skip_on_early() ? "true" : "false");
-
     getRenderEngine().dump(result);
 
     result.append("ClientCache state:\n");
@@ -6562,7 +6538,7 @@
     /*
      * Dump flag/property manager state
      */
-    mFlagManager.dump(result);
+    FlagManager::getInstance().dump(result);
 
     result.append(mTimeStats->miniDump());
     result.append("\n");
@@ -7227,7 +7203,7 @@
             // Second argument is a delay in ms for triggering the jank. This is useful for working
             // with tools that steal the adb connection. This argument is optional.
             case 1045: {
-                if (flagutils::vrrConfigEnabled()) {
+                if (FlagManager::getInstance().vrr_config()) {
                     float jankAmount = data.readFloat();
                     int32_t jankDelayMs = 0;
                     if (data.readInt32(&jankDelayMs) != NO_ERROR) {
@@ -9078,7 +9054,7 @@
     const sp<Client> client = sp<Client>::make(mFlinger);
     if (client->initCheck() == NO_ERROR) {
         *outClient = client;
-        if (flags::misc1()) {
+        if (FlagManager::getInstance().misc1()) {
             const int policy = SCHED_FIFO;
             client->setMinSchedulerPolicy(policy, sched_get_priority_min(policy));
         }
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 96b67b8..520bd22 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -1421,8 +1421,6 @@
 
     const sp<WindowInfosListenerInvoker> mWindowInfosListenerInvoker;
 
-    FlagManager mFlagManager;
-
     // returns the framerate of the layer with the given sequence ID
     float getLayerFramerate(nsecs_t now, int32_t id) const {
         return mScheduler->getLayerFramerate(now, id);
@@ -1459,12 +1457,6 @@
     void sfdo_setDebugFlash(int delay);
     void sfdo_scheduleComposite();
     void sfdo_scheduleCommit();
-
-    // Trunk-Stable flags
-    bool mMiscFlagValue;
-    bool mConnectedDisplayFlagValue;
-    bool mMisc2FlagEarlyBootValue;
-    bool mMisc2FlagLateBootValue;
 };
 
 class SurfaceComposerAIDL : public gui::BnSurfaceComposer {
diff --git a/services/surfaceflinger/Utils/FlagUtils.h b/services/surfaceflinger/Utils/FlagUtils.h
deleted file mode 100644
index 8435f04..0000000
--- a/services/surfaceflinger/Utils/FlagUtils.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Copyright 2023 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.
- */
-
-#pragma once
-
-#include <android-base/properties.h>
-#include <com_android_graphics_surfaceflinger_flags.h>
-#include <string>
-
-namespace android::flagutils {
-
-using namespace std::literals::string_literals;
-using namespace com::android::graphics::surfaceflinger;
-
-inline bool vrrConfigEnabled() {
-    static const bool enable_vrr_config =
-            base::GetBoolProperty("debug.sf.enable_vrr_config"s, false);
-    return flags::vrr_config() || enable_vrr_config;
-}
-} // namespace android::flagutils
diff --git a/services/surfaceflinger/main_surfaceflinger.cpp b/services/surfaceflinger/main_surfaceflinger.cpp
index 9599452..9889cb9 100644
--- a/services/surfaceflinger/main_surfaceflinger.cpp
+++ b/services/surfaceflinger/main_surfaceflinger.cpp
@@ -34,6 +34,7 @@
 #include <errno.h>
 #include <hidl/LegacySupport.h>
 #include <processgroup/sched_policy.h>
+#include "FlagManager.h"
 #include "SurfaceFlinger.h"
 #include "SurfaceFlingerFactory.h"
 #include "SurfaceFlingerProperties.h"
@@ -149,7 +150,7 @@
 
     // publish gui::ISurfaceComposer, the new AIDL interface
     sp<SurfaceComposerAIDL> composerAIDL = sp<SurfaceComposerAIDL>::make(flinger);
-    if (flags::misc1()) {
+    if (FlagManager::getInstance().misc1()) {
         composerAIDL->setMinSchedulerPolicy(SCHED_FIFO, newPriority);
     }
     sm->addService(String16("SurfaceFlingerAIDL"), composerAIDL, false,
diff --git a/services/surfaceflinger/tests/unittests/FlagManagerTest.cpp b/services/surfaceflinger/tests/unittests/FlagManagerTest.cpp
index 0905cd1..aa37754 100644
--- a/services/surfaceflinger/tests/unittests/FlagManagerTest.cpp
+++ b/services/surfaceflinger/tests/unittests/FlagManagerTest.cpp
@@ -14,130 +14,153 @@
  * limitations under the License.
  */
 
-#include <cstdint>
 #undef LOG_TAG
 #define LOG_TAG "FlagManagerTest"
 
 #include "FlagManager.h"
+#include "FlagUtils.h"
 
-#include <android-base/properties.h>
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
 #include <log/log.h>
-#include <server_configurable_flags/get_flags.h>
-#include <optional>
+
+#include <com_android_graphics_surfaceflinger_flags.h>
 
 namespace android {
 
 using testing::Return;
 
-class MockFlagManager : public FlagManager {
+class TestableFlagManager : public FlagManager {
 public:
-    MockFlagManager() = default;
-    ~MockFlagManager() = default;
+    TestableFlagManager() : FlagManager(ConstructorTag{}) { markBootCompleted(); }
+    ~TestableFlagManager() = default;
 
-    MOCK_METHOD(std::string, getServerConfigurableFlag, (const std::string& experimentFlagName),
-                (const, override));
+    MOCK_METHOD(std::optional<bool>, getBoolProperty, (const char*), (const, override));
+    MOCK_METHOD(bool, getServerConfigurableFlag, (const char*), (const, override));
+
+    void markBootIncomplete() { mBootCompleted = false; }
 };
 
 class FlagManagerTest : public testing::Test {
 public:
-    FlagManagerTest();
-    ~FlagManagerTest() override;
-    std::unique_ptr<MockFlagManager> mFlagManager;
+    FlagManagerTest() {
+        const ::testing::TestInfo* const test_info =
+                ::testing::UnitTest::GetInstance()->current_test_info();
+        ALOGD("**** Setting up for %s.%s\n", test_info->test_case_name(), test_info->name());
+    }
+    ~FlagManagerTest() override {
+        const ::testing::TestInfo* const test_info =
+                ::testing::UnitTest::GetInstance()->current_test_info();
+        ALOGD("**** Tearing down after %s.%s\n", test_info->test_case_name(), test_info->name());
+    }
 
-    template <typename T>
-    T getValue(const std::string& experimentFlagName, std::optional<T> systemPropertyOpt,
-               T defaultValue);
+    TestableFlagManager mFlagManager;
 };
 
-FlagManagerTest::FlagManagerTest() {
-    const ::testing::TestInfo* const test_info =
-            ::testing::UnitTest::GetInstance()->current_test_info();
-    ALOGD("**** Setting up for %s.%s\n", test_info->test_case_name(), test_info->name());
-    mFlagManager = std::make_unique<MockFlagManager>();
+TEST_F(FlagManagerTest, isSingleton) {
+    EXPECT_EQ(&FlagManager::getInstance(), &FlagManager::getInstance());
 }
 
-FlagManagerTest::~FlagManagerTest() {
-    const ::testing::TestInfo* const test_info =
-            ::testing::UnitTest::GetInstance()->current_test_info();
-    ALOGD("**** Tearing down after %s.%s\n", test_info->test_case_name(), test_info->name());
+TEST_F(FlagManagerTest, legacyCreashesIfQueriedBeforeBoot) {
+    mFlagManager.markBootIncomplete();
+    EXPECT_DEATH(FlagManager::getInstance().test_flag(), "");
 }
 
-template <typename T>
-T FlagManagerTest::getValue(const std::string& experimentFlagName,
-                            std::optional<T> systemPropertyOpt, T defaultValue) {
-    return mFlagManager->getValue(experimentFlagName, systemPropertyOpt, defaultValue);
+TEST_F(FlagManagerTest, legacyReturnsOverride) {
+    EXPECT_CALL(mFlagManager, getBoolProperty).WillOnce(Return(true));
+    EXPECT_EQ(true, mFlagManager.test_flag());
+
+    EXPECT_CALL(mFlagManager, getBoolProperty).WillOnce(Return(false));
+    EXPECT_EQ(false, mFlagManager.test_flag());
 }
 
-namespace {
-TEST_F(FlagManagerTest, getValue_bool_default) {
-    EXPECT_CALL(*mFlagManager, getServerConfigurableFlag).Times(1).WillOnce(Return(""));
-    const bool defaultValue = false;
-    std::optional<bool> systemPropertyValue = std::nullopt;
-    const bool result = FlagManagerTest::getValue("test_flag", systemPropertyValue, defaultValue);
-    ASSERT_EQ(result, defaultValue);
+TEST_F(FlagManagerTest, legacyReturnsValue) {
+    EXPECT_CALL(mFlagManager, getBoolProperty).WillRepeatedly(Return(std::nullopt));
+
+    EXPECT_CALL(mFlagManager, getServerConfigurableFlag).WillOnce(Return(true));
+    EXPECT_EQ(true, mFlagManager.test_flag());
+
+    EXPECT_CALL(mFlagManager, getServerConfigurableFlag).WillOnce(Return(false));
+    EXPECT_EQ(false, mFlagManager.test_flag());
 }
 
-TEST_F(FlagManagerTest, getValue_bool_sysprop) {
-    const bool defaultValue = false;
-    std::optional<bool> systemPropertyValue = std::make_optional(true);
-    const bool result = FlagManagerTest::getValue("test_flag", systemPropertyValue, defaultValue);
-    ASSERT_EQ(result, true);
+TEST_F(FlagManagerTest, creashesIfQueriedBeforeBoot) {
+    mFlagManager.markBootIncomplete();
+    EXPECT_DEATH(FlagManager::getInstance().late_boot_misc2(), "");
 }
 
-TEST_F(FlagManagerTest, getValue_bool_experiment) {
-    EXPECT_CALL(*mFlagManager, getServerConfigurableFlag).Times(1).WillOnce(Return("1"));
-    const bool defaultValue = false;
-    std::optional<bool> systemPropertyValue = std::nullopt;
-    const bool result = FlagManagerTest::getValue("test_flag", systemPropertyValue, defaultValue);
-    ASSERT_EQ(result, true);
+TEST_F(FlagManagerTest, returnsOverride) {
+    mFlagManager.setUnitTestMode();
+
+    // Twice, since the first call is to initialize the static variable
+    EXPECT_CALL(mFlagManager, getBoolProperty)
+            .Times((2))
+            .WillOnce(Return(true))
+            .WillOnce(Return(true));
+    EXPECT_EQ(true, mFlagManager.late_boot_misc2());
+
+    EXPECT_CALL(mFlagManager, getBoolProperty).WillOnce(Return(false));
+    EXPECT_EQ(false, mFlagManager.late_boot_misc2());
 }
 
-TEST_F(FlagManagerTest, getValue_int32_default) {
-    EXPECT_CALL(*mFlagManager, getServerConfigurableFlag).Times(1).WillOnce(Return(""));
-    int32_t defaultValue = 30;
-    std::optional<int32_t> systemPropertyValue = std::nullopt;
-    int32_t result = FlagManagerTest::getValue("test_flag", systemPropertyValue, defaultValue);
-    ASSERT_EQ(result, defaultValue);
+TEST_F(FlagManagerTest, returnsValue) {
+    mFlagManager.setUnitTestMode();
+
+    EXPECT_CALL(mFlagManager, getBoolProperty).WillRepeatedly(Return(std::nullopt));
+
+    {
+        SET_FLAG_FOR_TEST(com::android::graphics::surfaceflinger::flags::late_boot_misc2, true);
+        EXPECT_EQ(true, mFlagManager.late_boot_misc2());
+    }
+
+    {
+        SET_FLAG_FOR_TEST(com::android::graphics::surfaceflinger::flags::late_boot_misc2, false);
+        EXPECT_EQ(false, mFlagManager.late_boot_misc2());
+    }
 }
 
-TEST_F(FlagManagerTest, getValue_int32_sysprop) {
-    int32_t defaultValue = 30;
-    std::optional<int32_t> systemPropertyValue = std::make_optional(10);
-    int32_t result = FlagManagerTest::getValue("test_flag", systemPropertyValue, defaultValue);
-    ASSERT_EQ(result, 10);
+TEST_F(FlagManagerTest, readonlyReturnsOverride) {
+    mFlagManager.setUnitTestMode();
+
+    // Twice, since the first call is to initialize the static variable
+    EXPECT_CALL(mFlagManager, getBoolProperty)
+            .Times(2)
+            .WillOnce(Return(true))
+            .WillOnce(Return(true));
+    EXPECT_EQ(true, mFlagManager.misc1());
+
+    EXPECT_CALL(mFlagManager, getBoolProperty).WillOnce(Return(false));
+    EXPECT_EQ(false, mFlagManager.misc1());
 }
 
-TEST_F(FlagManagerTest, getValue_int32_experiment) {
-    EXPECT_CALL(*mFlagManager, getServerConfigurableFlag).Times(1).WillOnce(Return("50"));
-    std::int32_t defaultValue = 30;
-    std::optional<std::int32_t> systemPropertyValue = std::nullopt;
-    std::int32_t result = FlagManagerTest::getValue("test_flag", systemPropertyValue, defaultValue);
-    ASSERT_EQ(result, 50);
+TEST_F(FlagManagerTest, readonlyReturnsValue) {
+    mFlagManager.setUnitTestMode();
+
+    EXPECT_CALL(mFlagManager, getBoolProperty).WillRepeatedly(Return(std::nullopt));
+
+    {
+        SET_FLAG_FOR_TEST(com::android::graphics::surfaceflinger::flags::misc1, true);
+        EXPECT_EQ(true, mFlagManager.misc1());
+    }
+
+    {
+        SET_FLAG_FOR_TEST(com::android::graphics::surfaceflinger::flags::misc1, false);
+        EXPECT_EQ(false, mFlagManager.misc1());
+    }
 }
 
-TEST_F(FlagManagerTest, getValue_int64_default) {
-    EXPECT_CALL(*mFlagManager, getServerConfigurableFlag).Times(1).WillOnce(Return(""));
-    int64_t defaultValue = 30;
-    std::optional<int64_t> systemPropertyValue = std::nullopt;
-    int64_t result = getValue("flag_name", systemPropertyValue, defaultValue);
-    ASSERT_EQ(result, defaultValue);
+TEST_F(FlagManagerTest, dontSkipOnEarlyIsNotCached) {
+    EXPECT_CALL(mFlagManager, getBoolProperty).WillRepeatedly(Return(std::nullopt));
+
+    const auto initialValue = com::android::graphics::surfaceflinger::flags::dont_skip_on_early();
+
+    com::android::graphics::surfaceflinger::flags::dont_skip_on_early(true);
+    EXPECT_EQ(true, mFlagManager.dont_skip_on_early());
+
+    com::android::graphics::surfaceflinger::flags::dont_skip_on_early(false);
+    EXPECT_EQ(false, mFlagManager.dont_skip_on_early());
+
+    com::android::graphics::surfaceflinger::flags::dont_skip_on_early(initialValue);
 }
 
-TEST_F(FlagManagerTest, getValue_int64_sysprop) {
-    int64_t defaultValue = 30;
-    std::optional<int64_t> systemPropertyValue = std::make_optional(10);
-    int64_t result = getValue("flag_name", systemPropertyValue, defaultValue);
-    ASSERT_EQ(result, 10);
-}
-
-TEST_F(FlagManagerTest, getValue_int64_experiment) {
-    EXPECT_CALL(*mFlagManager, getServerConfigurableFlag).Times(1).WillOnce(Return("50"));
-    int64_t defaultValue = 30;
-    std::optional<int64_t> systemPropertyValue = std::nullopt;
-    int64_t result = getValue("flag_name", systemPropertyValue, defaultValue);
-    ASSERT_EQ(result, 50);
-}
-} // namespace
 } // namespace android
diff --git a/services/surfaceflinger/tests/unittests/FlagUtils.h b/services/surfaceflinger/tests/unittests/FlagUtils.h
index 7103684..333e4e7 100644
--- a/services/surfaceflinger/tests/unittests/FlagUtils.h
+++ b/services/surfaceflinger/tests/unittests/FlagUtils.h
@@ -16,12 +16,16 @@
 
 #pragma once
 
+#include "FlagManager.h"
+
 #define SET_FLAG_FOR_TEST(name, value) TestFlagSetter _testflag_((name), (name), (value))
 
 namespace android {
 class TestFlagSetter {
 public:
     TestFlagSetter(bool (*getter)(), void((*setter)(bool)), bool flagValue) {
+        FlagManager::getMutableInstance().setUnitTestMode();
+
         const bool initialValue = getter();
         setter(flagValue);
         mResetFlagValue = [=] { setter(initialValue); };