Merge "wifi: correct API name" into rvc-dev
diff --git a/cmds/incidentd/src/Section.cpp b/cmds/incidentd/src/Section.cpp
index 2229e1c..d79123b 100644
--- a/cmds/incidentd/src/Section.cpp
+++ b/cmds/incidentd/src/Section.cpp
@@ -20,9 +20,9 @@
 
 #include <dirent.h>
 #include <errno.h>
-
 #include <mutex>
 #include <set>
+#include <thread>
 
 #include <android-base/file.h>
 #include <android-base/properties.h>
@@ -42,6 +42,7 @@
 #include "frameworks/base/core/proto/android/os/backtrace.proto.h"
 #include "frameworks/base/core/proto/android/os/data.proto.h"
 #include "frameworks/base/core/proto/android/util/log.proto.h"
+#include "frameworks/base/core/proto/android/util/textdump.proto.h"
 #include "incidentd_util.h"
 
 namespace android {
@@ -135,7 +136,7 @@
     status_t ihStatus = wait_child(pid);
     if (ihStatus != NO_ERROR) {
         ALOGW("[%s] abnormal child process: %s", this->name.string(), strerror(-ihStatus));
-        return ihStatus;
+        return OK; // Not a fatal error.
     }
 
     return writer->writeSection(buffer);
@@ -234,7 +235,7 @@
     Fpipe pipe;
 
     // Lock protects these fields
-    mutex lock;
+    std::mutex lock;
     bool workerDone;
     status_t workerError;
 
@@ -261,83 +262,47 @@
     }
 }
 
-static void* worker_thread_func(void* cookie) {
-    // Don't crash the service if we write to a closed pipe (which can happen if
-    // dumping times out).
-    signal(SIGPIPE, sigpipe_handler);
-
-    WorkerThreadData* data = (WorkerThreadData*)cookie;
-    status_t err = data->section->BlockingCall(data->pipe.writeFd());
-
-    {
-        unique_lock<mutex> lock(data->lock);
-        data->workerDone = true;
-        data->workerError = err;
-    }
-
-    data->pipe.writeFd().reset();
-    data->decStrong(data->section);
-    // data might be gone now. don't use it after this point in this thread.
-    return NULL;
-}
-
 status_t WorkerThreadSection::Execute(ReportWriter* writer) const {
     status_t err = NO_ERROR;
-    pthread_t thread;
-    pthread_attr_t attr;
     bool workerDone = false;
     FdBuffer buffer;
 
-    // Data shared between this thread and the worker thread.
-    sp<WorkerThreadData> data = new WorkerThreadData(this);
-
-    // Create the pipe
-    if (!data->pipe.init()) {
+    // Create shared data and pipe
+    WorkerThreadData data(this);
+    if (!data.pipe.init()) {
         return -errno;
     }
 
-    // Create the thread
-    err = pthread_attr_init(&attr);
-    if (err != 0) {
-        return -err;
-    }
-    // TODO: Do we need to tweak thread priority?
-    err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
-    if (err != 0) {
-        pthread_attr_destroy(&attr);
-        return -err;
-    }
-
-    // The worker thread needs a reference and we can't let the count go to zero
-    // if that thread is slow to start.
-    data->incStrong(this);
-
-    err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
-    pthread_attr_destroy(&attr);
-    if (err != 0) {
-        data->decStrong(this);
-        return -err;
-    }
+    std::thread([&]() {
+        // Don't crash the service if writing to a closed pipe (may happen if dumping times out)
+        signal(SIGPIPE, sigpipe_handler);
+        status_t err = data.section->BlockingCall(data.pipe.writeFd());
+        {
+            std::unique_lock<std::mutex> lock(data.lock);
+            data.workerDone = true;
+            data.workerError = err;
+            // unique_fd is not thread safe. If we don't lock it, reset() may pause half way while
+            // the other thread executes to the end, calling ~Fpipe, which is a race condition.
+            data.pipe.writeFd().reset();
+        }
+    }).detach();
 
     // Loop reading until either the timeout or the worker side is done (i.e. eof).
-    err = buffer.read(data->pipe.readFd().get(), this->timeoutMs);
+    err = buffer.read(data.pipe.readFd().get(), this->timeoutMs);
     if (err != NO_ERROR) {
         ALOGE("[%s] reader failed with error '%s'", this->name.string(), strerror(-err));
     }
 
-    // Done with the read fd. The worker thread closes the write one so
-    // we never race and get here first.
-    data->pipe.readFd().reset();
-
     // If the worker side is finished, then return its error (which may overwrite
     // our possible error -- but it's more interesting anyway). If not, then we timed out.
     {
-        unique_lock<mutex> lock(data->lock);
-        if (data->workerError != NO_ERROR) {
-            err = data->workerError;
+        std::unique_lock<std::mutex> lock(data.lock);
+        data.pipe.close();
+        if (data.workerError != NO_ERROR) {
+            err = data.workerError;
             ALOGE("[%s] worker failed with error '%s'", this->name.string(), strerror(-err));
         }
-        workerDone = data->workerDone;
+        workerDone = data.workerDone;
     }
 
     writer->setSectionStats(buffer);
@@ -473,6 +438,77 @@
 }
 
 // ================================================================================
+TextDumpsysSection::TextDumpsysSection(int id, const char* service, ...)
+    : WorkerThreadSection(id, REMOTE_CALL_TIMEOUT_MS), mService(service) {
+    name = "dumpsys ";
+    name += service;
+
+    va_list args;
+    va_start(args, service);
+    while (true) {
+        const char* arg = va_arg(args, const char*);
+        if (arg == NULL) {
+            break;
+        }
+        mArgs.add(String16(arg));
+        name += " ";
+        name += arg;
+    }
+    va_end(args);
+}
+
+TextDumpsysSection::~TextDumpsysSection() {}
+
+status_t TextDumpsysSection::BlockingCall(unique_fd& pipeWriteFd) const {
+    // checkService won't wait for the service to show up like getService will.
+    sp<IBinder> service = defaultServiceManager()->checkService(mService);
+    if (service == NULL) {
+        ALOGW("TextDumpsysSection: Can't lookup service: %s", String8(mService).string());
+        return NAME_NOT_FOUND;
+    }
+
+    // Create pipe
+    Fpipe dumpPipe;
+    if (!dumpPipe.init()) {
+        ALOGW("[%s] failed to setup pipe", this->name.string());
+        return -errno;
+    }
+
+    // Run dumping thread
+    const uint64_t start = Nanotime();
+    std::thread worker([&]() {
+        // Don't crash the service if writing to a closed pipe (may happen if dumping times out)
+        signal(SIGPIPE, sigpipe_handler);
+        status_t err = service->dump(dumpPipe.writeFd().get(), mArgs);
+        if (err != OK) {
+            ALOGW("[%s] dump thread failed. Error: %s", this->name.string(), strerror(-err));
+        }
+        dumpPipe.writeFd().reset();
+    });
+
+    // Collect dump content
+    std::string content;
+    bool success = ReadFdToString(dumpPipe.readFd(), &content);
+    worker.join(); // Wait for worker to finish
+    dumpPipe.readFd().reset();
+    if (!success) {
+        ALOGW("[%s] failed to read data from pipe", this->name.string());
+        return -1;
+    }
+
+    ProtoOutputStream proto;
+    proto.write(util::TextDumpProto::COMMAND, std::string(name.string()));
+    proto.write(util::TextDumpProto::CONTENT, content);
+    proto.write(util::TextDumpProto::DUMP_DURATION_NS, int64_t(Nanotime() - start));
+
+    if (!proto.flush(pipeWriteFd.get()) && errno == EPIPE) {
+        ALOGE("[%s] wrote to a broken pipe\n", this->name.string());
+        return EPIPE;
+    }
+    return OK;
+}
+
+// ================================================================================
 // initialization only once in Section.cpp.
 map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
 
diff --git a/cmds/incidentd/src/Section.h b/cmds/incidentd/src/Section.h
index 0bb9da9..6162b3a 100644
--- a/cmds/incidentd/src/Section.h
+++ b/cmds/incidentd/src/Section.h
@@ -112,7 +112,8 @@
 };
 
 /**
- * Section that calls dumpsys on a system service.
+ * Section that calls protobuf dumpsys on a system service, usually
+ * "dumpsys [service_name] --proto".
  */
 class DumpsysSection : public WorkerThreadSection {
 public:
@@ -127,6 +128,21 @@
 };
 
 /**
+ * Section that calls text dumpsys on a system service, usually "dumpsys [service_name]".
+ */
+class TextDumpsysSection : public WorkerThreadSection {
+public:
+    TextDumpsysSection(int id, const char* service, ...);
+    virtual ~TextDumpsysSection();
+
+    virtual status_t BlockingCall(unique_fd& pipeWriteFd) const;
+
+private:
+    String16 mService;
+    Vector<String16> mArgs;
+};
+
+/**
  * Section that calls dumpsys on a system service.
  */
 class SystemPropertyDumpsysSection : public WorkerThreadSection {
diff --git a/core/java/android/view/WindowManagerImpl.java b/core/java/android/view/WindowManagerImpl.java
index d40f505..6435b42 100644
--- a/core/java/android/view/WindowManagerImpl.java
+++ b/core/java/android/view/WindowManagerImpl.java
@@ -16,6 +16,11 @@
 
 package android.view;
 
+import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
+import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
+import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
+import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
+
 import android.annotation.NonNull;
 import android.app.ResourcesManager;
 import android.compat.annotation.UnsupportedAppUsage;
@@ -67,10 +72,6 @@
 
     private IBinder mDefaultToken;
 
-    private boolean mIsViewAdded;
-    private View mLastView;
-    private WindowManager.LayoutParams mLastParams;
-
     public WindowManagerImpl(Context context) {
         this(context, null);
     }
@@ -102,9 +103,6 @@
     public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
         applyDefaultToken(params);
         mGlobal.addView(view, params, mContext.getDisplayNoVerify(), mParentWindow);
-        mIsViewAdded = true;
-        mLastView = view;
-        mLastParams = (WindowManager.LayoutParams) params;
     }
 
     @Override
@@ -247,21 +245,19 @@
     }
 
     private WindowInsets computeWindowInsets() {
-        // TODO(window-context): This can only be properly implemented
+        // TODO(b/118118435): This can only be properly implemented
         //  once we flip the new insets mode flag.
-        if (mParentWindow != null) {
-            if (mParentWindow.getDecorView().isAttachedToWindow()) {
-                return mParentWindow.getDecorView().getViewRootImpl()
-                        .getWindowInsets(true /* forceConstruct */);
-            }
-            return getWindowInsetsFromServer(mParentWindow.getAttributes());
-        }
-        if (mIsViewAdded) {
-            return mLastView.getViewRootImpl().getWindowInsets(true /* forceConstruct */);
-        } else {
-            return getWindowInsetsFromServer(new WindowManager.LayoutParams());
-        }
+        // Initialize params which used for obtaining all system insets.
+        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
+        params.flags = FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR;
+        params.token = (mParentWindow != null) ? mParentWindow.getContext().getActivityToken()
+                : mContext.getActivityToken();
+        params.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+                | SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
+        params.setFitInsetsTypes(0);
+        params.setFitInsetsSides(0);
 
+        return getWindowInsetsFromServer(params);
     }
 
     private WindowInsets getWindowInsetsFromServer(WindowManager.LayoutParams attrs) {
diff --git a/core/java/android/view/WindowMetrics.java b/core/java/android/view/WindowMetrics.java
index 8caf5b7..ab5a06e 100644
--- a/core/java/android/view/WindowMetrics.java
+++ b/core/java/android/view/WindowMetrics.java
@@ -17,6 +17,7 @@
 package android.view;
 
 import android.annotation.NonNull;
+import android.graphics.Point;
 import android.util.Size;
 
 /**
@@ -40,6 +41,30 @@
 
     /**
      * Returns the size of the window.
+     * <p>
+     * <b>Note that this reports a different size than {@link Display#getSize(Point)}.</b>
+     * This method reports the window size including all system bars area, while
+     * {@link Display#getSize(Point)} reports the area excluding navigation bars and display cutout
+     * areas. The value reported by {@link Display#getSize(Point)} can be obtained by using:
+     * <pre class="prettyprint">
+     * final WindowMetrics metrics = windowManager.getCurrentMetrics();
+     * // Gets all excluding insets
+     * final WindowInsets windowInsets = metrics.getWindowInsets();
+     * Insets insets = windowInsets.getInsets(WindowInsets.Type.navigationBars());
+     * final DisplayCutout cutout = windowInsets.getCutout();
+     * if (cutout != null) {
+     *     final Insets cutoutSafeInsets = Insets.of(cutout.getSafeInsetsLeft(), ...);
+     *     insets = insets.max(insets, cutoutSafeInsets);
+     * }
+     *
+     * int insetsWidth = insets.right + insets.left;
+     * int insetsHeight = insets.top + insets.bottom;
+     *
+     * // Legacy size that Display#getSize reports
+     * final Size legacySize = new Size(metrics.getWidth() - insetsWidth,
+     *         metrics.getHeight() - insetsHeight);
+     * </pre>
+     * </p>
      *
      * @return window size in pixel.
      */
diff --git a/core/proto/android/os/incident.proto b/core/proto/android/os/incident.proto
index 7d1cf5d..d6687f0 100644
--- a/core/proto/android/os/incident.proto
+++ b/core/proto/android/os/incident.proto
@@ -58,6 +58,7 @@
 import "frameworks/base/core/proto/android/service/usb.proto";
 import "frameworks/base/core/proto/android/util/event_log_tags.proto";
 import "frameworks/base/core/proto/android/util/log.proto";
+import "frameworks/base/core/proto/android/util/textdump.proto";
 import "frameworks/base/core/proto/android/privacy.proto";
 import "frameworks/base/core/proto/android/section.proto";
 import "frameworks/base/proto/src/ipconnectivity.proto";
@@ -510,6 +511,17 @@
         (section).args = "sensorservice --proto"
     ];
 
+    // Dumps in text format (on userdebug and eng builds only): 4000 ~ 4999
+    optional android.util.TextDumpProto textdump_wifi = 4000 [
+        (section).type = SECTION_TEXT_DUMPSYS,
+        (section).args = "wifi"
+    ];
+
+    optional android.util.TextDumpProto textdump_bluetooth = 4001 [
+        (section).type = SECTION_TEXT_DUMPSYS,
+        (section).args = "bluetooth_manager"
+    ];
+
     // Reserved for OEMs.
     extensions 50000 to 100000;
 }
diff --git a/core/proto/android/section.proto b/core/proto/android/section.proto
index 5afe22a..299d6f9a 100644
--- a/core/proto/android/section.proto
+++ b/core/proto/android/section.proto
@@ -46,6 +46,10 @@
 
     // incidentd calls tombstoned for annotated field
     SECTION_TOMBSTONE = 6;
+
+    // incidentd calls legacy text dumpsys for annotated field. The section will only be generated
+    // on userdebug and eng builds.
+    SECTION_TEXT_DUMPSYS = 7;
 }
 
 message SectionFlags {
diff --git a/core/proto/android/util/textdump.proto b/core/proto/android/util/textdump.proto
new file mode 100644
index 0000000..6118487
--- /dev/null
+++ b/core/proto/android/util/textdump.proto
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto2";
+package android.util;
+
+import "frameworks/base/core/proto/android/privacy.proto";
+
+option java_multiple_files = true;
+
+message TextDumpProto {
+    option (android.msg_privacy).dest = DEST_EXPLICIT;
+
+    // The command that was executed
+    optional string command = 1;
+    // The content that was dumped
+    optional string content = 2;
+    // The duration of the dump process
+    optional int64 dump_duration_ns = 3;
+}
diff --git a/core/tests/coretests/AndroidManifest.xml b/core/tests/coretests/AndroidManifest.xml
index 718ca46..b42fce0 100644
--- a/core/tests/coretests/AndroidManifest.xml
+++ b/core/tests/coretests/AndroidManifest.xml
@@ -138,6 +138,9 @@
     <!-- vr test permissions -->
     <uses-permission android:name="android.permission.RESTRICTED_VR_ACCESS" />
 
+    <!-- WindowMetricsTest permissions -->
+    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
+
     <application android:theme="@style/Theme" android:supportsRtl="true">
         <uses-library android:name="android.test.runner" />
         <uses-library android:name="org.apache.http.legacy" android:required="false" />
diff --git a/core/tests/coretests/src/android/view/WindowMetricsTest.java b/core/tests/coretests/src/android/view/WindowMetricsTest.java
new file mode 100644
index 0000000..fa68860
--- /dev/null
+++ b/core/tests/coretests/src/android/view/WindowMetricsTest.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view;
+
+import static android.view.Display.DEFAULT_DISPLAY;
+import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
+
+import static org.junit.Assert.assertTrue;
+
+import android.content.Context;
+import android.hardware.display.DisplayManager;
+import android.os.Handler;
+import android.platform.test.annotations.Presubmit;
+import android.util.Size;
+
+import androidx.test.filters.FlakyTest;
+import androidx.test.filters.SmallTest;
+import androidx.test.platform.app.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Tests for {@link WindowManager#getCurrentWindowMetrics()} and
+ * {@link WindowManager#getMaximumWindowMetrics()}.
+ *
+ * <p>Build/Install/Run:
+ *  atest FrameworksCoreTests:WindowMetricsTest
+ *
+ * <p>This test class is a part of Window Manager Service tests and specified in
+ * {@link com.android.server.wm.test.filters.FrameworksTestsFilter}.
+ */
+@FlakyTest(bugId = 148789183, detail = "Remove after confirmed it's stable.")
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+@Presubmit
+public class WindowMetricsTest {
+    private Context mWindowContext;
+    private WindowManager mWm;
+
+    @Before
+    public void setUp() {
+        final Context insetContext = InstrumentationRegistry.getInstrumentation()
+                .getTargetContext();
+        final Display display = insetContext.getSystemService(DisplayManager.class)
+                .getDisplay(DEFAULT_DISPLAY);
+        mWindowContext = insetContext.createDisplayContext(display)
+                .createWindowContext(TYPE_APPLICATION_OVERLAY, null /* options */);
+        mWm = mWindowContext.getSystemService(WindowManager.class);
+    }
+
+    @Test
+    public void testAddViewANdRemoveView_GetMetrics_DoNotCrash() {
+        final View view = new View(mWindowContext);
+        final WindowManager.LayoutParams params =
+                new WindowManager.LayoutParams(TYPE_APPLICATION_OVERLAY);
+        Handler.getMain().runWithScissors(() -> {
+            mWm.addView(view, params);
+            // Check get metrics do not crash.
+            WindowMetrics currentMetrics = mWm.getCurrentWindowMetrics();
+            WindowMetrics maxMetrics = mWm.getMaximumWindowMetrics();
+            verifyMetricsSanity(currentMetrics, maxMetrics);
+
+            mWm.removeViewImmediate(view);
+            // Check get metrics do not crash.
+            currentMetrics = mWm.getCurrentWindowMetrics();
+            maxMetrics = mWm.getMaximumWindowMetrics();
+            verifyMetricsSanity(currentMetrics, maxMetrics);
+        }, 0);
+    }
+
+    private static void verifyMetricsSanity(WindowMetrics currentMetrics,
+            WindowMetrics maxMetrics) {
+        Size currentSize = currentMetrics.getSize();
+        Size maxSize = maxMetrics.getSize();
+
+        assertTrue(maxSize.getWidth() >= currentSize.getWidth());
+        assertTrue(maxSize.getHeight() >= currentSize.getHeight());
+    }
+}
diff --git a/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java b/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java
index 8d090f1..801d75b 100644
--- a/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java
+++ b/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java
@@ -218,11 +218,7 @@
                         packageInstaller.getSessionInfo(sessionId);
                 if (sessionInfo.isStagedSessionReady() && markStagedSessionHandled(rollbackId)) {
                     mContext.unregisterReceiver(listener);
-                    if (logPackage != null) {
-                        // We save the rollback id so that after reboot, we can log if rollback was
-                        // successful or not. If logPackage is null, then there is nothing to log.
-                        saveStagedRollbackId(rollbackId);
-                    }
+                    saveStagedRollbackId(rollbackId);
                     WatchdogRollbackLogger.logEvent(logPackage,
                             FrameworkStatsLog
                             .WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_BOOT_TRIGGERED,
diff --git a/services/core/java/com/android/server/rollback/WatchdogRollbackLogger.java b/services/core/java/com/android/server/rollback/WatchdogRollbackLogger.java
index 1be6f22..659de00 100644
--- a/services/core/java/com/android/server/rollback/WatchdogRollbackLogger.java
+++ b/services/core/java/com/android/server/rollback/WatchdogRollbackLogger.java
@@ -159,6 +159,12 @@
             return;
         }
 
+        // If no logging packages are found, use a null package to ensure the rollback status
+        // is still logged.
+        if (oldLoggingPackages.isEmpty()) {
+            oldLoggingPackages.add(null);
+        }
+
         for (VersionedPackage oldLoggingPackage : oldLoggingPackages) {
             if (sessionInfo.isStagedSessionApplied()) {
                 logEvent(oldLoggingPackage,
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 9cb5ba7..e0f8f0e 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -8075,32 +8075,39 @@
     public void getWindowInsets(WindowManager.LayoutParams attrs,
             int displayId, Rect outContentInsets, Rect outStableInsets,
             DisplayCutout.ParcelableWrapper displayCutout) {
-        synchronized (mGlobalLock) {
-            final DisplayContent dc = mRoot.getDisplayContentOrCreate(displayId);
-            if (dc == null) {
-                throw new WindowManager.InvalidDisplayException("Display#" + displayId
-                        + "could not be found!");
+        final long origId = Binder.clearCallingIdentity();
+        try {
+            synchronized (mGlobalLock) {
+                final DisplayContent dc = getDisplayContentOrCreate(displayId, attrs.token);
+                if (dc == null) {
+                    throw new WindowManager.InvalidDisplayException("Display#" + displayId
+                            + "could not be found!");
+                }
+                final WindowToken windowToken = dc.getWindowToken(attrs.token);
+                final ActivityRecord activity;
+                if (windowToken != null && windowToken.asActivityRecord() != null) {
+                    activity = windowToken.asActivityRecord();
+                } else {
+                    activity = null;
+                }
+                final Rect taskBounds;
+                final boolean floatingStack;
+                if (activity != null && activity.getTask() != null) {
+                    final Task task = activity.getTask();
+                    taskBounds = new Rect();
+                    task.getBounds(taskBounds);
+                    floatingStack = task.isFloating();
+                } else {
+                    taskBounds = null;
+                    floatingStack = false;
+                }
+                final DisplayFrames displayFrames = dc.mDisplayFrames;
+                final DisplayPolicy policy = dc.getDisplayPolicy();
+                policy.getLayoutHintLw(attrs, taskBounds, displayFrames, floatingStack,
+                        new Rect(), outContentInsets, outStableInsets, displayCutout);
             }
-            final WindowToken windowToken = dc.getWindowToken(attrs.token);
-            final ActivityRecord activity;
-            if (windowToken != null && windowToken.asActivityRecord() != null) {
-                activity = windowToken.asActivityRecord();
-            } else {
-                activity = null;
-            }
-            final Rect taskBounds = new Rect();
-            final boolean floatingStack;
-            if (activity != null && activity.getTask() != null) {
-                final Task task = activity.getTask();
-                task.getBounds(taskBounds);
-                floatingStack = task.isFloating();
-            } else {
-                floatingStack = false;
-            }
-            final DisplayFrames displayFrames = dc.mDisplayFrames;
-            final DisplayPolicy policy = dc.getDisplayPolicy();
-            policy.getLayoutHintLw(attrs, taskBounds, displayFrames, floatingStack,
-                    new Rect(), outContentInsets, outStableInsets, displayCutout);
+        } finally {
+            Binder.restoreCallingIdentity(origId);
         }
     }
 }
diff --git a/tests/RollbackTest/NetworkStagedRollbackTest/src/com/android/tests/rollback/host/NetworkStagedRollbackTest.java b/tests/RollbackTest/NetworkStagedRollbackTest/src/com/android/tests/rollback/host/NetworkStagedRollbackTest.java
index d4e34f9..f6dcff4 100644
--- a/tests/RollbackTest/NetworkStagedRollbackTest/src/com/android/tests/rollback/host/NetworkStagedRollbackTest.java
+++ b/tests/RollbackTest/NetworkStagedRollbackTest/src/com/android/tests/rollback/host/NetworkStagedRollbackTest.java
@@ -53,6 +53,7 @@
 
     private static final String ROLLBACK_INITIATE = "ROLLBACK_INITIATE";
     private static final String ROLLBACK_BOOT_TRIGGERED = "ROLLBACK_BOOT_TRIGGERED";
+    private static final String ROLLBACK_SUCCESS = "ROLLBACK_SUCCESS";
 
     private WatchdogEventLogger mLogger = new WatchdogEventLogger();
 
@@ -93,6 +94,7 @@
                     REASON_EXPLICIT_HEALTH_CHECK, null));
             assertTrue(watchdogEventOccurred(watchdogEvents, ROLLBACK_BOOT_TRIGGERED, null,
                     null, null));
+            assertTrue(watchdogEventOccurred(watchdogEvents, ROLLBACK_SUCCESS, null, null, null));
         } finally {
             // Reconnect internet again so we won't break tests which assume internet available
             getDevice().executeShellCommand("svc wifi enable");
diff --git a/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java b/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java
index 43759cf..4afebb5 100644
--- a/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java
+++ b/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java
@@ -76,10 +76,10 @@
 
     private static final String REASON_APP_CRASH = "REASON_APP_CRASH";
     private static final String REASON_NATIVE_CRASH = "REASON_NATIVE_CRASH";
-    private static final String REASON_EXPLICIT_HEALTH_CHECK = "REASON_EXPLICIT_HEALTH_CHECK";
 
     private static final String ROLLBACK_INITIATE = "ROLLBACK_INITIATE";
     private static final String ROLLBACK_BOOT_TRIGGERED = "ROLLBACK_BOOT_TRIGGERED";
+    private static final String ROLLBACK_SUCCESS = "ROLLBACK_SUCCESS";
 
     private WatchdogEventLogger mLogger = new WatchdogEventLogger();
 
@@ -146,6 +146,7 @@
                 REASON_APP_CRASH, TESTAPP_A));
         assertTrue(watchdogEventOccurred(watchdogEvents, ROLLBACK_BOOT_TRIGGERED, null,
                 null, null));
+        assertTrue(watchdogEventOccurred(watchdogEvents, ROLLBACK_SUCCESS, null, null, null));
     }
 
     @Test
@@ -179,6 +180,7 @@
                         REASON_NATIVE_CRASH, null));
         assertTrue(watchdogEventOccurred(watchdogEvents, ROLLBACK_BOOT_TRIGGERED, null,
                 null, null));
+        assertTrue(watchdogEventOccurred(watchdogEvents, ROLLBACK_SUCCESS, null, null, null));
     }
 
     @Test
@@ -219,6 +221,7 @@
                         REASON_NATIVE_CRASH, null));
         assertTrue(watchdogEventOccurred(watchdogEvents, ROLLBACK_BOOT_TRIGGERED, null,
                 null, null));
+        assertTrue(watchdogEventOccurred(watchdogEvents, ROLLBACK_SUCCESS, null, null, null));
     }
 
     /**
@@ -290,6 +293,7 @@
                 REASON_APP_CRASH, TESTAPP_A));
         assertTrue(watchdogEventOccurred(watchdogEvents, ROLLBACK_BOOT_TRIGGERED, null,
                 null, null));
+        assertTrue(watchdogEventOccurred(watchdogEvents, ROLLBACK_SUCCESS, null, null, null));
     }
 
     /**
diff --git a/tests/utils/testutils/java/com/android/server/wm/test/filters/FrameworksTestsFilter.java b/tests/utils/testutils/java/com/android/server/wm/test/filters/FrameworksTestsFilter.java
index 26916bc..aed62d0 100644
--- a/tests/utils/testutils/java/com/android/server/wm/test/filters/FrameworksTestsFilter.java
+++ b/tests/utils/testutils/java/com/android/server/wm/test/filters/FrameworksTestsFilter.java
@@ -46,6 +46,7 @@
             "android.view.InsetsSourceTest",
             "android.view.InsetsSourceConsumerTest",
             "android.view.InsetsStateTest",
+            "android.view.WindowMetricsTest"
     };
 
     public FrameworksTestsFilter(Bundle testArgs) {
diff --git a/tools/incident_section_gen/main.cpp b/tools/incident_section_gen/main.cpp
index ded4b91..786223a 100644
--- a/tools/incident_section_gen/main.cpp
+++ b/tools/incident_section_gen/main.cpp
@@ -415,7 +415,7 @@
         }
 
         const SectionFlags s = getSectionFlags(field);
-        if (s.userdebug_and_eng_only()) {
+        if (s.userdebug_and_eng_only() || s.type() == SECTION_TEXT_DUMPSYS) {
             printf("#if ALLOW_RESTRICTED_SECTIONS\n");
         }
 
@@ -449,8 +449,13 @@
                 printf("    new TombstoneSection(%d, \"%s\"),\n", field->number(),
                         s.args().c_str());
                 break;
+            case SECTION_TEXT_DUMPSYS:
+                printf("    new TextDumpsysSection(%d, ", field->number());
+                splitAndPrint(s.args());
+                printf(" NULL),\n");
+                break;
         }
-        if (s.userdebug_and_eng_only()) {
+        if (s.userdebug_and_eng_only() || s.type() == SECTION_TEXT_DUMPSYS) {
             printf("#endif\n");
         }
     }