Synchronize all WindowTestsBase and WindowTestUtils methods.

Several WindowManager tests access WindowManager code that assume the WM
lock is already held. This can cause crashes in native code and cause
unexpected behavior. Added synchronize blocks around all helper methods
to avoid adding synchronized blocks in all WM tests methods.

This does not guarantee that all WM tests are synchronized, but handles
a good bulk of them for now.

The largest number of failures were from ZOrderingTests since that tests
creates a lot of windows, making synchronicity issues more likely. Ran
that test class multiple times to ensure I was unable to get the
failure.

Test: ZOrderingTests
Bug: 73966377
Change-Id: I96f586e7ea91223589caef885c87ecded555ab13
Fixes: 72976082
diff --git a/services/tests/servicestests/src/com/android/server/wm/AppWindowTokenTests.java b/services/tests/servicestests/src/com/android/server/wm/AppWindowTokenTests.java
index 759894b..8d5214a 100644
--- a/services/tests/servicestests/src/com/android/server/wm/AppWindowTokenTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/AppWindowTokenTests.java
@@ -61,7 +61,7 @@
 
         mStack = createTaskStackOnDisplay(mDisplayContent);
         mTask = createTaskInStack(mStack, 0 /* userId */);
-        mToken = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
+        mToken = WindowTestUtils.createTestAppWindowToken(mDisplayContent);
 
         mTask.addChild(mToken, 0);
     }
diff --git a/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java b/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java
index a8556bd..e31e20c 100644
--- a/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java
@@ -193,7 +193,8 @@
         assertEquals(dc, stack.getDisplayContent());
 
         final Task task = createTaskInStack(stack, 0 /* userId */);
-        final WindowTestUtils.TestAppWindowToken token = new WindowTestUtils.TestAppWindowToken(dc);
+        final WindowTestUtils.TestAppWindowToken token = WindowTestUtils.createTestAppWindowToken(
+                dc);
         task.addChild(token, 0);
         assertEquals(dc, task.getDisplayContent());
         assertEquals(dc, token.getDisplayContent());
@@ -265,14 +266,14 @@
         final TaskStack stack0 = createTaskStackOnDisplay(dc0);
         final Task task0 = createTaskInStack(stack0, 0 /* userId */);
         final WindowTestUtils.TestAppWindowToken token =
-                new WindowTestUtils.TestAppWindowToken(dc0);
+                WindowTestUtils.createTestAppWindowToken(dc0);
         task0.addChild(token, 0);
         dc0.mTapDetector = new TaskTapPointerEventListener(sWm, dc0);
         sWm.registerPointerEventListener(dc0.mTapDetector);
         final TaskStack stack1 = createTaskStackOnDisplay(dc1);
         final Task task1 = createTaskInStack(stack1, 0 /* userId */);
         final WindowTestUtils.TestAppWindowToken token1 =
-                new WindowTestUtils.TestAppWindowToken(dc0);
+                WindowTestUtils.createTestAppWindowToken(dc0);
         task1.addChild(token1, 0);
         dc1.mTapDetector = new TaskTapPointerEventListener(sWm, dc0);
         sWm.registerPointerEventListener(dc1.mTapDetector);
diff --git a/services/tests/servicestests/src/com/android/server/wm/DragDropControllerTests.java b/services/tests/servicestests/src/com/android/server/wm/DragDropControllerTests.java
index 57da6a3..a09656c 100644
--- a/services/tests/servicestests/src/com/android/server/wm/DragDropControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/DragDropControllerTests.java
@@ -89,7 +89,7 @@
      * Creates a window state which can be used as a drop target.
      */
     private WindowState createDropTargetWindow(String name, int ownerId) {
-        final WindowTestUtils.TestAppWindowToken token = new WindowTestUtils.TestAppWindowToken(
+        final WindowTestUtils.TestAppWindowToken token = WindowTestUtils.createTestAppWindowToken(
                 mDisplayContent);
         final TaskStack stack = createStackControllerOnStackOnDisplay(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, mDisplayContent).mContainer;
diff --git a/services/tests/servicestests/src/com/android/server/wm/TaskStackContainersTests.java b/services/tests/servicestests/src/com/android/server/wm/TaskStackContainersTests.java
index 71bcae7..ca1994f 100644
--- a/services/tests/servicestests/src/com/android/server/wm/TaskStackContainersTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/TaskStackContainersTests.java
@@ -54,8 +54,8 @@
         // Stack should contain visible app window to be considered visible.
         final Task pinnedTask = createTaskInStack(mPinnedStack, 0 /* userId */);
         assertFalse(mPinnedStack.isVisible());
-        final WindowTestUtils.TestAppWindowToken pinnedApp = new WindowTestUtils.TestAppWindowToken(
-                mDisplayContent);
+        final WindowTestUtils.TestAppWindowToken pinnedApp =
+                WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         pinnedTask.addChild(pinnedApp, 0 /* addPos */);
         assertTrue(mPinnedStack.isVisible());
     }
diff --git a/services/tests/servicestests/src/com/android/server/wm/TaskStackTests.java b/services/tests/servicestests/src/com/android/server/wm/TaskStackTests.java
index 0ef78f4..eaf71f0 100644
--- a/services/tests/servicestests/src/com/android/server/wm/TaskStackTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/TaskStackTests.java
@@ -65,13 +65,13 @@
         final TaskStack stack = createTaskStackOnDisplay(mDisplayContent);
         final Task task1 = createTaskInStack(stack, 0 /* userId */);
         WindowTestUtils.TestAppWindowToken appWindowToken1 =
-                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
+                WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         task1.addChild(appWindowToken1, 0);
         appWindowToken1.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
 
         final Task task2 = createTaskInStack(stack, 1 /* userId */);
         WindowTestUtils.TestAppWindowToken appWindowToken2 =
-                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
+                WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         task2.addChild(appWindowToken2, 0);
         appWindowToken2.setOrientation(SCREEN_ORIENTATION_PORTRAIT);
 
@@ -85,13 +85,13 @@
         final TaskStack stack = createTaskStackOnDisplay(mDisplayContent);
         final Task task1 = createTaskInStack(stack, 0 /* userId */);
         WindowTestUtils.TestAppWindowToken appWindowToken1 =
-                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
+                WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         task1.addChild(appWindowToken1, 0);
         appWindowToken1.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
 
         final Task task2 = createTaskInStack(stack, 1 /* userId */);
         WindowTestUtils.TestAppWindowToken appWindowToken2 =
-                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
+                WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         task2.addChild(appWindowToken2, 0);
         appWindowToken2.setOrientation(SCREEN_ORIENTATION_PORTRAIT);
 
diff --git a/services/tests/servicestests/src/com/android/server/wm/UnknownAppVisibilityControllerTest.java b/services/tests/servicestests/src/com/android/server/wm/UnknownAppVisibilityControllerTest.java
index 4a22a29..a5c47de 100644
--- a/services/tests/servicestests/src/com/android/server/wm/UnknownAppVisibilityControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/wm/UnknownAppVisibilityControllerTest.java
@@ -44,7 +44,7 @@
 
     @Test
     public void testFlow() throws Exception {
-        final AppWindowToken token = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
+        final AppWindowToken token = WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         sWm.mUnknownAppVisibilityController.notifyLaunched(token);
         sWm.mUnknownAppVisibilityController.notifyAppResumedFinished(token);
         sWm.mUnknownAppVisibilityController.notifyRelayouted(token);
@@ -56,8 +56,8 @@
 
     @Test
     public void testMultiple() throws Exception {
-        final AppWindowToken token1 = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
-        final AppWindowToken token2 = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
+        final AppWindowToken token1 = WindowTestUtils.createTestAppWindowToken(mDisplayContent);
+        final AppWindowToken token2 = WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         sWm.mUnknownAppVisibilityController.notifyLaunched(token1);
         sWm.mUnknownAppVisibilityController.notifyAppResumedFinished(token1);
         sWm.mUnknownAppVisibilityController.notifyLaunched(token2);
@@ -72,7 +72,7 @@
 
     @Test
     public void testClear() throws Exception {
-        final AppWindowToken token = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
+        final AppWindowToken token = WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         sWm.mUnknownAppVisibilityController.notifyLaunched(token);
         sWm.mUnknownAppVisibilityController.clear();;
         assertTrue(sWm.mUnknownAppVisibilityController.allResolved());
@@ -80,7 +80,7 @@
 
     @Test
     public void testAppRemoved() throws Exception {
-        final AppWindowToken token = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
+        final AppWindowToken token = WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         sWm.mUnknownAppVisibilityController.notifyLaunched(token);
         sWm.mUnknownAppVisibilityController.appRemovedOrHidden(token);
         assertTrue(sWm.mUnknownAppVisibilityController.allResolved());
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowFrameTests.java b/services/tests/servicestests/src/com/android/server/wm/WindowFrameTests.java
index 7d6301cc..b5d5fc6 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowFrameTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowFrameTests.java
@@ -114,7 +114,8 @@
         // Just any non zero value.
         sWm.mSystemDecorLayer = 10000;
 
-        mWindowToken = new WindowTestUtils.TestAppWindowToken(sWm.getDefaultDisplayContentLocked());
+        mWindowToken = WindowTestUtils.createTestAppWindowToken(
+                sWm.getDefaultDisplayContentLocked());
         mStubStack = new TaskStack(sWm, 0, null);
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowStateTests.java b/services/tests/servicestests/src/com/android/server/wm/WindowStateTests.java
index 678aa64..cdcb949 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowStateTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowStateTests.java
@@ -260,7 +260,7 @@
 
         // Call prepareWindowToDisplayDuringRelayout for a windows that are not children of an
         // appWindowToken. Both windows have the FLAG_TURNS_SCREEN_ON so both should call wakeup
-        final WindowToken windowToken = new WindowTestUtils.TestWindowToken(FIRST_SUB_WINDOW,
+        final WindowToken windowToken = WindowTestUtils.createTestWindowToken(FIRST_SUB_WINDOW,
                 mDisplayContent);
         final WindowState firstWindow = createWindow(null, TYPE_APPLICATION, windowToken,
                 "firstWindow");
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowTestUtils.java b/services/tests/servicestests/src/com/android/server/wm/WindowTestUtils.java
index 012fc23..f4cdc90 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowTestUtils.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowTestUtils.java
@@ -87,10 +87,12 @@
     /** Creates a {@link Task} and adds it to the specified {@link TaskStack}. */
     public static Task createTaskInStack(WindowManagerService service, TaskStack stack,
             int userId) {
-        final Task newTask = new Task(sNextTaskId++, stack, userId, service, 0, false,
-                new ActivityManager.TaskDescription(), null);
-        stack.addTask(newTask, POSITION_TOP);
-        return newTask;
+        synchronized (service.mWindowMap) {
+            final Task newTask = new Task(sNextTaskId++, stack, userId, service, 0, false,
+                    new ActivityManager.TaskDescription(), null);
+            stack.addTask(newTask, POSITION_TOP);
+            return newTask;
+        }
     }
 
     /**
@@ -108,11 +110,17 @@
         }
     }
 
+    static TestAppWindowToken createTestAppWindowToken(DisplayContent dc) {
+        synchronized (dc.mService.mWindowMap) {
+            return new TestAppWindowToken(dc);
+        }
+    }
+
     /** Used so we can gain access to some protected members of the {@link AppWindowToken} class. */
     public static class TestAppWindowToken extends AppWindowToken {
         boolean mOnTop = false;
 
-        TestAppWindowToken(DisplayContent dc) {
+        private TestAppWindowToken(DisplayContent dc) {
             super(dc.mService, new IApplicationToken.Stub() {
                 public String getName() {return null;}
                 }, false, dc, true /* fillsParent */);
@@ -158,14 +166,21 @@
         }
     }
 
+    static TestWindowToken createTestWindowToken(int type, DisplayContent dc) {
+        return createTestWindowToken(type, dc, false /* persistOnEmpty */);
+    }
+
+    static TestWindowToken createTestWindowToken(int type, DisplayContent dc,
+            boolean persistOnEmpty) {
+        synchronized (dc.mService.mWindowMap) {
+            return new TestWindowToken(type, dc, persistOnEmpty);
+        }
+    }
+
     /* Used so we can gain access to some protected members of the {@link WindowToken} class */
     public static class TestWindowToken extends WindowToken {
 
-        TestWindowToken(int type, DisplayContent dc) {
-            this(type, dc, false /* persistOnEmpty */);
-        }
-
-        TestWindowToken(int type, DisplayContent dc, boolean persistOnEmpty) {
+        private TestWindowToken(int type, DisplayContent dc, boolean persistOnEmpty) {
             super(dc.mService, mock(IBinder.class), type, persistOnEmpty, dc,
                     false /* ownerCanManageAppTokens */);
         }
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowTestsBase.java b/services/tests/servicestests/src/com/android/server/wm/WindowTestsBase.java
index 7499190..6fa2740 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowTestsBase.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowTestsBase.java
@@ -61,6 +61,8 @@
 
 /**
  * Common base class for window manager unit test classes.
+ *
+ * Make sure any requests to WM hold the WM lock if needed b/73966377
  */
 class WindowTestsBase {
     private static final String TAG = WindowTestsBase.class.getSimpleName();
@@ -120,21 +122,24 @@
 
             // Set-up some common windows.
             mCommonWindows = new HashSet();
-            mWallpaperWindow = createCommonWindow(null, TYPE_WALLPAPER, "wallpaperWindow");
-            mImeWindow = createCommonWindow(null, TYPE_INPUT_METHOD, "mImeWindow");
-            sWm.mInputMethodWindow = mImeWindow;
-            mImeDialogWindow = createCommonWindow(null, TYPE_INPUT_METHOD_DIALOG,
-                    "mImeDialogWindow");
-            mStatusBarWindow = createCommonWindow(null, TYPE_STATUS_BAR, "mStatusBarWindow");
-            mNavBarWindow = createCommonWindow(null, TYPE_NAVIGATION_BAR, "mNavBarWindow");
-            mDockedDividerWindow = createCommonWindow(null, TYPE_DOCK_DIVIDER,
-                    "mDockedDividerWindow");
-            mAppWindow = createCommonWindow(null, TYPE_BASE_APPLICATION, "mAppWindow");
-            mChildAppWindowAbove = createCommonWindow(mAppWindow, TYPE_APPLICATION_ATTACHED_DIALOG,
-                    "mChildAppWindowAbove");
-            mChildAppWindowBelow = createCommonWindow(mAppWindow, TYPE_APPLICATION_MEDIA_OVERLAY,
-                    "mChildAppWindowBelow");
-
+            synchronized (sWm.mWindowMap) {
+                mWallpaperWindow = createCommonWindow(null, TYPE_WALLPAPER, "wallpaperWindow");
+                mImeWindow = createCommonWindow(null, TYPE_INPUT_METHOD, "mImeWindow");
+                sWm.mInputMethodWindow = mImeWindow;
+                mImeDialogWindow = createCommonWindow(null, TYPE_INPUT_METHOD_DIALOG,
+                        "mImeDialogWindow");
+                mStatusBarWindow = createCommonWindow(null, TYPE_STATUS_BAR, "mStatusBarWindow");
+                mNavBarWindow = createCommonWindow(null, TYPE_NAVIGATION_BAR, "mNavBarWindow");
+                mDockedDividerWindow = createCommonWindow(null, TYPE_DOCK_DIVIDER,
+                        "mDockedDividerWindow");
+                mAppWindow = createCommonWindow(null, TYPE_BASE_APPLICATION, "mAppWindow");
+                mChildAppWindowAbove = createCommonWindow(mAppWindow,
+                        TYPE_APPLICATION_ATTACHED_DIALOG,
+                        "mChildAppWindowAbove");
+                mChildAppWindowBelow = createCommonWindow(mAppWindow,
+                        TYPE_APPLICATION_MEDIA_OVERLAY,
+                        "mChildAppWindowBelow");
+            }
             // Adding a display will cause freezing the display. Make sure to wait until it's
             // unfrozen to not run into race conditions with the tests.
             waitUntilHandlersIdle();
@@ -187,11 +192,13 @@
     }
 
     private WindowState createCommonWindow(WindowState parent, int type, String name) {
-        final WindowState win = createWindow(parent, type, name);
-        mCommonWindows.add(win);
-        // Prevent common windows from been IMe targets
-        win.mAttrs.flags |= FLAG_NOT_FOCUSABLE;
-        return win;
+        synchronized (sWm.mWindowMap) {
+            final WindowState win = createWindow(parent, type, name);
+            mCommonWindows.add(win);
+            // Prevent common windows from been IMe targets
+            win.mAttrs.flags |= FLAG_NOT_FOCUSABLE;
+            return win;
+        }
     }
 
     /** Asserts that the first entry is greater than the second entry. */
@@ -215,11 +222,13 @@
 
     private WindowToken createWindowToken(
             DisplayContent dc, int windowingMode, int activityType, int type) {
-        if (type < FIRST_APPLICATION_WINDOW || type > LAST_APPLICATION_WINDOW) {
-            return new WindowTestUtils.TestWindowToken(type, dc);
-        }
+        synchronized (sWm.mWindowMap) {
+            if (type < FIRST_APPLICATION_WINDOW || type > LAST_APPLICATION_WINDOW) {
+                return WindowTestUtils.createTestWindowToken(type, dc);
+            }
 
-        return createAppWindowToken(dc, windowingMode, activityType);
+            return createAppWindowToken(dc, windowingMode, activityType);
+        }
     }
 
     AppWindowToken createAppWindowToken(DisplayContent dc, int windowingMode, int activityType) {
@@ -227,81 +236,103 @@
                 dc).mContainer;
         final Task task = createTaskInStack(stack, 0 /* userId */);
         final WindowTestUtils.TestAppWindowToken appWindowToken =
-                new WindowTestUtils.TestAppWindowToken(mDisplayContent);
+                WindowTestUtils.createTestAppWindowToken(dc);
         task.addChild(appWindowToken, 0);
         return appWindowToken;
     }
 
     WindowState createWindow(WindowState parent, int type, String name) {
-        return (parent == null)
-                ? createWindow(parent, type, mDisplayContent, name)
-                : createWindow(parent, type, parent.mToken, name);
+        synchronized (sWm.mWindowMap) {
+            return (parent == null)
+                    ? createWindow(parent, type, mDisplayContent, name)
+                    : createWindow(parent, type, parent.mToken, name);
+        }
     }
 
     WindowState createWindowOnStack(WindowState parent, int windowingMode, int activityType,
             int type, DisplayContent dc, String name) {
-        final WindowToken token = createWindowToken(dc, windowingMode, activityType, type);
-        return createWindow(parent, type, token, name);
+        synchronized (sWm.mWindowMap) {
+            final WindowToken token = createWindowToken(dc, windowingMode, activityType, type);
+            return createWindow(parent, type, token, name);
+        }
     }
 
     WindowState createAppWindow(Task task, int type, String name) {
-        final AppWindowToken token = new WindowTestUtils.TestAppWindowToken(mDisplayContent);
-        task.addChild(token, 0);
-        return createWindow(null, type, token, name);
+        synchronized (sWm.mWindowMap) {
+            final AppWindowToken token = WindowTestUtils.createTestAppWindowToken(mDisplayContent);
+            task.addChild(token, 0);
+            return createWindow(null, type, token, name);
+        }
     }
 
     WindowState createWindow(WindowState parent, int type, DisplayContent dc, String name) {
-        final WindowToken token = createWindowToken(
-                dc, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, type);
-        return createWindow(parent, type, token, name);
+        synchronized (sWm.mWindowMap) {
+            final WindowToken token = createWindowToken(
+                    dc, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, type);
+            return createWindow(parent, type, token, name);
+        }
     }
 
     WindowState createWindow(WindowState parent, int type, DisplayContent dc, String name,
             boolean ownerCanAddInternalSystemWindow) {
-        final WindowToken token = createWindowToken(
-                dc, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, type);
-        return createWindow(parent, type, token, name, 0 /* ownerId */,
-                ownerCanAddInternalSystemWindow);
+        synchronized (sWm.mWindowMap) {
+            final WindowToken token = createWindowToken(
+                    dc, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, type);
+            return createWindow(parent, type, token, name, 0 /* ownerId */,
+                    ownerCanAddInternalSystemWindow);
+        }
     }
 
     static WindowState createWindow(WindowState parent, int type, WindowToken token, String name) {
-        return createWindow(parent, type, token, name, 0 /* ownerId */,
-                false /* ownerCanAddInternalSystemWindow */);
+        synchronized (sWm.mWindowMap) {
+            return createWindow(parent, type, token, name, 0 /* ownerId */,
+                    false /* ownerCanAddInternalSystemWindow */);
+        }
     }
 
     static WindowState createWindow(WindowState parent, int type, WindowToken token, String name,
             int ownerId, boolean ownerCanAddInternalSystemWindow) {
-        final WindowManager.LayoutParams attrs = new WindowManager.LayoutParams(type);
-        attrs.setTitle(name);
+        synchronized (sWm.mWindowMap) {
+            final WindowManager.LayoutParams attrs = new WindowManager.LayoutParams(type);
+            attrs.setTitle(name);
 
-        final WindowState w = new WindowState(sWm, sMockSession, sIWindow, token, parent, OP_NONE,
-                0, attrs, VISIBLE, ownerId, ownerCanAddInternalSystemWindow, mPowerManagerWrapper);
-        // TODO: Probably better to make this call in the WindowState ctor to avoid errors with
-        // adding it to the token...
-        token.addWindow(w);
-        return w;
+            final WindowState w = new WindowState(sWm, sMockSession, sIWindow, token, parent,
+                    OP_NONE,
+                    0, attrs, VISIBLE, ownerId, ownerCanAddInternalSystemWindow,
+                    mPowerManagerWrapper);
+            // TODO: Probably better to make this call in the WindowState ctor to avoid errors with
+            // adding it to the token...
+            token.addWindow(w);
+            return w;
+        }
     }
 
     /** Creates a {@link TaskStack} and adds it to the specified {@link DisplayContent}. */
     TaskStack createTaskStackOnDisplay(DisplayContent dc) {
-        return createStackControllerOnDisplay(dc).mContainer;
+        synchronized (sWm.mWindowMap) {
+            return createStackControllerOnDisplay(dc).mContainer;
+        }
     }
 
     StackWindowController createStackControllerOnDisplay(DisplayContent dc) {
-        return createStackControllerOnStackOnDisplay(
-                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, dc);
+        synchronized (sWm.mWindowMap) {
+            return createStackControllerOnStackOnDisplay(
+                    WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, dc);
+        }
     }
 
     StackWindowController createStackControllerOnStackOnDisplay(
             int windowingMode, int activityType, DisplayContent dc) {
-        final Configuration overrideConfig = new Configuration();
-        overrideConfig.windowConfiguration.setWindowingMode(windowingMode);
-        overrideConfig.windowConfiguration.setActivityType(activityType);
-        final int stackId = ++sNextStackId;
-        final StackWindowController controller = new StackWindowController(stackId, null,
-                dc.getDisplayId(), true /* onTop */, new Rect(), sWm);
-        controller.onOverrideConfigurationChanged(overrideConfig);
-        return controller;
+        synchronized (sWm.mWindowMap) {
+            final Configuration overrideConfig = new Configuration();
+            overrideConfig.windowConfiguration.setWindowingMode(windowingMode);
+            overrideConfig.windowConfiguration.setActivityType(activityType);
+            final int stackId = ++sNextStackId;
+            final StackWindowController controller = new StackWindowController(stackId, null,
+                    dc.getDisplayId(), true /* onTop */, new Rect(), sWm);
+            controller.onOverrideConfigurationChanged(overrideConfig);
+            return controller;
+        }
     }
 
     /** Creates a {@link Task} and adds it to the specified {@link TaskStack}. */
@@ -314,14 +345,18 @@
         final int displayId = sNextDisplayId++;
         final Display display = new Display(DisplayManagerGlobal.getInstance(), displayId,
                 mDisplayInfo, DEFAULT_DISPLAY_ADJUSTMENTS);
-        return new DisplayContent(display, sWm, mWallpaperController,
-                mock(DisplayWindowController.class));
+        synchronized (sWm.mWindowMap) {
+            return new DisplayContent(display, sWm, mWallpaperController,
+                    mock(DisplayWindowController.class));
+        }
     }
 
     /** Creates a {@link com.android.server.wm.WindowTestUtils.TestWindowState} */
     WindowTestUtils.TestWindowState createWindowState(WindowManager.LayoutParams attrs,
             WindowToken token) {
-        return new WindowTestUtils.TestWindowState(sWm, sMockSession, sIWindow, attrs, token);
+        synchronized (sWm.mWindowMap) {
+            return new WindowTestUtils.TestWindowState(sWm, sMockSession, sIWindow, attrs, token);
+        }
     }
 
 }
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowTokenTests.java b/services/tests/servicestests/src/com/android/server/wm/WindowTokenTests.java
index 394e636..e3b7174 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowTokenTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowTokenTests.java
@@ -49,7 +49,7 @@
     @Test
     public void testAddWindow() throws Exception {
         final WindowTestUtils.TestWindowToken token =
-                new WindowTestUtils.TestWindowToken(0, mDisplayContent);
+                WindowTestUtils.createTestWindowToken(0, mDisplayContent);
 
         assertEquals(0, token.getWindowsCount());
 
@@ -79,7 +79,7 @@
     @Test
     public void testChildRemoval() throws Exception {
         final DisplayContent dc = mDisplayContent;
-        final WindowTestUtils.TestWindowToken token = new WindowTestUtils.TestWindowToken(0, dc);
+        final WindowTestUtils.TestWindowToken token = WindowTestUtils.createTestWindowToken(0, dc);
 
         assertEquals(token, dc.getWindowToken(token.token));
 
@@ -102,9 +102,8 @@
      */
     @Test
     public void testTokenRemovalProcess() throws Exception {
-        final WindowTestUtils.TestWindowToken token =
-                new WindowTestUtils.TestWindowToken(TYPE_TOAST, mDisplayContent,
-                        true /* persistOnEmpty */);
+        final WindowTestUtils.TestWindowToken token = WindowTestUtils.createTestWindowToken(
+                TYPE_TOAST, mDisplayContent, true /* persistOnEmpty */);
 
         // Verify that the token is on the display
         assertNotNull(mDisplayContent.getWindowToken(token.token));