Add scoped autoreleasepool to tests and examples

This ensures ObjC objects do not leak. On non-Apple
platforms, the scope does nothing.

Fixed: dawn:546
Change-Id: Id43702e6536bf9cb37825a5449511e10cf0734f5
Reviewed-on: https://dawn-review.googlesource.com/c/dawn/+/55841
Commit-Queue: Austin Eng <enga@chromium.org>
Reviewed-by: Corentin Wallez <cwallez@chromium.org>
diff --git a/examples/Animometer.cpp b/examples/Animometer.cpp
index 4d573c4..1f3fa03 100644
--- a/examples/Animometer.cpp
+++ b/examples/Animometer.cpp
@@ -15,6 +15,7 @@
 #include "SampleUtils.h"
 
 #include "utils/ComboRenderPipelineDescriptor.h"
+#include "utils/ScopedAutoreleasePool.h"
 #include "utils/SystemUtils.h"
 #include "utils/WGPUHelpers.h"
 
@@ -184,6 +185,7 @@
     init();
 
     while (!ShouldQuit()) {
+        utils::ScopedAutoreleasePool pool;
         frame();
         utils::USleep(16000);
     }
diff --git a/examples/CHelloTriangle.cpp b/examples/CHelloTriangle.cpp
index 1caed99..b5a556b 100644
--- a/examples/CHelloTriangle.cpp
+++ b/examples/CHelloTriangle.cpp
@@ -14,6 +14,7 @@
 
 #include "SampleUtils.h"
 
+#include "utils/ScopedAutoreleasePool.h"
 #include "utils/SystemUtils.h"
 #include "utils/WGPUHelpers.h"
 
@@ -147,6 +148,7 @@
     init();
 
     while (!ShouldQuit()) {
+        utils::ScopedAutoreleasePool pool;
         frame();
         utils::USleep(16000);
     }
diff --git a/examples/ComputeBoids.cpp b/examples/ComputeBoids.cpp
index 0061368..cb19387 100644
--- a/examples/ComputeBoids.cpp
+++ b/examples/ComputeBoids.cpp
@@ -15,6 +15,7 @@
 #include "SampleUtils.h"
 
 #include "utils/ComboRenderPipelineDescriptor.h"
+#include "utils/ScopedAutoreleasePool.h"
 #include "utils/SystemUtils.h"
 #include "utils/WGPUHelpers.h"
 
@@ -324,6 +325,7 @@
     init();
 
     while (!ShouldQuit()) {
+        utils::ScopedAutoreleasePool pool;
         frame();
         utils::USleep(16000);
     }
diff --git a/examples/CppHelloTriangle.cpp b/examples/CppHelloTriangle.cpp
index ea3c6eb..cf5f73c 100644
--- a/examples/CppHelloTriangle.cpp
+++ b/examples/CppHelloTriangle.cpp
@@ -15,6 +15,7 @@
 #include "SampleUtils.h"
 
 #include "utils/ComboRenderPipelineDescriptor.h"
+#include "utils/ScopedAutoreleasePool.h"
 #include "utils/SystemUtils.h"
 #include "utils/WGPUHelpers.h"
 
@@ -176,6 +177,7 @@
     init();
 
     while (!ShouldQuit()) {
+        utils::ScopedAutoreleasePool pool;
         frame();
         utils::USleep(16000);
     }
diff --git a/examples/CubeReflection.cpp b/examples/CubeReflection.cpp
index 92c5c6a..f54766d 100644
--- a/examples/CubeReflection.cpp
+++ b/examples/CubeReflection.cpp
@@ -15,6 +15,7 @@
 #include "SampleUtils.h"
 
 #include "utils/ComboRenderPipelineDescriptor.h"
+#include "utils/ScopedAutoreleasePool.h"
 #include "utils/SystemUtils.h"
 #include "utils/WGPUHelpers.h"
 
@@ -301,6 +302,7 @@
     init();
 
     while (!ShouldQuit()) {
+        utils::ScopedAutoreleasePool pool;
         frame();
         utils::USleep(16000);
     }
diff --git a/examples/ManualSwapChainTest.cpp b/examples/ManualSwapChainTest.cpp
index e282af4..1c7d9dd 100644
--- a/examples/ManualSwapChainTest.cpp
+++ b/examples/ManualSwapChainTest.cpp
@@ -55,6 +55,7 @@
 #include "common/Log.h"
 #include "utils/ComboRenderPipelineDescriptor.h"
 #include "utils/GLFWUtils.h"
+#include "utils/ScopedAutoreleasePool.h"
 #include "utils/WGPUHelpers.h"
 
 #include <dawn/dawn_proc.h>
@@ -334,6 +335,7 @@
     AddWindow();
 
     while (windows.size() != 0) {
+        utils::ScopedAutoreleasePool pool;
         glfwPollEvents();
 
         for (auto it = windows.begin(); it != windows.end();) {
diff --git a/src/dawn_native/metal/CommandRecordingContext.mm b/src/dawn_native/metal/CommandRecordingContext.mm
index 6f2aefa..decb650 100644
--- a/src/dawn_native/metal/CommandRecordingContext.mm
+++ b/src/dawn_native/metal/CommandRecordingContext.mm
@@ -61,7 +61,7 @@
 
             // The encoder is created autoreleased. Retain it to avoid the autoreleasepool from
             // draining from under us.
-            mBlit = [*mCommands blitCommandEncoder];
+            mBlit.Acquire([[*mCommands blitCommandEncoder] retain]);
         }
         return mBlit.Get();
     }
@@ -82,9 +82,9 @@
         ASSERT(!mInEncoder);
 
         mInEncoder = true;
-        // The encoder is created autoreleased. Retain it to avoid the autoreleasepool from draining
-        // from under us.
-        mCompute = [*mCommands computeCommandEncoder];
+        // The encoder is created autoreleased. Retain it to avoid the autoreleasepool from
+        // draining from under us.
+        mCompute.Acquire([[*mCommands computeCommandEncoder] retain]);
         return mCompute.Get();
     }
 
@@ -104,9 +104,9 @@
         ASSERT(!mInEncoder);
 
         mInEncoder = true;
-        // The encoder is created autoreleased. Retain it to avoid the autoreleasepool from draining
-        // from under us.
-        mRender = [*mCommands renderCommandEncoderWithDescriptor:descriptor];
+        // The encoder is created autoreleased. Retain it to avoid the autoreleasepool from
+        // draining from under us.
+        mRender.Acquire([[*mCommands renderCommandEncoderWithDescriptor:descriptor] retain]);
         return mRender.Get();
     }
 
diff --git a/src/dawn_native/metal/DeviceMTL.mm b/src/dawn_native/metal/DeviceMTL.mm
index 98b1f77..ea7e09c 100644
--- a/src/dawn_native/metal/DeviceMTL.mm
+++ b/src/dawn_native/metal/DeviceMTL.mm
@@ -308,7 +308,8 @@
             // The MTLCommandBuffer will be autoreleased by default.
             // The autorelease pool may drain before the command buffer is submitted. Retain so it
             // stays alive.
-            mCommandContext = CommandRecordingContext([*mCommandQueue commandBuffer]);
+            mCommandContext =
+                CommandRecordingContext(AcquireNSPRef([[*mCommandQueue commandBuffer] retain]));
         }
         return &mCommandContext;
     }
diff --git a/src/tests/DawnTest.h b/src/tests/DawnTest.h
index c59f7f5..aa15e33 100644
--- a/src/tests/DawnTest.h
+++ b/src/tests/DawnTest.h
@@ -23,6 +23,7 @@
 #include "dawn_native/DawnNative.h"
 #include "tests/ParamGenerator.h"
 #include "tests/ToggleParser.h"
+#include "utils/ScopedAutoreleasePool.h"
 
 #include <dawn_platform/DawnPlatform.h>
 #include <gtest/gtest.h>
@@ -478,6 +479,7 @@
     const wgpu::AdapterProperties& GetAdapterProperties() const;
 
   private:
+    utils::ScopedAutoreleasePool mObjCAutoreleasePool;
     AdapterTestParam mParam;
     std::unique_ptr<utils::WireHelper> mWireHelper;
 
diff --git a/src/utils/BUILD.gn b/src/utils/BUILD.gn
index 1bd4073..ba8a0f4 100644
--- a/src/utils/BUILD.gn
+++ b/src/utils/BUILD.gn
@@ -71,6 +71,7 @@
     "ComboRenderPipelineDescriptor.cpp",
     "ComboRenderPipelineDescriptor.h",
     "PlatformDebugLogger.h",
+    "ScopedAutoreleasePool.h",
     "SystemUtils.cpp",
     "SystemUtils.h",
     "TerribleCommandBuffer.cpp",
@@ -114,6 +115,12 @@
     sources += [ "PosixTimer.cpp" ]
   }
 
+  if (is_mac) {
+    sources += [ "ScopedAutoreleasePool.mm" ]
+  } else {
+    sources += [ "ScopedAutoreleasePool.cpp" ]
+  }
+
   if (dawn_supports_glfw_for_windowing) {
     sources += [
       "GLFWUtils.cpp",
diff --git a/src/utils/ScopedAutoreleasePool.cpp b/src/utils/ScopedAutoreleasePool.cpp
new file mode 100644
index 0000000..0cee799
--- /dev/null
+++ b/src/utils/ScopedAutoreleasePool.cpp
@@ -0,0 +1,34 @@
+// Copyright 2021 The Dawn Authors
+//
+// 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.
+
+#include "utils/ScopedAutoreleasePool.h"
+
+#include "common/Compiler.h"
+
+namespace utils {
+
+    ScopedAutoreleasePool::ScopedAutoreleasePool() : mPool(nullptr) {
+        DAWN_UNUSED(mPool);
+    }
+
+    ScopedAutoreleasePool::~ScopedAutoreleasePool() = default;
+
+    ScopedAutoreleasePool::ScopedAutoreleasePool(ScopedAutoreleasePool&& rhs) {
+    }
+
+    ScopedAutoreleasePool& ScopedAutoreleasePool::operator=(ScopedAutoreleasePool&& rhs) {
+        return *this;
+    }
+
+}  // namespace utils
diff --git a/src/utils/ScopedAutoreleasePool.h b/src/utils/ScopedAutoreleasePool.h
new file mode 100644
index 0000000..e9c945d
--- /dev/null
+++ b/src/utils/ScopedAutoreleasePool.h
@@ -0,0 +1,61 @@
+// Copyright 2021 The Dawn Authors
+//
+// 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.
+
+#ifndef UTILS_SCOPEDAUTORELEASEPOOL_H_
+#define UTILS_SCOPEDAUTORELEASEPOOL_H_
+
+#include "common/Compiler.h"
+
+#include <cstddef>
+
+namespace utils {
+
+    /**
+     * ScopedAutoreleasePool is a scoped class which initializes an NSAutoreleasePool on
+     * creation, and drains it on destruction. On non-Apple platforms, ScopedAutoreleasePool
+     * is a no-op.
+     *
+     * An autoreleasepool is needed when using protocol objects in Objective-C because Cocoa
+     * expects a pool to always be available in each thread. If a pool is not available, then
+     * autoreleased objects will never be released and will leak.
+     *
+     * In long-running blocks of code or loops, it is important to periodically create and drain
+     * autorelease pools so that memory is recycled. In Dawn's tests, we have an autoreleasepool
+     * per-test. In graphics applications it's advised to create an autoreleasepool around the
+     * frame loop. Ex.)
+     *   void frame() {
+     *     // Any protocol objects will be reclaimed when this object falls out of scope.
+     *     utils::ScopedAutoreleasePool pool;
+     *
+     *     // do rendering ...
+     *   }
+     */
+    class DAWN_NO_DISCARD ScopedAutoreleasePool {
+      public:
+        ScopedAutoreleasePool();
+        ~ScopedAutoreleasePool();
+
+        ScopedAutoreleasePool(const ScopedAutoreleasePool&) = delete;
+        ScopedAutoreleasePool& operator=(const ScopedAutoreleasePool&) = delete;
+
+        ScopedAutoreleasePool(ScopedAutoreleasePool&&);
+        ScopedAutoreleasePool& operator=(ScopedAutoreleasePool&&);
+
+      private:
+        void* mPool = nullptr;
+    };
+
+}  // namespace utils
+
+#endif  // UTILS_SCOPEDAUTORELEASEPOOL_H_
diff --git a/src/utils/ScopedAutoreleasePool.mm b/src/utils/ScopedAutoreleasePool.mm
new file mode 100644
index 0000000..f649f3e
--- /dev/null
+++ b/src/utils/ScopedAutoreleasePool.mm
@@ -0,0 +1,44 @@
+// Copyright 2021 The Dawn Authors
+//
+// 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.
+
+#include "utils/ScopedAutoreleasePool.h"
+
+#import <Foundation/Foundation.h>
+
+namespace utils {
+
+    ScopedAutoreleasePool::ScopedAutoreleasePool() : mPool([[NSAutoreleasePool alloc] init]) {
+    }
+
+    ScopedAutoreleasePool::~ScopedAutoreleasePool() {
+        if (mPool != nullptr) {
+            [static_cast<NSAutoreleasePool*>(mPool) release];
+            mPool = nullptr;
+        }
+    }
+
+    ScopedAutoreleasePool::ScopedAutoreleasePool(ScopedAutoreleasePool&& rhs) {
+        mPool = rhs.mPool;
+        rhs.mPool = nullptr;
+    }
+
+    ScopedAutoreleasePool& ScopedAutoreleasePool::operator=(ScopedAutoreleasePool&& rhs) {
+        if (&rhs != this) {
+            mPool = rhs.mPool;
+            rhs.mPool = nullptr;
+        }
+        return *this;
+    }
+
+}  // namespace utils