Fixes use after free caused by delete in RootWindowController (2)

RootWindowController::CloseChildWindows() was explicitly deleting
windows. It should only do that for windows that are owned by the
parent, otherwise the window should be removed.

BUG=297028
TEST=covered by test now.
[email protected]
[email protected]

Review URL: https://codereview.chromium.org/25736004

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@226524 0039d316-1c4b-4281-b951-d872f2087c98
diff --git a/ash/root_window_controller.cc b/ash/root_window_controller.cc
index 9327cbd..a1b030eb 100644
--- a/ash/root_window_controller.cc
+++ b/ash/root_window_controller.cc
@@ -437,7 +437,8 @@
   workspace_controller_.reset();
   aura::client::SetTooltipClient(root_window_.get(), NULL);
 
-  // Remove all toplevel windows first.
+  // Explicitly destroy top level windows. We do this as during part of
+  // destruction such windows may query the RootWindow for state.
   std::queue<aura::Window*> non_toplevel_windows;
   non_toplevel_windows.push(root_window_.get());
   while (!non_toplevel_windows.empty()) {
@@ -446,6 +447,8 @@
     aura::WindowTracker toplevel_windows;
     for (size_t i = 0; i < non_toplevel_window->children().size(); ++i) {
       aura::Window* child = non_toplevel_window->children()[i];
+      if (!child->owned_by_parent())
+        continue;
       if (child->delegate())
         toplevel_windows.Add(child);
       else
@@ -455,8 +458,14 @@
       delete *toplevel_windows.windows().begin();
   }
   // And then remove the containers.
-  while (!root_window_->children().empty())
-    delete root_window_->children()[0];
+  while (!root_window_->children().empty()) {
+    aura::Window* window = root_window_->children()[0];
+    if (window->owned_by_parent()) {
+      delete window;
+    } else {
+      root_window_->RemoveChild(window);
+    }
+  }
 
   shelf_.reset(NULL);
 }