SurfaceFlinger: Get rid of String8 in dumpsys

Test: build and gui/ui/renderengine/surfaceflinger tests and compare
dumpsys SurfaceFlinger results
Change-Id: Iafdaf73a0acbbbb8fbafc930ad86285106a07e13
diff --git a/services/surfaceflinger/Colorizer.h b/services/surfaceflinger/Colorizer.h
index d56b1c8..b7d61ce 100644
--- a/services/surfaceflinger/Colorizer.h
+++ b/services/surfaceflinger/Colorizer.h
@@ -17,7 +17,7 @@
 #ifndef ANDROID_SURFACE_FLINGER_COLORIZER_H
 #define ANDROID_SURFACE_FLINGER_COLORIZER_H
 
-#include <utils/String8.h>
+#include <android-base/stringprintf.h>
 
 namespace android {
 
@@ -40,19 +40,19 @@
         : mEnabled(enabled) {
     }
 
-    void colorize(String8& out, color c) {
+    void colorize(std::string& out, color c) {
         if (mEnabled) {
-            out.appendFormat("\e[%dm", c);
+            base::StringAppendF(&out, "\e[%dm", c);
         }
     }
 
-    void bold(String8& out) {
+    void bold(std::string& out) {
         if (mEnabled) {
             out.append("\e[1m");
         }
     }
 
-    void reset(String8& out) {
+    void reset(std::string& out) {
         if (mEnabled) {
             out.append("\e[0m");
         }
diff --git a/services/surfaceflinger/DisplayDevice.cpp b/services/surfaceflinger/DisplayDevice.cpp
index 1215bd9..b83b84a 100644
--- a/services/surfaceflinger/DisplayDevice.cpp
+++ b/services/surfaceflinger/DisplayDevice.cpp
@@ -54,6 +54,7 @@
 // retrieve triple buffer setting from configstore
 using namespace android::hardware::configstore;
 using namespace android::hardware::configstore::V1_0;
+using android::base::StringAppendF;
 using android::ui::ColorMode;
 using android::ui::Dataspace;
 using android::ui::Hdr;
@@ -715,33 +716,33 @@
                               mDisplayName.c_str());
 }
 
-void DisplayDevice::dump(String8& result) const {
+void DisplayDevice::dump(std::string& result) const {
     const ui::Transform& tr(mGlobalTransform);
     ANativeWindow* const window = mNativeWindow.get();
-    result.appendFormat("+ %s\n", getDebugName().c_str());
-    result.appendFormat("  layerStack=%u, (%4dx%4d), ANativeWindow=%p "
-                        "format=%d, orient=%2d (type=%08x), flips=%u, isSecure=%d, "
-                        "powerMode=%d, activeConfig=%d, numLayers=%zu\n",
-                        mLayerStack, mDisplayWidth, mDisplayHeight, window,
-                        ANativeWindow_getFormat(window), mOrientation, tr.getType(),
-                        getPageFlipCount(), mIsSecure, mPowerMode, mActiveConfig,
-                        mVisibleLayersSortedByZ.size());
-    result.appendFormat("   v:[%d,%d,%d,%d], f:[%d,%d,%d,%d], s:[%d,%d,%d,%d],"
-                        "transform:[[%0.3f,%0.3f,%0.3f][%0.3f,%0.3f,%0.3f][%0.3f,%0.3f,%0.3f]]\n",
-                        mViewport.left, mViewport.top, mViewport.right, mViewport.bottom,
-                        mFrame.left, mFrame.top, mFrame.right, mFrame.bottom, mScissor.left,
-                        mScissor.top, mScissor.right, mScissor.bottom, tr[0][0], tr[1][0], tr[2][0],
-                        tr[0][1], tr[1][1], tr[2][1], tr[0][2], tr[1][2], tr[2][2]);
+    StringAppendF(&result, "+ %s\n", getDebugName().c_str());
+    StringAppendF(&result,
+                  "  layerStack=%u, (%4dx%4d), ANativeWindow=%p "
+                  "format=%d, orient=%2d (type=%08x), flips=%u, isSecure=%d, "
+                  "powerMode=%d, activeConfig=%d, numLayers=%zu\n",
+                  mLayerStack, mDisplayWidth, mDisplayHeight, window,
+                  ANativeWindow_getFormat(window), mOrientation, tr.getType(), getPageFlipCount(),
+                  mIsSecure, mPowerMode, mActiveConfig, mVisibleLayersSortedByZ.size());
+    StringAppendF(&result,
+                  "   v:[%d,%d,%d,%d], f:[%d,%d,%d,%d], s:[%d,%d,%d,%d],"
+                  "transform:[[%0.3f,%0.3f,%0.3f][%0.3f,%0.3f,%0.3f][%0.3f,%0.3f,%0.3f]]\n",
+                  mViewport.left, mViewport.top, mViewport.right, mViewport.bottom, mFrame.left,
+                  mFrame.top, mFrame.right, mFrame.bottom, mScissor.left, mScissor.top,
+                  mScissor.right, mScissor.bottom, tr[0][0], tr[1][0], tr[2][0], tr[0][1], tr[1][1],
+                  tr[2][1], tr[0][2], tr[1][2], tr[2][2]);
     auto const surface = static_cast<Surface*>(window);
     ui::Dataspace dataspace = surface->getBuffersDataSpace();
-    result.appendFormat("   wideColorGamut=%d, hdr10=%d, colorMode=%s, dataspace: %s (%d)\n",
-                        mHasWideColorGamut, mHasHdr10, decodeColorMode(mActiveColorMode).c_str(),
-                        dataspaceDetails(static_cast<android_dataspace>(dataspace)).c_str(),
-                        dataspace);
+    StringAppendF(&result, "   wideColorGamut=%d, hdr10=%d, colorMode=%s, dataspace: %s (%d)\n",
+                  mHasWideColorGamut, mHasHdr10, decodeColorMode(mActiveColorMode).c_str(),
+                  dataspaceDetails(static_cast<android_dataspace>(dataspace)).c_str(), dataspace);
 
     String8 surfaceDump;
     mDisplaySurface->dumpAsString(surfaceDump);
-    result.append(surfaceDump);
+    result.append(surfaceDump.string(), surfaceDump.size());
 }
 
 // Map dataspace/intent to the best matched dataspace/colorMode/renderIntent
diff --git a/services/surfaceflinger/DisplayDevice.h b/services/surfaceflinger/DisplayDevice.h
index eb2c5c3..8357228 100644
--- a/services/surfaceflinger/DisplayDevice.h
+++ b/services/surfaceflinger/DisplayDevice.h
@@ -37,7 +37,6 @@
 #include <ui/Transform.h>
 #include <utils/Mutex.h>
 #include <utils/RefBase.h>
-#include <utils/String8.h>
 #include <utils/Timers.h>
 
 #include "DisplayHardware/DisplayIdentification.h"
@@ -201,7 +200,7 @@
      */
     uint32_t getPageFlipCount() const;
     std::string getDebugName() const;
-    void dump(String8& result) const;
+    void dump(std::string& result) const;
 
 private:
     const sp<SurfaceFlinger> mFlinger;
diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.cpp b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
index b27344d..0aa0dfb 100644
--- a/services/surfaceflinger/DisplayHardware/HWComposer.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
@@ -774,11 +774,11 @@
     return getComposer()->isUsingVrComposer();
 }
 
-void HWComposer::dump(String8& result) const {
+void HWComposer::dump(std::string& result) const {
     // TODO: In order to provide a dump equivalent to HWC1, we need to shadow
     // all the state going into the layers. This is probably better done in
     // Layer itself, but it's going to take a bit of work to get there.
-    result.append(mHwcDevice->dump().c_str());
+    result.append(mHwcDevice->dump());
 }
 
 std::optional<DisplayId> HWComposer::toPhysicalDisplayId(hwc2_display_t hwcDisplayId) const {
diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.h b/services/surfaceflinger/DisplayHardware/HWComposer.h
index 3f1328e..aaa6e8c 100644
--- a/services/surfaceflinger/DisplayHardware/HWComposer.h
+++ b/services/surfaceflinger/DisplayHardware/HWComposer.h
@@ -37,7 +37,6 @@
 namespace android {
 
 class GraphicBuffer;
-class String8;
 class TestableSurfaceFlinger;
 struct CompositionInfo;
 
@@ -161,7 +160,7 @@
     bool isUsingVrComposer() const;
 
     // for debugging ----------------------------------------------------------
-    void dump(String8& out) const;
+    void dump(std::string& out) const;
 
     Hwc2::Composer* getComposer() const { return mHwcDevice->getComposer(); }
 
diff --git a/services/surfaceflinger/FrameTracker.cpp b/services/surfaceflinger/FrameTracker.cpp
index 1539873..f4cc49b 100644
--- a/services/surfaceflinger/FrameTracker.cpp
+++ b/services/surfaceflinger/FrameTracker.cpp
@@ -19,6 +19,7 @@
 
 #include <inttypes.h>
 
+#include <android-base/stringprintf.h>
 #include <android/log.h>
 #include <utils/String8.h>
 
@@ -230,17 +231,17 @@
             mFrameRecords[idx].actualPresentTime < INT64_MAX;
 }
 
-void FrameTracker::dumpStats(String8& result) const {
+void FrameTracker::dumpStats(std::string& result) const {
     Mutex::Autolock lock(mMutex);
     processFencesLocked();
 
     const size_t o = mOffset;
     for (size_t i = 1; i < NUM_FRAME_RECORDS; i++) {
         const size_t index = (o+i) % NUM_FRAME_RECORDS;
-        result.appendFormat("%" PRId64 "\t%" PRId64 "\t%" PRId64 "\n",
-            mFrameRecords[index].desiredPresentTime,
-            mFrameRecords[index].actualPresentTime,
-            mFrameRecords[index].frameReadyTime);
+        base::StringAppendF(&result, "%" PRId64 "\t%" PRId64 "\t%" PRId64 "\n",
+                            mFrameRecords[index].desiredPresentTime,
+                            mFrameRecords[index].actualPresentTime,
+                            mFrameRecords[index].frameReadyTime);
     }
     result.append("\n");
 }
diff --git a/services/surfaceflinger/FrameTracker.h b/services/surfaceflinger/FrameTracker.h
index b4a9fd6..555dcc1 100644
--- a/services/surfaceflinger/FrameTracker.h
+++ b/services/surfaceflinger/FrameTracker.h
@@ -90,7 +90,7 @@
     void logAndResetStats(const String8& name);
 
     // dumpStats dump appends the current frame display time history to the result string.
-    void dumpStats(String8& result) const;
+    void dumpStats(std::string& result) const;
 
 private:
     struct FrameRecord {
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index f53ffae..8e7be47 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -25,6 +25,8 @@
 #include <sys/types.h>
 #include <algorithm>
 
+#include <android-base/stringprintf.h>
+
 #include <cutils/compiler.h>
 #include <cutils/native_handle.h>
 #include <cutils/properties.h>
@@ -63,6 +65,8 @@
 
 namespace android {
 
+using base::StringAppendF;
+
 std::atomic<int32_t> Layer::sSequence{1};
 
 Layer::Layer(const LayerCreationArgs& args)
@@ -1399,7 +1403,7 @@
     info.mName = getName();
     sp<Layer> parent = getParent();
     info.mParentName = (parent == nullptr ? std::string("none") : parent->getName().string());
-    info.mType = String8(getTypeId());
+    info.mType = std::string(getTypeId());
     info.mTransparentRegion = ds.activeTransparentRegion_legacy;
     info.mVisibleRegion = visibleRegion;
     info.mSurfaceDamageRegion = surfaceDamageRegion;
@@ -1439,7 +1443,7 @@
     return info;
 }
 
-void Layer::miniDumpHeader(String8& result) {
+void Layer::miniDumpHeader(std::string& result) {
     result.append("-------------------------------");
     result.append("-------------------------------");
     result.append("-----------------------------\n");
@@ -1454,50 +1458,51 @@
     result.append("-----------------------------\n");
 }
 
-void Layer::miniDump(String8& result, DisplayId displayId) const {
+void Layer::miniDump(std::string& result, DisplayId displayId) const {
     if (!hasHwcLayer(displayId)) {
         return;
     }
 
-    String8 name;
+    std::string name;
     if (mName.length() > 77) {
         std::string shortened;
         shortened.append(mName.string(), 36);
         shortened.append("[...]");
         shortened.append(mName.string() + (mName.length() - 36), 36);
-        name = shortened.c_str();
+        name = shortened;
     } else {
-        name = mName;
+        name = std::string(mName.string(), mName.size());
     }
 
-    result.appendFormat(" %s\n", name.string());
+    StringAppendF(&result, " %s\n", name.c_str());
 
     const State& layerState(getDrawingState());
     const LayerBE::HWCInfo& hwcInfo = getBE().mHwcLayers.at(displayId);
     if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
-        result.appendFormat("  rel %6d | ", layerState.z);
+        StringAppendF(&result, "  rel %6d | ", layerState.z);
     } else {
-        result.appendFormat("  %10d | ", layerState.z);
+        StringAppendF(&result, "  %10d | ", layerState.z);
     }
-    result.appendFormat("%10s | ", to_string(getCompositionType(displayId)).c_str());
-    result.appendFormat("%10s | ", to_string(hwcInfo.transform).c_str());
+    StringAppendF(&result, "%10s | ", to_string(getCompositionType(displayId)).c_str());
+    StringAppendF(&result, "%10s | ", to_string(hwcInfo.transform).c_str());
     const Rect& frame = hwcInfo.displayFrame;
-    result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
+    StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
     const FloatRect& crop = hwcInfo.sourceCrop;
-    result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top, crop.right, crop.bottom);
+    StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top, crop.right,
+                  crop.bottom);
 
     result.append("- - - - - - - - - - - - - - - -\n");
 
     std::string compositionInfoStr;
     getBE().compositionInfo.dump(compositionInfoStr, "compositionInfo");
-    result.append(compositionInfoStr.c_str());
+    result.append(compositionInfoStr);
 
     result.append("- - - - - - - - - - - - - - - -");
     result.append("- - - - - - - - - - - - - - - -");
     result.append("- - - - - - - - - - - - - - -\n");
 }
 
-void Layer::dumpFrameStats(String8& result) const {
+void Layer::dumpFrameStats(std::string& result) const {
     mFrameTracker.dumpStats(result);
 }
 
@@ -1513,8 +1518,8 @@
     mFrameTracker.getStats(outStats);
 }
 
-void Layer::dumpFrameEvents(String8& result) {
-    result.appendFormat("- Layer %s (%s, %p)\n", getName().string(), getTypeId(), this);
+void Layer::dumpFrameEvents(std::string& result) {
+    StringAppendF(&result, "- Layer %s (%s, %p)\n", getName().string(), getTypeId(), this);
     Mutex::Autolock lock(mFrameEventHistoryMutex);
     mFrameEventHistory.checkFencesForCompletion();
     mFrameEventHistory.dump(result);
diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h
index 6ea80c7..4d95c40 100644
--- a/services/surfaceflinger/Layer.h
+++ b/services/surfaceflinger/Layer.h
@@ -565,10 +565,10 @@
     LayerDebugInfo getLayerDebugInfo() const;
 
     /* always call base class first */
-    static void miniDumpHeader(String8& result);
-    void miniDump(String8& result, DisplayId displayId) const;
-    void dumpFrameStats(String8& result) const;
-    void dumpFrameEvents(String8& result);
+    static void miniDumpHeader(std::string& result);
+    void miniDump(std::string& result, DisplayId displayId) const;
+    void dumpFrameStats(std::string& result) const;
+    void dumpFrameEvents(std::string& result);
     void clearFrameStats();
     void logFrameStats();
     void getFrameStats(FrameStats* outStats) const;
diff --git a/services/surfaceflinger/LayerBE.cpp b/services/surfaceflinger/LayerBE.cpp
index 70b00dd..e39babe 100644
--- a/services/surfaceflinger/LayerBE.cpp
+++ b/services/surfaceflinger/LayerBE.cpp
@@ -101,15 +101,8 @@
     result += base::StringPrintf("\tsourceCrop=%6.1f %6.1f %6.1f %6.1f\n", hwc.sourceCrop.left,
                                  hwc.sourceCrop.top, hwc.sourceCrop.right, hwc.sourceCrop.bottom);
 
-    {
-        //
-        // Keep a conversion from std::string to String8 and back until Region can use std::string
-        //
-        String8 regionString;
-        hwc.visibleRegion.dump(regionString, "visibleRegion");
-        hwc.surfaceDamage.dump(regionString, "surfaceDamage");
-        result += regionString.string();
-    }
+    hwc.visibleRegion.dump(result, "visibleRegion");
+    hwc.surfaceDamage.dump(result, "surfaceDamage");
 
     result += base::StringPrintf("\tcolor transform matrix:\n"
                                  "\t\t[%f, %f, %f, %f,\n"
diff --git a/services/surfaceflinger/LayerStats.cpp b/services/surfaceflinger/LayerStats.cpp
index c0174ae..a2d1feb 100644
--- a/services/surfaceflinger/LayerStats.cpp
+++ b/services/surfaceflinger/LayerStats.cpp
@@ -23,11 +23,13 @@
 
 #include <android-base/stringprintf.h>
 #include <log/log.h>
-#include <utils/String8.h>
 #include <utils/Trace.h>
 
 namespace android {
 
+using base::StringAppendF;
+using base::StringPrintf;
+
 void LayerStats::enable() {
     ATRACE_CALL();
     std::lock_guard<std::mutex> lock(mMutex);
@@ -64,26 +66,24 @@
         if (!layer) continue;
         traverseLayerTreeStatsLocked(layer->children, layerGlobal, outLayerShapeVec);
         std::string key = "";
-        base::StringAppendF(&key, ",%s", layer->type.c_str());
-        base::StringAppendF(&key, ",%s", layerCompositionType(layer->hwcCompositionType));
-        base::StringAppendF(&key, ",%d", layer->isProtected);
-        base::StringAppendF(&key, ",%s", layerTransform(layer->hwcTransform));
-        base::StringAppendF(&key, ",%s", layerPixelFormat(layer->activeBuffer.format).c_str());
-        base::StringAppendF(&key, ",%s", layer->dataspace.c_str());
-        base::StringAppendF(&key, ",%s",
-                            destinationLocation(layer->hwcFrame.left, layerGlobal.resolution[0],
-                                                true));
-        base::StringAppendF(&key, ",%s",
-                            destinationLocation(layer->hwcFrame.top, layerGlobal.resolution[1],
-                                                false));
-        base::StringAppendF(&key, ",%s",
-                            destinationSize(layer->hwcFrame.right - layer->hwcFrame.left,
-                                            layerGlobal.resolution[0], true));
-        base::StringAppendF(&key, ",%s",
-                            destinationSize(layer->hwcFrame.bottom - layer->hwcFrame.top,
-                                            layerGlobal.resolution[1], false));
-        base::StringAppendF(&key, ",%s", scaleRatioWH(layer).c_str());
-        base::StringAppendF(&key, ",%s", alpha(static_cast<float>(layer->color.a)));
+        StringAppendF(&key, ",%s", layer->type.c_str());
+        StringAppendF(&key, ",%s", layerCompositionType(layer->hwcCompositionType));
+        StringAppendF(&key, ",%d", layer->isProtected);
+        StringAppendF(&key, ",%s", layerTransform(layer->hwcTransform));
+        StringAppendF(&key, ",%s", layerPixelFormat(layer->activeBuffer.format).c_str());
+        StringAppendF(&key, ",%s", layer->dataspace.c_str());
+        StringAppendF(&key, ",%s",
+                      destinationLocation(layer->hwcFrame.left, layerGlobal.resolution[0], true));
+        StringAppendF(&key, ",%s",
+                      destinationLocation(layer->hwcFrame.top, layerGlobal.resolution[1], false));
+        StringAppendF(&key, ",%s",
+                      destinationSize(layer->hwcFrame.right - layer->hwcFrame.left,
+                                      layerGlobal.resolution[0], true));
+        StringAppendF(&key, ",%s",
+                      destinationSize(layer->hwcFrame.bottom - layer->hwcFrame.top,
+                                      layerGlobal.resolution[1], false));
+        StringAppendF(&key, ",%s", scaleRatioWH(layer).c_str());
+        StringAppendF(&key, ",%s", alpha(static_cast<float>(layer->color.a)));
 
         outLayerShapeVec->push_back(key);
         ALOGV("%s", key.c_str());
@@ -101,9 +101,9 @@
     traverseLayerTreeStatsLocked(layerTree.topLevelLayers, layerGlobal, &layerShapeVec);
 
     std::string layerShapeKey =
-            base::StringPrintf("%d,%s,%s,%s", static_cast<int32_t>(layerShapeVec.size()),
-                               layerGlobal.colorMode.c_str(), layerGlobal.colorTransform.c_str(),
-                               layerTransform(layerGlobal.globalTransform));
+            StringPrintf("%d,%s,%s,%s", static_cast<int32_t>(layerShapeVec.size()),
+                         layerGlobal.colorMode.c_str(), layerGlobal.colorTransform.c_str(),
+                         layerTransform(layerGlobal.globalTransform));
     ALOGV("%s", layerShapeKey.c_str());
 
     std::sort(layerShapeVec.begin(), layerShapeVec.end(), std::greater<std::string>());
@@ -114,7 +114,7 @@
     mLayerShapeStatsMap[layerShapeKey]++;
 }
 
-void LayerStats::dump(String8& result) {
+void LayerStats::dump(std::string& result) {
     ATRACE_CALL();
     ALOGD("Dumping");
     std::lock_guard<std::mutex> lock(mMutex);
@@ -122,7 +122,7 @@
     result.append("LayerType,CompositionType,IsProtected,Transform,PixelFormat,Dataspace,");
     result.append("DstX,DstY,DstWidth,DstHeight,WScale,HScale,Alpha\n");
     for (auto& u : mLayerShapeStatsMap) {
-        result.appendFormat("%u,%s\n", u.second, u.first.c_str());
+        StringAppendF(&result, "%u,%s\n", u.second, u.first.c_str());
     }
 }
 
diff --git a/services/surfaceflinger/LayerStats.h b/services/surfaceflinger/LayerStats.h
index 9de9cce..62b2688 100644
--- a/services/surfaceflinger/LayerStats.h
+++ b/services/surfaceflinger/LayerStats.h
@@ -24,7 +24,6 @@
 using namespace android::surfaceflinger;
 
 namespace android {
-class String8;
 
 class LayerStats {
 public:
@@ -33,7 +32,7 @@
     void clear();
     bool isEnabled();
     void logLayerStats(const LayersProto& layersProto);
-    void dump(String8& result);
+    void dump(std::string& result);
 
 private:
     // Traverse layer tree to get all visible layers' stats
diff --git a/services/surfaceflinger/Scheduler/DispSync.cpp b/services/surfaceflinger/Scheduler/DispSync.cpp
index 172c418..b74b901 100644
--- a/services/surfaceflinger/Scheduler/DispSync.cpp
+++ b/services/surfaceflinger/Scheduler/DispSync.cpp
@@ -24,9 +24,9 @@
 
 #include <algorithm>
 
-#include <log/log.h>
+#include <android-base/stringprintf.h>
 #include <cutils/properties.h>
-#include <utils/String8.h>
+#include <log/log.h>
 #include <utils/Thread.h>
 #include <utils/Trace.h>
 
@@ -36,6 +36,7 @@
 #include "EventLog/EventLog.h"
 #include "SurfaceFlinger.h"
 
+using android::base::StringAppendF;
 using std::max;
 using std::min;
 
@@ -667,54 +668,56 @@
     }
 }
 
-void DispSync::dump(String8& result) const {
+void DispSync::dump(std::string& result) const {
     Mutex::Autolock lock(mMutex);
-    result.appendFormat("present fences are %s\n", mIgnorePresentFences ? "ignored" : "used");
-    result.appendFormat("mPeriod: %" PRId64 " ns (%.3f fps; skipCount=%d)\n", mPeriod,
-                        1000000000.0 / mPeriod, mRefreshSkipCount);
-    result.appendFormat("mPhase: %" PRId64 " ns\n", mPhase);
-    result.appendFormat("mError: %" PRId64 " ns (sqrt=%.1f)\n", mError, sqrt(mError));
-    result.appendFormat("mNumResyncSamplesSincePresent: %d (limit %d)\n",
-                        mNumResyncSamplesSincePresent, MAX_RESYNC_SAMPLES_WITHOUT_PRESENT);
-    result.appendFormat("mNumResyncSamples: %zd (max %d)\n", mNumResyncSamples, MAX_RESYNC_SAMPLES);
+    StringAppendF(&result, "present fences are %s\n", mIgnorePresentFences ? "ignored" : "used");
+    StringAppendF(&result, "mPeriod: %" PRId64 " ns (%.3f fps; skipCount=%d)\n", mPeriod,
+                  1000000000.0 / mPeriod, mRefreshSkipCount);
+    StringAppendF(&result, "mPhase: %" PRId64 " ns\n", mPhase);
+    StringAppendF(&result, "mError: %" PRId64 " ns (sqrt=%.1f)\n", mError, sqrt(mError));
+    StringAppendF(&result, "mNumResyncSamplesSincePresent: %d (limit %d)\n",
+                  mNumResyncSamplesSincePresent, MAX_RESYNC_SAMPLES_WITHOUT_PRESENT);
+    StringAppendF(&result, "mNumResyncSamples: %zd (max %d)\n", mNumResyncSamples,
+                  MAX_RESYNC_SAMPLES);
 
-    result.appendFormat("mResyncSamples:\n");
+    result.append("mResyncSamples:\n");
     nsecs_t previous = -1;
     for (size_t i = 0; i < mNumResyncSamples; i++) {
         size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
         nsecs_t sampleTime = mResyncSamples[idx];
         if (i == 0) {
-            result.appendFormat("  %" PRId64 "\n", sampleTime);
+            StringAppendF(&result, "  %" PRId64 "\n", sampleTime);
         } else {
-            result.appendFormat("  %" PRId64 " (+%" PRId64 ")\n", sampleTime,
-                                sampleTime - previous);
+            StringAppendF(&result, "  %" PRId64 " (+%" PRId64 ")\n", sampleTime,
+                          sampleTime - previous);
         }
         previous = sampleTime;
     }
 
-    result.appendFormat("mPresentFences [%d]:\n", NUM_PRESENT_SAMPLES);
+    StringAppendF(&result, "mPresentFences [%d]:\n", NUM_PRESENT_SAMPLES);
     nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
     previous = Fence::SIGNAL_TIME_INVALID;
     for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
         size_t idx = (i + mPresentSampleOffset) % NUM_PRESENT_SAMPLES;
         nsecs_t presentTime = mPresentFences[idx]->getSignalTime();
         if (presentTime == Fence::SIGNAL_TIME_PENDING) {
-            result.appendFormat("  [unsignaled fence]\n");
+            StringAppendF(&result, "  [unsignaled fence]\n");
         } else if (presentTime == Fence::SIGNAL_TIME_INVALID) {
-            result.appendFormat("  [invalid fence]\n");
+            StringAppendF(&result, "  [invalid fence]\n");
         } else if (previous == Fence::SIGNAL_TIME_PENDING ||
                    previous == Fence::SIGNAL_TIME_INVALID) {
-            result.appendFormat("  %" PRId64 "  (%.3f ms ago)\n", presentTime,
-                                (now - presentTime) / 1000000.0);
+            StringAppendF(&result, "  %" PRId64 "  (%.3f ms ago)\n", presentTime,
+                          (now - presentTime) / 1000000.0);
         } else {
-            result.appendFormat("  %" PRId64 " (+%" PRId64 " / %.3f)  (%.3f ms ago)\n", presentTime,
-                                presentTime - previous, (presentTime - previous) / (double)mPeriod,
-                                (now - presentTime) / 1000000.0);
+            StringAppendF(&result, "  %" PRId64 " (+%" PRId64 " / %.3f)  (%.3f ms ago)\n",
+                          presentTime, presentTime - previous,
+                          (presentTime - previous) / (double)mPeriod,
+                          (now - presentTime) / 1000000.0);
         }
         previous = presentTime;
     }
 
-    result.appendFormat("current monotonic time: %" PRId64 "\n", now);
+    StringAppendF(&result, "current monotonic time: %" PRId64 "\n", now);
 }
 
 // TODO(b/113612090): Figure out how much of this is still relevant.
diff --git a/services/surfaceflinger/Scheduler/DispSync.h b/services/surfaceflinger/Scheduler/DispSync.h
index 5d19093..4a90f10 100644
--- a/services/surfaceflinger/Scheduler/DispSync.h
+++ b/services/surfaceflinger/Scheduler/DispSync.h
@@ -29,7 +29,6 @@
 
 namespace android {
 
-class String8;
 class FenceTime;
 
 class DispSync {
@@ -57,7 +56,7 @@
     virtual void setIgnorePresentFences(bool ignore) = 0;
     virtual nsecs_t expectedPresentTime() = 0;
 
-    virtual void dump(String8& result) const = 0;
+    virtual void dump(std::string& result) const = 0;
 };
 
 namespace impl {
@@ -161,7 +160,7 @@
     nsecs_t expectedPresentTime();
 
     // dump appends human-readable debug info to the result string.
-    void dump(String8& result) const override;
+    void dump(std::string& result) const override;
 
 private:
     void updateModelLocked();
diff --git a/services/surfaceflinger/Scheduler/EventThread.cpp b/services/surfaceflinger/Scheduler/EventThread.cpp
index 9bee9a3..49e7ef6 100644
--- a/services/surfaceflinger/Scheduler/EventThread.cpp
+++ b/services/surfaceflinger/Scheduler/EventThread.cpp
@@ -22,18 +22,20 @@
 #include <chrono>
 #include <cstdint>
 
+#include <android-base/stringprintf.h>
+
 #include <cutils/compiler.h>
 #include <cutils/sched_policy.h>
 
 #include <gui/DisplayEventReceiver.h>
 
 #include <utils/Errors.h>
-#include <utils/String8.h>
 #include <utils/Trace.h>
 
 #include "EventThread.h"
 
 using namespace std::chrono_literals;
+using android::base::StringAppendF;
 
 // ---------------------------------------------------------------------------
 
@@ -384,18 +386,18 @@
     }
 }
 
-void EventThread::dump(String8& result) const {
+void EventThread::dump(std::string& result) const {
     std::lock_guard<std::mutex> lock(mMutex);
-    result.appendFormat("VSYNC state: %s\n", mDebugVsyncEnabled ? "enabled" : "disabled");
-    result.appendFormat("  soft-vsync: %s\n", mUseSoftwareVSync ? "enabled" : "disabled");
-    result.appendFormat("  numListeners=%zu,\n  events-delivered: %u\n",
-                        mDisplayEventConnections.size(), mVSyncEvent[0].vsync.count);
+    StringAppendF(&result, "VSYNC state: %s\n", mDebugVsyncEnabled ? "enabled" : "disabled");
+    StringAppendF(&result, "  soft-vsync: %s\n", mUseSoftwareVSync ? "enabled" : "disabled");
+    StringAppendF(&result, "  numListeners=%zu,\n  events-delivered: %u\n",
+                  mDisplayEventConnections.size(), mVSyncEvent[0].vsync.count);
     for (const wp<Connection>& weak : mDisplayEventConnections) {
         sp<Connection> connection = weak.promote();
-        result.appendFormat("    %p: count=%d\n", connection.get(),
-                            connection != nullptr ? connection->count : 0);
+        StringAppendF(&result, "    %p: count=%d\n", connection.get(),
+                      connection != nullptr ? connection->count : 0);
     }
-    result.appendFormat("  other-events-pending: %zu\n", mPendingEvents.size());
+    StringAppendF(&result, "  other-events-pending: %zu\n", mPendingEvents.size());
 }
 
 // ---------------------------------------------------------------------------
diff --git a/services/surfaceflinger/Scheduler/EventThread.h b/services/surfaceflinger/Scheduler/EventThread.h
index 5e7ed13..15b5bba 100644
--- a/services/surfaceflinger/Scheduler/EventThread.h
+++ b/services/surfaceflinger/Scheduler/EventThread.h
@@ -40,7 +40,6 @@
 
 class EventThreadTest;
 class SurfaceFlinger;
-class String8;
 
 // ---------------------------------------------------------------------------
 
@@ -76,7 +75,7 @@
     // called when receiving a hotplug event
     virtual void onHotplugReceived(DisplayType displayType, bool connected) = 0;
 
-    virtual void dump(String8& result) const = 0;
+    virtual void dump(std::string& result) const = 0;
 
     virtual void setPhaseOffset(nsecs_t phaseOffset) = 0;
 };
@@ -131,7 +130,7 @@
     // called when receiving a hotplug event
     void onHotplugReceived(DisplayType displayType, bool connected) override;
 
-    void dump(String8& result) const override;
+    void dump(std::string& result) const override;
 
     void setPhaseOffset(nsecs_t phaseOffset) override;
 
diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp
index 4457f72..5b8cc10 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.cpp
+++ b/services/surfaceflinger/Scheduler/Scheduler.cpp
@@ -133,7 +133,7 @@
     mConnections[handle->id]->thread->onScreenReleased();
 }
 
-void Scheduler::dump(const sp<Scheduler::ConnectionHandle>& handle, String8& result) const {
+void Scheduler::dump(const sp<Scheduler::ConnectionHandle>& handle, std::string& result) const {
     RETURN_IF_INVALID();
     mConnections.at(handle->id)->thread->dump(result);
 }
diff --git a/services/surfaceflinger/Scheduler/Scheduler.h b/services/surfaceflinger/Scheduler/Scheduler.h
index 764ad00..ea90824 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.h
+++ b/services/surfaceflinger/Scheduler/Scheduler.h
@@ -91,7 +91,7 @@
     void onScreenReleased(const sp<ConnectionHandle>& handle);
 
     // Should be called when dumpsys command is received.
-    void dump(const sp<ConnectionHandle>& handle, String8& result) const;
+    void dump(const sp<ConnectionHandle>& handle, std::string& result) const;
 
     // Offers ability to modify phase offset in the event thread.
     void setPhaseOffset(const sp<ConnectionHandle>& handle, nsecs_t phaseOffset);
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 0bda020..8170d4c 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -113,6 +113,7 @@
 
 using namespace android::hardware::configstore;
 using namespace android::hardware::configstore::V1_0;
+using base::StringAppendF;
 using ui::ColorMode;
 using ui::Dataspace;
 using ui::Hdr;
@@ -4094,7 +4095,7 @@
 
 status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
         NO_THREAD_SAFETY_ANALYSIS {
-    String8 result;
+    std::string result;
 
     IPCThreadState* ipc = IPCThreadState::self();
     const int pid = ipc->getCallingPid();
@@ -4102,8 +4103,8 @@
 
     if ((uid != AID_SHELL) &&
             !PermissionCache::checkPermission(sDump, pid, uid)) {
-        result.appendFormat("Permission Denial: "
-                "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
+        StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
+                      pid, uid);
     } else {
         // Try to get the main lock, but give up after one second
         // (this would indicate SF is stuck, but we want to be able to
@@ -4111,9 +4112,10 @@
         status_t err = mStateLock.timedLock(s2ns(1));
         bool locked = (err == NO_ERROR);
         if (!locked) {
-            result.appendFormat(
-                    "SurfaceFlinger appears to be unresponsive (%s [%d]), "
-                    "dumping anyways (no locks held)\n", strerror(-err), err);
+            StringAppendF(&result,
+                          "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
+                          "(no locks held)\n",
+                          strerror(-err), err);
         }
 
         bool dumpAll = true;
@@ -4231,21 +4233,18 @@
             mStateLock.unlock();
         }
     }
-    write(fd, result.string(), result.size());
+    write(fd, result.c_str(), result.size());
     return NO_ERROR;
 }
 
-void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
-        size_t& /* index */, String8& result) const
-{
-    mCurrentState.traverseInZOrder([&](Layer* layer) {
-        result.appendFormat("%s\n", layer->getName().string());
-    });
+void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
+                                      std::string& result) const {
+    mCurrentState.traverseInZOrder(
+            [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
 }
 
 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
-        String8& result) const
-{
+                                     std::string& result) const {
     String8 name;
     if (index < args.size()) {
         name = String8(args[index]);
@@ -4256,7 +4255,7 @@
         displayId && getHwComposer().isConnected(*displayId)) {
         const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
         const nsecs_t period = activeConfig->getVsyncPeriod();
-        result.appendFormat("%" PRId64 "\n", period);
+        StringAppendF(&result, "%" PRId64 "\n", period);
     }
 
     if (name.isEmpty()) {
@@ -4271,8 +4270,7 @@
 }
 
 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
-        String8& /* result */)
-{
+                                      std::string& /* result */) {
     String8 name;
     if (index < args.size()) {
         name = String8(args[index]);
@@ -4298,37 +4296,34 @@
     mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
 }
 
-void SurfaceFlinger::appendSfConfigString(String8& result) const
-{
+void SurfaceFlinger::appendSfConfigString(std::string& result) const {
     result.append(" [sf");
 
     if (isLayerTripleBufferingDisabled())
         result.append(" DISABLE_TRIPLE_BUFFERING");
 
-    result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
-    result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
-    result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
-    result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
-    result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
-                        maxFrameBufferAcquiredBuffers);
+    StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
+    StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
+    StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
+    StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
+    StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
+                  maxFrameBufferAcquiredBuffers);
     result.append("]");
 }
 
-void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
-{
-    result.appendFormat("Static screen stats:\n");
+void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
+    result.append("Static screen stats:\n");
     for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
         float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
         float percent = 100.0f *
                 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
-        result.appendFormat("  < %zd frames: %.3f s (%.1f%%)\n",
-                b + 1, bucketTimeSec, percent);
+        StringAppendF(&result, "  < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
     }
     float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
     float percent = 100.0f *
             static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
-    result.appendFormat("  %zd+ frames: %.3f s (%.1f%%)\n",
-            SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
+    StringAppendF(&result, "  %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
+                  bucketTimeSec, percent);
 }
 
 void SurfaceFlinger::recordBufferingStats(const char* layerName,
@@ -4349,8 +4344,8 @@
     }
 }
 
-void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
-    result.appendFormat("Layer frame timestamps:\n");
+void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
+    result.append("Layer frame timestamps:\n");
 
     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
     const size_t count = currentLayers.size();
@@ -4359,7 +4354,7 @@
     }
 }
 
-void SurfaceFlinger::dumpBufferingStats(String8& result) const {
+void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
     result.append("Buffering stats:\n");
     result.append("  [Layer name] <Active time> <Two buffer> "
             "<Double buffered> <Triple buffered>\n");
@@ -4385,15 +4380,13 @@
     for (const auto& sortedPair : sorted) {
         float activeTime = sortedPair.first;
         const BufferTuple& values = sortedPair.second;
-        result.appendFormat("  [%s] %.2f %.3f %.3f %.3f\n",
-                std::get<0>(values).c_str(), activeTime,
-                std::get<1>(values), std::get<2>(values),
-                std::get<3>(values));
+        StringAppendF(&result, "  [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
+                      activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
     }
     result.append("\n");
 }
 
-void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
+void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
     for (const auto& [token, display] : mDisplays) {
         const auto displayId = display->getId();
         if (!displayId) {
@@ -4404,8 +4397,9 @@
             continue;
         }
 
-        result.appendFormat("Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
-                            *hwcDisplayId);
+        StringAppendF(&result,
+                      "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
+                      *hwcDisplayId);
         uint8_t port;
         DisplayIdentificationData data;
         if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
@@ -4416,7 +4410,7 @@
         if (!isEdid(data)) {
             result.append("unknown identification data: ");
             for (uint8_t byte : data) {
-                result.appendFormat("%x ", byte);
+                StringAppendF(&result, "%x ", byte);
             }
             result.append("\n");
             continue;
@@ -4426,23 +4420,23 @@
         if (!edid) {
             result.append("invalid EDID: ");
             for (uint8_t byte : data) {
-                result.appendFormat("%x ", byte);
+                StringAppendF(&result, "%x ", byte);
             }
             result.append("\n");
             continue;
         }
 
-        result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
+        StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
         result.append(edid->displayName.data(), edid->displayName.length());
         result.append("\"\n");
     }
 }
 
-void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
-    result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
-    result.appendFormat("Device uses color management: %d\n", useColorManagement);
-    result.appendFormat("DisplayColorSetting: %s\n",
-            decodeDisplayColorSetting(mDisplayColorSetting).c_str());
+void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
+    StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
+    StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
+    StringAppendF(&result, "DisplayColorSetting: %s\n",
+                  decodeDisplayColorSetting(mDisplayColorSetting).c_str());
 
     // TODO: print out if wide-color mode is active or not
 
@@ -4452,22 +4446,20 @@
             continue;
         }
 
-        result.appendFormat("Display %s color modes:\n", to_string(*displayId).c_str());
+        StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
         std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
         for (auto&& mode : modes) {
-            result.appendFormat("    %s (%d)\n", decodeColorMode(mode).c_str(), mode);
+            StringAppendF(&result, "    %s (%d)\n", decodeColorMode(mode).c_str(), mode);
         }
 
         ColorMode currentMode = display->getActiveColorMode();
-        result.appendFormat("    Current color mode: %s (%d)\n",
-                            decodeColorMode(currentMode).c_str(), currentMode);
+        StringAppendF(&result, "    Current color mode: %s (%d)\n",
+                      decodeColorMode(currentMode).c_str(), currentMode);
     }
     result.append("\n");
 }
 
-void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
-    std::string stringResult;
-
+void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
     for (const auto& [token, display] : mDisplays) {
         const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
         if (it == getBE().mEndOfFrameCompositionInfo.end()) {
@@ -4475,15 +4467,13 @@
         }
 
         const auto& compositionInfoList = it->second;
-        stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
-        stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
+        StringAppendF(&result, "%s\n", display->getDebugName().c_str());
+        StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
         for (const auto& compositionInfo : compositionInfoList) {
-            compositionInfo.dump(stringResult, nullptr);
-            stringResult += base::StringPrintf("\n");
+            compositionInfo.dump(result, nullptr);
+            result.append("\n");
         }
     }
-
-    result.append(stringResult.c_str());
 }
 
 LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
@@ -4522,8 +4512,7 @@
 }
 
 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
-        String8& result) const
-{
+                                   std::string& result) const {
     bool colorize = false;
     if (index < args.size()
             && (args[index] == String16("--color"))) {
@@ -4571,16 +4560,17 @@
     if (const auto displayId = getInternalDisplayId();
         displayId && getHwComposer().isConnected(*displayId)) {
         const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
-        result.appendFormat("Display %s: app phase %" PRId64 " ns, "
-                            "sf phase %" PRId64 " ns, "
-                            "early app phase %" PRId64 " ns, "
-                            "early sf phase %" PRId64 " ns, "
-                            "early app gl phase %" PRId64 " ns, "
-                            "early sf gl phase %" PRId64 " ns, "
-                            "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
-                            to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
-                            appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
-                            dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
+        StringAppendF(&result,
+                      "Display %s: app phase %" PRId64 " ns, "
+                      "sf phase %" PRId64 " ns, "
+                      "early app phase %" PRId64 " ns, "
+                      "early sf phase %" PRId64 " ns, "
+                      "early app gl phase %" PRId64 " ns, "
+                      "early sf gl phase %" PRId64 " ns, "
+                      "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
+                      to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
+                      appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
+                      dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
     }
     result.append("\n");
 
@@ -4589,7 +4579,7 @@
     dumpStaticScreenStats(result);
     result.append("\n");
 
-    result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
+    StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
 
     dumpBufferingStats(result);
 
@@ -4597,15 +4587,15 @@
      * Dump the visible layer list
      */
     colorizer.bold(result);
-    result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
-    result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
-                        mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
+    StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
+    StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
+                  mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
     colorizer.reset(result);
 
     {
         LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
         auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
-        result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
+        result.append(LayerProtoParser::layerTreeToString(layerTree));
         result.append("\n");
     }
 
@@ -4618,7 +4608,7 @@
      */
 
     colorizer.bold(result);
-    result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
+    StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
     colorizer.reset(result);
     for (const auto& [token, display] : mDisplays) {
         display->dump(result);
@@ -4637,27 +4627,28 @@
 
     if (const auto display = getDefaultDisplayDeviceLocked()) {
         display->undefinedRegion.dump(result, "undefinedRegion");
-        result.appendFormat("  orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
-                            display->isPoweredOn());
+        StringAppendF(&result, "  orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
+                      display->isPoweredOn());
     }
-    result.appendFormat("  transaction-flags         : %08x\n"
-                        "  gpu_to_cpu_unsupported    : %d\n",
-                        mTransactionFlags.load(), !mGpuToCpuSupported);
+    StringAppendF(&result,
+                  "  transaction-flags         : %08x\n"
+                  "  gpu_to_cpu_unsupported    : %d\n",
+                  mTransactionFlags.load(), !mGpuToCpuSupported);
 
     if (const auto displayId = getInternalDisplayId();
         displayId && getHwComposer().isConnected(*displayId)) {
         const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
-        result.appendFormat("  refresh-rate              : %f fps\n"
-                            "  x-dpi                     : %f\n"
-                            "  y-dpi                     : %f\n",
-                            1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
-                            activeConfig->getDpiY());
+        StringAppendF(&result,
+                      "  refresh-rate              : %f fps\n"
+                      "  x-dpi                     : %f\n"
+                      "  y-dpi                     : %f\n",
+                      1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
+                      activeConfig->getDpiY());
     }
 
-    result.appendFormat("  transaction time: %f us\n",
-            inTransactionDuration/1000.0);
+    StringAppendF(&result, "  transaction time: %f us\n", inTransactionDuration / 1000.0);
 
-    result.appendFormat("  use Scheduler: %s\n", mUseScheduler ? "true" : "false");
+    StringAppendF(&result, "  use Scheduler: %s\n", mUseScheduler ? "true" : "false");
     /*
      * VSYNC state
      */
@@ -4683,7 +4674,7 @@
             continue;
         }
 
-        result.appendFormat("Display %s HWC layers:\n", to_string(*displayId).c_str());
+        StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
         Layer::miniDumpHeader(result);
         mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
         result.append("\n");
@@ -4696,8 +4687,7 @@
     result.append("h/w composer state:\n");
     colorizer.reset(result);
     bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
-    result.appendFormat("  h/w composer %s\n",
-            hwcDisabled ? "disabled" : "enabled");
+    StringAppendF(&result, "  h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
     getHwComposer().dump(result);
 
     /*
@@ -4711,7 +4701,7 @@
      */
     if (mVrFlingerRequestsDisplay && mVrFlinger) {
         result.append("VrFlinger state:\n");
-        result.append(mVrFlinger->Dump().c_str());
+        result.append(mVrFlinger->Dump());
         result.append("\n");
     }
 }
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index fe2f1c26..bff847e 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -806,25 +806,25 @@
         return hwcDisplayId ? getHwComposer().toPhysicalDisplayId(*hwcDisplayId) : std::nullopt;
     }
 
-    void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
-    void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
-    void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
-    void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
+    void listLayersLocked(const Vector<String16>& args, size_t& index, std::string& result) const;
+    void dumpStatsLocked(const Vector<String16>& args, size_t& index, std::string& result) const;
+    void clearStatsLocked(const Vector<String16>& args, size_t& index, std::string& result);
+    void dumpAllLocked(const Vector<String16>& args, size_t& index, std::string& result) const;
     bool startDdmConnection();
-    void appendSfConfigString(String8& result) const;
+    void appendSfConfigString(std::string& result) const;
 
     void logFrameStats();
 
-    void dumpStaticScreenStats(String8& result) const;
+    void dumpStaticScreenStats(std::string& result) const;
     // Not const because each Layer needs to query Fences and cache timestamps.
-    void dumpFrameEventsLocked(String8& result);
+    void dumpFrameEventsLocked(std::string& result);
 
     void recordBufferingStats(const char* layerName,
             std::vector<OccupancyTracker::Segment>&& history);
-    void dumpBufferingStats(String8& result) const;
-    void dumpDisplayIdentificationData(String8& result) const;
-    void dumpWideColorInfo(String8& result) const;
-    void dumpFrameCompositionInfo(String8& result) const;
+    void dumpBufferingStats(std::string& result) const;
+    void dumpDisplayIdentificationData(std::string& result) const;
+    void dumpWideColorInfo(std::string& result) const;
+    void dumpFrameCompositionInfo(std::string& result) const;
     LayersProto dumpProtoInfo(LayerVector::StateSet stateSet) const;
     LayersProto dumpVisibleLayersProtoInfo(const DisplayDevice& display) const;
 
diff --git a/services/surfaceflinger/SurfaceTracing.cpp b/services/surfaceflinger/SurfaceTracing.cpp
index 1835929..b7e9a91 100644
--- a/services/surfaceflinger/SurfaceTracing.cpp
+++ b/services/surfaceflinger/SurfaceTracing.cpp
@@ -20,6 +20,7 @@
 #include "SurfaceTracing.h"
 
 #include <android-base/file.h>
+#include <android-base/stringprintf.h>
 #include <log/log.h>
 #include <utils/SystemClock.h>
 #include <utils/Trace.h>
@@ -120,12 +121,13 @@
     return NO_ERROR;
 }
 
-void SurfaceTracing::dump(String8& result) const {
+void SurfaceTracing::dump(std::string& result) const {
     std::lock_guard<std::mutex> protoGuard(mTraceMutex);
 
-    result.appendFormat("Tracing state: %s\n", mEnabled ? "enabled" : "disabled");
-    result.appendFormat("  number of entries: %zu (%.2fMB / %.2fMB)\n", mBuffer.frameCount(),
-                        float(mBuffer.used()) / float(1_MB), float(mBuffer.size()) / float(1_MB));
+    base::StringAppendF(&result, "Tracing state: %s\n", mEnabled ? "enabled" : "disabled");
+    base::StringAppendF(&result, "  number of entries: %zu (%.2fMB / %.2fMB)\n",
+                        mBuffer.frameCount(), float(mBuffer.used()) / float(1_MB),
+                        float(mBuffer.size()) / float(1_MB));
 }
 
 } // namespace android
diff --git a/services/surfaceflinger/SurfaceTracing.h b/services/surfaceflinger/SurfaceTracing.h
index ec01be7..fd919af 100644
--- a/services/surfaceflinger/SurfaceTracing.h
+++ b/services/surfaceflinger/SurfaceTracing.h
@@ -18,7 +18,6 @@
 
 #include <layerproto/LayerProtoHeader.h>
 #include <utils/Errors.h>
-#include <utils/String8.h>
 
 #include <memory>
 #include <mutex>
@@ -43,7 +42,7 @@
     void traceLayers(const char* where, LayersProto);
 
     bool isEnabled() const;
-    void dump(String8& result) const;
+    void dump(std::string& result) const;
 
 private:
     static constexpr auto kDefaultBufferCapInByte = 100_MB;
diff --git a/services/surfaceflinger/TimeStats/TimeStats.cpp b/services/surfaceflinger/TimeStats/TimeStats.cpp
index 2b9f5c8..6a5488a 100644
--- a/services/surfaceflinger/TimeStats/TimeStats.cpp
+++ b/services/surfaceflinger/TimeStats/TimeStats.cpp
@@ -33,7 +33,7 @@
 namespace android {
 
 void TimeStats::parseArgs(bool asProto, const Vector<String16>& args, size_t& index,
-                          String8& result) {
+                          std::string& result) {
     ATRACE_CALL();
 
     if (args.size() > index + 10) {
@@ -564,7 +564,7 @@
     return mEnabled.load();
 }
 
-void TimeStats::dump(bool asProto, std::optional<uint32_t> maxLayers, String8& result) {
+void TimeStats::dump(bool asProto, std::optional<uint32_t> maxLayers, std::string& result) {
     ATRACE_CALL();
 
     std::lock_guard<std::mutex> lock(mMutex);
@@ -582,7 +582,7 @@
         result.append(timeStatsProto.SerializeAsString().c_str(), timeStatsProto.ByteSize());
     } else {
         ALOGD("Dumping TimeStats as text");
-        result.append(mTimeStats.toString(maxLayers).c_str());
+        result.append(mTimeStats.toString(maxLayers));
         result.append("\n");
     }
 }
diff --git a/services/surfaceflinger/TimeStats/TimeStats.h b/services/surfaceflinger/TimeStats/TimeStats.h
index 0b24c46..71c3ed7 100644
--- a/services/surfaceflinger/TimeStats/TimeStats.h
+++ b/services/surfaceflinger/TimeStats/TimeStats.h
@@ -24,7 +24,6 @@
 #include <ui/FenceTime.h>
 
 #include <utils/String16.h>
-#include <utils/String8.h>
 #include <utils/Vector.h>
 
 #include <deque>
@@ -35,7 +34,6 @@
 using namespace android::surfaceflinger;
 
 namespace android {
-class String8;
 
 class TimeStats {
     struct FrameTime {
@@ -79,7 +77,7 @@
     TimeStats() = default;
     ~TimeStats() = default;
 
-    void parseArgs(bool asProto, const Vector<String16>& args, size_t& index, String8& result);
+    void parseArgs(bool asProto, const Vector<String16>& args, size_t& index, std::string& result);
     bool isEnabled();
 
     void incrementTotalFrames();
@@ -117,7 +115,7 @@
     void enable();
     void disable();
     void clear();
-    void dump(bool asProto, std::optional<uint32_t> maxLayers, String8& result);
+    void dump(bool asProto, std::optional<uint32_t> maxLayers, std::string& result);
 
     std::atomic<bool> mEnabled = false;
     std::mutex mMutex;
diff --git a/services/surfaceflinger/tests/unittests/SchedulerTest.cpp b/services/surfaceflinger/tests/unittests/SchedulerTest.cpp
index d0cf1b7..35f30d7 100644
--- a/services/surfaceflinger/tests/unittests/SchedulerTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SchedulerTest.cpp
@@ -117,7 +117,7 @@
             mScheduler->hotplugReceived(nullptr, EventThread::DisplayType::Primary, false));
     ASSERT_NO_FATAL_FAILURE(mScheduler->onScreenAcquired(nullptr));
     ASSERT_NO_FATAL_FAILURE(mScheduler->onScreenReleased(nullptr));
-    String8 testString;
+    std::string testString;
     ASSERT_NO_FATAL_FAILURE(mScheduler->dump(nullptr, testString));
     EXPECT_TRUE(testString == "");
     ASSERT_NO_FATAL_FAILURE(mScheduler->setPhaseOffset(nullptr, 10));
@@ -146,7 +146,7 @@
     EXPECT_CALL(*mEventThread, onScreenReleased()).Times(0);
     ASSERT_NO_FATAL_FAILURE(mScheduler->onScreenReleased(connectionHandle));
 
-    String8 testString;
+    std::string testString;
     EXPECT_CALL(*mEventThread, dump(_)).Times(0);
     ASSERT_NO_FATAL_FAILURE(mScheduler->dump(connectionHandle, testString));
     EXPECT_TRUE(testString == "");
@@ -176,7 +176,7 @@
     EXPECT_CALL(*mEventThread, onScreenReleased()).Times(1);
     ASSERT_NO_FATAL_FAILURE(mScheduler->onScreenReleased(mConnectionHandle));
 
-    String8 testString("dump");
+    std::string testString("dump");
     EXPECT_CALL(*mEventThread, dump(testString)).Times(1);
     ASSERT_NO_FATAL_FAILURE(mScheduler->dump(mConnectionHandle, testString));
     EXPECT_TRUE(testString != "");
diff --git a/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp b/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp
index 186ed79..bfd34cd 100644
--- a/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp
@@ -21,7 +21,6 @@
 
 #include <log/log.h>
 #include <utils/String16.h>
-#include <utils/String8.h>
 #include <utils/Vector.h>
 
 #include <random>
@@ -131,7 +130,7 @@
 
 std::string TimeStatsTest::inputCommand(InputCommand cmd, bool useProto) {
     size_t index = 0;
-    String8 result;
+    std::string result;
     Vector<String16> args;
 
     switch (cmd) {
@@ -162,7 +161,7 @@
     }
 
     EXPECT_NO_FATAL_FAILURE(mTimeStats->parseArgs(useProto, args, index, result));
-    return std::string(result.string(), result.size());
+    return result;
 }
 
 static std::string genLayerName(int32_t layerID) {
diff --git a/services/surfaceflinger/tests/unittests/mock/MockDispSync.h b/services/surfaceflinger/tests/unittests/mock/MockDispSync.h
index 34e71cb..9213ae5 100644
--- a/services/surfaceflinger/tests/unittests/mock/MockDispSync.h
+++ b/services/surfaceflinger/tests/unittests/mock/MockDispSync.h
@@ -18,7 +18,6 @@
 
 #include <gmock/gmock.h>
 
-#include <utils/String8.h>
 #include "Scheduler/DispSync.h"
 
 namespace android {
@@ -44,7 +43,7 @@
     MOCK_METHOD1(setIgnorePresentFences, void(bool));
     MOCK_METHOD0(expectedPresentTime, nsecs_t());
 
-    MOCK_CONST_METHOD1(dump, void(String8&));
+    MOCK_CONST_METHOD1(dump, void(std::string&));
 };
 
 } // namespace mock
diff --git a/services/surfaceflinger/tests/unittests/mock/MockEventThread.h b/services/surfaceflinger/tests/unittests/mock/MockEventThread.h
index ad2463d..0a1c827 100644
--- a/services/surfaceflinger/tests/unittests/mock/MockEventThread.h
+++ b/services/surfaceflinger/tests/unittests/mock/MockEventThread.h
@@ -32,7 +32,7 @@
     MOCK_METHOD0(onScreenReleased, void());
     MOCK_METHOD0(onScreenAcquired, void());
     MOCK_METHOD2(onHotplugReceived, void(DisplayType, bool));
-    MOCK_CONST_METHOD1(dump, void(String8&));
+    MOCK_CONST_METHOD1(dump, void(std::string&));
     MOCK_METHOD1(setPhaseOffset, void(nsecs_t phaseOffset));
 };
 
diff --git a/services/surfaceflinger/tests/unittests/mock/RenderEngine/MockRenderEngine.h b/services/surfaceflinger/tests/unittests/mock/RenderEngine/MockRenderEngine.h
index a416808..11e5631 100644
--- a/services/surfaceflinger/tests/unittests/mock/RenderEngine/MockRenderEngine.h
+++ b/services/surfaceflinger/tests/unittests/mock/RenderEngine/MockRenderEngine.h
@@ -38,7 +38,7 @@
     MOCK_METHOD0(createFramebuffer, std::unique_ptr<Framebuffer>());
     MOCK_METHOD0(createImage, std::unique_ptr<renderengine::Image>());
     MOCK_CONST_METHOD0(primeCache, void());
-    MOCK_METHOD1(dump, void(String8&));
+    MOCK_METHOD1(dump, void(std::string&));
     MOCK_CONST_METHOD0(useNativeFenceSync, bool());
     MOCK_CONST_METHOD0(useWaitSync, bool());
     MOCK_CONST_METHOD0(isCurrent, bool());