Merge changes Iae143d11,I400c347b,I0639df17,I6d56160d

* changes:
  graphics: add a basic test for IMapper::lockFlex
  graphics: clean up composer VTS tests
  graphics: clean up mapper VTS tests
  graphics: clean up allocator VTS tests
diff --git a/graphics/allocator/2.0/vts/functional/Android.bp b/graphics/allocator/2.0/vts/functional/Android.bp
index fdc91ae..c3a16fb 100644
--- a/graphics/allocator/2.0/vts/functional/Android.bp
+++ b/graphics/allocator/2.0/vts/functional/Android.bp
@@ -14,6 +14,25 @@
 // limitations under the License.
 //
 
+cc_library_static {
+    name: "libVtsHalGraphicsAllocatorTestUtils",
+    srcs: ["VtsHalGraphicsAllocatorTestUtils.cpp"],
+    shared_libs: [
+        "android.hardware.graphics.allocator@2.0",
+    ],
+    static_libs: [
+        "VtsHalHidlTargetBaseTest",
+    ],
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+        "-O0",
+        "-g",
+    ],
+    export_include_dirs: ["."],
+}
+
 cc_test {
     name: "VtsHalGraphicsAllocatorV2_0TargetTest",
     srcs: ["VtsHalGraphicsAllocatorV2_0TargetTest.cpp"],
@@ -27,8 +46,14 @@
         "libutils",
         "android.hardware.graphics.allocator@2.0",
     ],
-    static_libs: ["VtsHalHidlTargetBaseTest"],
+    static_libs: [
+        "libVtsHalGraphicsAllocatorTestUtils",
+        "VtsHalHidlTargetBaseTest",
+    ],
     cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
         "-O0",
         "-g",
     ]
diff --git a/graphics/allocator/2.0/vts/functional/VtsHalGraphicsAllocatorTestUtils.cpp b/graphics/allocator/2.0/vts/functional/VtsHalGraphicsAllocatorTestUtils.cpp
new file mode 100644
index 0000000..141743b
--- /dev/null
+++ b/graphics/allocator/2.0/vts/functional/VtsHalGraphicsAllocatorTestUtils.cpp
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#include <VtsHalHidlTargetBaseTest.h>
+
+#include "VtsHalGraphicsAllocatorTestUtils.h"
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace allocator {
+namespace V2_0 {
+namespace tests {
+
+Allocator::Allocator() { init(); }
+
+void Allocator::init() {
+  mAllocator = ::testing::VtsHalHidlTargetBaseTest::getService<IAllocator>();
+  ASSERT_NE(nullptr, mAllocator.get()) << "failed to get allocator service";
+
+  std::vector<IAllocator::Capability> capabilities = getCapabilities();
+  mCapabilities.insert(capabilities.begin(), capabilities.end());
+}
+
+sp<IAllocator> Allocator::getRaw() const { return mAllocator; }
+
+bool Allocator::hasCapability(IAllocator::Capability capability) const {
+  return mCapabilities.count(capability) > 0;
+}
+
+std::vector<IAllocator::Capability> Allocator::getCapabilities() {
+  std::vector<IAllocator::Capability> capabilities;
+  mAllocator->getCapabilities(
+      [&](const auto& tmpCapabilities) { capabilities = tmpCapabilities; });
+
+  return capabilities;
+}
+
+std::string Allocator::dumpDebugInfo() {
+  std::string debugInfo;
+  mAllocator->dumpDebugInfo(
+      [&](const auto& tmpDebugInfo) { debugInfo = tmpDebugInfo.c_str(); });
+
+  return debugInfo;
+}
+
+std::unique_ptr<AllocatorClient> Allocator::createClient() {
+  std::unique_ptr<AllocatorClient> client;
+  mAllocator->createClient([&](const auto& tmpError, const auto& tmpClient) {
+    ASSERT_EQ(Error::NONE, tmpError) << "failed to create client";
+    client = std::make_unique<AllocatorClient>(tmpClient);
+  });
+
+  return client;
+}
+
+AllocatorClient::AllocatorClient(const sp<IAllocatorClient>& client)
+    : mClient(client) {}
+
+AllocatorClient::~AllocatorClient() {
+  for (auto buffer : mBuffers) {
+    EXPECT_EQ(Error::NONE, mClient->free(buffer))
+        << "failed to free buffer " << buffer;
+  }
+  mBuffers.clear();
+
+  for (auto descriptor : mDescriptors) {
+    EXPECT_EQ(Error::NONE, mClient->destroyDescriptor(descriptor))
+        << "failed to destroy descriptor " << descriptor;
+  }
+  mDescriptors.clear();
+}
+
+sp<IAllocatorClient> AllocatorClient::getRaw() const { return mClient; }
+
+BufferDescriptor AllocatorClient::createDescriptor(
+    const IAllocatorClient::BufferDescriptorInfo& info) {
+  BufferDescriptor descriptor = 0;
+  mClient->createDescriptor(
+      info, [&](const auto& tmpError, const auto& tmpDescriptor) {
+        ASSERT_EQ(Error::NONE, tmpError) << "failed to create descriptor";
+        descriptor = tmpDescriptor;
+
+        EXPECT_TRUE(mDescriptors.insert(descriptor).second)
+            << "duplicated descriptor id " << descriptor;
+      });
+
+  return descriptor;
+}
+
+void AllocatorClient::destroyDescriptor(BufferDescriptor descriptor) {
+  ASSERT_EQ(Error::NONE, mClient->destroyDescriptor(descriptor))
+      << "failed to destroy descriptor " << descriptor;
+
+  mDescriptors.erase(descriptor);
+}
+
+Error AllocatorClient::testAllocate(
+    const std::vector<BufferDescriptor>& descriptors) {
+  return mClient->testAllocate(descriptors);
+}
+
+bool AllocatorClient::testAllocate(BufferDescriptor descriptor) {
+  std::vector<BufferDescriptor> descriptors(1, descriptor);
+  Error error = testAllocate(descriptors);
+  return (error == Error::NONE || error == Error::NOT_SHARED);
+}
+
+Error AllocatorClient::allocate(
+    const std::vector<BufferDescriptor>& descriptors,
+    std::vector<Buffer>& buffers) {
+  Error error = Error::NO_RESOURCES;
+  mClient->allocate(descriptors, [&](const auto& tmpError,
+                                     const auto& tmpBuffers) {
+    ASSERT_TRUE(tmpError == Error::NONE || tmpError == Error::NOT_SHARED)
+        << "failed to allocate buffer";
+    ASSERT_EQ(descriptors.size(), tmpBuffers.size()) << "invalid buffer count";
+
+    error = tmpError;
+    buffers = tmpBuffers;
+
+    for (auto buffer : buffers) {
+      EXPECT_TRUE(mBuffers.insert(buffer).second)
+          << "duplicated buffer id " << buffer;
+    }
+  });
+
+  return error;
+}
+
+Buffer AllocatorClient::allocate(BufferDescriptor descriptor) {
+  std::vector<BufferDescriptor> descriptors(1, descriptor);
+  std::vector<Buffer> buffers;
+  allocate(descriptors, buffers);
+  if (::testing::Test::HasFatalFailure()) {
+    return 0;
+  }
+
+  return buffers[0];
+}
+
+void AllocatorClient::free(Buffer buffer) {
+  ASSERT_EQ(Error::NONE, mClient->free(buffer))
+      << "failed to free buffer " << buffer;
+
+  mBuffers.erase(buffer);
+}
+
+native_handle_t* AllocatorClient::exportHandle(BufferDescriptor descriptor,
+                                               Buffer buffer) {
+  native_handle_t* handle;
+  mClient->exportHandle(
+      descriptor, buffer, [&](const auto& tmpError, const auto& tmpHandle) {
+        ASSERT_EQ(Error::NONE, tmpError) << "failed to export buffer handle";
+        ASSERT_NE(nullptr, tmpHandle.getNativeHandle())
+            << "invalid buffer handle";
+
+        handle = native_handle_clone(tmpHandle.getNativeHandle());
+        ASSERT_NE(nullptr, handle) << "failed to clone handle";
+      });
+
+  return handle;
+}
+
+}  // namespace tests
+}  // namespace V2_0
+}  // namespace allocator
+}  // namespace graphics
+}  // namespace hardware
+}  // namespace android
diff --git a/graphics/allocator/2.0/vts/functional/VtsHalGraphicsAllocatorTestUtils.h b/graphics/allocator/2.0/vts/functional/VtsHalGraphicsAllocatorTestUtils.h
new file mode 100644
index 0000000..c9bfe8f
--- /dev/null
+++ b/graphics/allocator/2.0/vts/functional/VtsHalGraphicsAllocatorTestUtils.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#ifndef VTS_HAL_GRAPHICS_ALLOCATOR_UTILS
+#define VTS_HAL_GRAPHICS_ALLOCATOR_UTILS
+
+#include <memory>
+#include <string>
+#include <unordered_set>
+#include <vector>
+
+#include <android/hardware/graphics/allocator/2.0/IAllocator.h>
+#include <utils/StrongPointer.h>
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace allocator {
+namespace V2_0 {
+namespace tests {
+
+class AllocatorClient;
+
+// A wrapper to IAllocator.
+class Allocator {
+ public:
+  Allocator();
+
+  sp<IAllocator> getRaw() const;
+
+  // Returns true when the allocator supports the specified capability.
+  bool hasCapability(IAllocator::Capability capability) const;
+
+  std::vector<IAllocator::Capability> getCapabilities();
+  std::string dumpDebugInfo();
+  std::unique_ptr<AllocatorClient> createClient();
+
+ private:
+  void init();
+
+  sp<IAllocator> mAllocator;
+  std::unordered_set<IAllocator::Capability> mCapabilities;
+};
+
+// A wrapper to IAllocatorClient.
+class AllocatorClient {
+ public:
+  AllocatorClient(const sp<IAllocatorClient>& client);
+  ~AllocatorClient();
+
+  sp<IAllocatorClient> getRaw() const;
+
+  BufferDescriptor createDescriptor(
+      const IAllocatorClient::BufferDescriptorInfo& info);
+  void destroyDescriptor(BufferDescriptor descriptor);
+
+  Error testAllocate(const std::vector<BufferDescriptor>& descriptors);
+  bool testAllocate(BufferDescriptor descriptor);
+
+  Error allocate(const std::vector<BufferDescriptor>& descriptors,
+                 std::vector<Buffer>& buffers);
+  Buffer allocate(BufferDescriptor descriptor);
+  void free(Buffer buffer);
+
+  // Returns a handle to the buffer.  The ownership of the handle is
+  // transferred to the caller.
+  native_handle_t* exportHandle(BufferDescriptor descriptor, Buffer buffer);
+
+ private:
+  sp<IAllocatorClient> mClient;
+
+  // Keep track of all descriptors and buffers.  When a test fails with
+  // ASSERT_*, the destructor will clean up the resources for the test.
+  std::unordered_set<BufferDescriptor> mDescriptors;
+  std::unordered_set<Buffer> mBuffers;
+};
+
+}  // namespace tests
+}  // namespace V2_0
+}  // namespace allocator
+}  // namespace graphics
+}  // namespace hardware
+}  // namespace android
+
+#endif  // VTS_HAL_GRAPHICS_ALLOCATOR_UTILS
diff --git a/graphics/allocator/2.0/vts/functional/VtsHalGraphicsAllocatorV2_0TargetTest.cpp b/graphics/allocator/2.0/vts/functional/VtsHalGraphicsAllocatorV2_0TargetTest.cpp
index a8ced8c..2e3ed73 100644
--- a/graphics/allocator/2.0/vts/functional/VtsHalGraphicsAllocatorV2_0TargetTest.cpp
+++ b/graphics/allocator/2.0/vts/functional/VtsHalGraphicsAllocatorV2_0TargetTest.cpp
@@ -16,12 +16,11 @@
 
 #define LOG_TAG "graphics_allocator_hidl_hal_test"
 
-#include <unordered_set>
-
 #include <android-base/logging.h>
-#include <android/hardware/graphics/allocator/2.0/IAllocator.h>
 #include <VtsHalHidlTargetBaseTest.h>
 
+#include "VtsHalGraphicsAllocatorTestUtils.h"
+
 namespace android {
 namespace hardware {
 namespace graphics {
@@ -34,55 +33,18 @@
 
 #define CHECK_FEATURE_OR_SKIP(FEATURE_NAME)                 \
   do {                                                      \
-    if (!hasCapability(FEATURE_NAME)) {                     \
+    if (!mAllocator->hasCapability(FEATURE_NAME)) {         \
       std::cout << "[  SKIPPED ] Feature " << #FEATURE_NAME \
                 << " not supported" << std::endl;           \
       return;                                               \
     }                                                       \
   } while (0)
 
-class TempDescriptor {
- public:
-  TempDescriptor(const sp<IAllocatorClient>& client,
-                 const IAllocatorClient::BufferDescriptorInfo& info)
-      : mClient(client), mError(Error::NO_RESOURCES) {
-    mClient->createDescriptor(
-        info, [&](const auto& tmpError, const auto& tmpDescriptor) {
-          mError = tmpError;
-          mDescriptor = tmpDescriptor;
-        });
-  }
-
-  ~TempDescriptor() {
-    if (mError == Error::NONE) {
-      mClient->destroyDescriptor(mDescriptor);
-    }
-  }
-
-  bool isValid() const { return (mError == Error::NONE); }
-
-  operator BufferDescriptor() const { return mDescriptor; }
-
- private:
-  sp<IAllocatorClient> mClient;
-  Error mError;
-  BufferDescriptor mDescriptor;
-};
-
 class GraphicsAllocatorHidlTest : public ::testing::VtsHalHidlTargetBaseTest {
  protected:
   void SetUp() override {
-    mAllocator = ::testing::VtsHalHidlTargetBaseTest::getService<IAllocator>();
-    ASSERT_NE(mAllocator, nullptr);
-
-    mAllocator->createClient([this](const auto& error, const auto& client) {
-      if (error == Error::NONE) {
-        mClient = client;
-      }
-    });
-    ASSERT_NE(mClient, nullptr);
-
-    initCapabilities();
+    ASSERT_NO_FATAL_FAILURE(mAllocator = std::make_unique<Allocator>());
+    ASSERT_NO_FATAL_FAILURE(mClient = mAllocator->createClient());
 
     mDummyDescriptorInfo.width = 64;
     mDummyDescriptorInfo.height = 64;
@@ -96,66 +58,27 @@
 
   void TearDown() override {}
 
-  /**
-   * Initialize the set of supported capabilities.
-   */
-  void initCapabilities() {
-    mAllocator->getCapabilities([this](const auto& capabilities) {
-      std::vector<IAllocator::Capability> caps = capabilities;
-      mCapabilities.insert(caps.cbegin(), caps.cend());
-    });
-  }
-
-  /**
-   * Test whether a capability is supported.
-   */
-  bool hasCapability(IAllocator::Capability capability) const {
-    return (mCapabilities.count(capability) > 0);
-  }
-
-  sp<IAllocator> mAllocator;
-  sp<IAllocatorClient> mClient;
+  std::unique_ptr<Allocator> mAllocator;
+  std::unique_ptr<AllocatorClient> mClient;
   IAllocatorClient::BufferDescriptorInfo mDummyDescriptorInfo{};
-
- private:
-  std::unordered_set<IAllocator::Capability> mCapabilities;
 };
 
 TEST_F(GraphicsAllocatorHidlTest, GetCapabilities) {
-  auto ret = mAllocator->getCapabilities([](const auto& capabilities) {
-    std::vector<IAllocator::Capability> caps = capabilities;
-    for (auto cap : caps) {
-      EXPECT_NE(IAllocator::Capability::INVALID, cap);
-    }
-  });
-
-  ASSERT_TRUE(ret.isOk());
+  auto capabilities = mAllocator->getCapabilities();
+  for (auto cap : capabilities) {
+    EXPECT_NE(IAllocator::Capability::INVALID, cap);
+  }
 }
 
 TEST_F(GraphicsAllocatorHidlTest, DumpDebugInfo) {
-  auto ret = mAllocator->dumpDebugInfo([](const auto&) {
-    // nothing to do
-  });
-
-  ASSERT_TRUE(ret.isOk());
+  mAllocator->dumpDebugInfo();
 }
 
 TEST_F(GraphicsAllocatorHidlTest, CreateDestroyDescriptor) {
-  Error error;
   BufferDescriptor descriptor;
-  auto ret = mClient->createDescriptor(
-      mDummyDescriptorInfo,
-      [&](const auto& tmpError, const auto& tmpDescriptor) {
-        error = tmpError;
-        descriptor = tmpDescriptor;
-      });
-
-  ASSERT_TRUE(ret.isOk());
-  ASSERT_EQ(Error::NONE, error);
-
-  auto err_ret = mClient->destroyDescriptor(descriptor);
-  ASSERT_TRUE(err_ret.isOk());
-  ASSERT_EQ(Error::NONE, static_cast<Error>(err_ret));
+  ASSERT_NO_FATAL_FAILURE(descriptor =
+                              mClient->createDescriptor(mDummyDescriptorInfo));
+  mClient->destroyDescriptor(descriptor);
 }
 
 /**
@@ -164,18 +87,11 @@
 TEST_F(GraphicsAllocatorHidlTest, TestAllocateBasic) {
   CHECK_FEATURE_OR_SKIP(IAllocator::Capability::TEST_ALLOCATE);
 
-  TempDescriptor descriptor(mClient, mDummyDescriptorInfo);
-  ASSERT_TRUE(descriptor.isValid());
+  BufferDescriptor descriptor;
+  ASSERT_NO_FATAL_FAILURE(descriptor =
+                              mClient->createDescriptor(mDummyDescriptorInfo));
 
-  hidl_vec<BufferDescriptor> descriptors;
-  descriptors.resize(1);
-  descriptors[0] = descriptor;
-
-  auto ret = mClient->testAllocate(descriptors);
-  ASSERT_TRUE(ret.isOk());
-
-  auto error = static_cast<Error>(ret);
-  ASSERT_TRUE(error == Error::NONE || error == Error::NOT_SHARED);
+  ASSERT_TRUE(mClient->testAllocate(descriptor));
 }
 
 /**
@@ -184,18 +100,16 @@
 TEST_F(GraphicsAllocatorHidlTest, TestAllocateArray) {
   CHECK_FEATURE_OR_SKIP(IAllocator::Capability::TEST_ALLOCATE);
 
-  TempDescriptor descriptor(mClient, mDummyDescriptorInfo);
-  ASSERT_TRUE(descriptor.isValid());
+  BufferDescriptor descriptor;
+  ASSERT_NO_FATAL_FAILURE(descriptor =
+                              mClient->createDescriptor(mDummyDescriptorInfo));
 
   hidl_vec<BufferDescriptor> descriptors;
   descriptors.resize(2);
   descriptors[0] = descriptor;
   descriptors[1] = descriptor;
 
-  auto ret = mClient->testAllocate(descriptors);
-  ASSERT_TRUE(ret.isOk());
-
-  auto error = static_cast<Error>(ret);
+  auto error = mClient->testAllocate(descriptors);
   ASSERT_TRUE(error == Error::NONE || error == Error::NOT_SHARED);
 }
 
@@ -203,41 +117,27 @@
  * Test allocate/free with a single buffer descriptor.
  */
 TEST_F(GraphicsAllocatorHidlTest, AllocateFreeBasic) {
-  TempDescriptor descriptor(mClient, mDummyDescriptorInfo);
-  ASSERT_TRUE(descriptor.isValid());
+  BufferDescriptor descriptor;
+  ASSERT_NO_FATAL_FAILURE(descriptor =
+                              mClient->createDescriptor(mDummyDescriptorInfo));
 
-  hidl_vec<BufferDescriptor> descriptors;
-  descriptors.resize(1);
-  descriptors[0] = descriptor;
+  Buffer buffer;
+  ASSERT_NO_FATAL_FAILURE(buffer = mClient->allocate(descriptor));
 
-  Error error;
-  std::vector<Buffer> buffers;
-  auto ret = mClient->allocate(
-      descriptors, [&](const auto& tmpError, const auto& tmpBuffers) {
-        error = tmpError;
-        buffers = tmpBuffers;
-      });
-
-  ASSERT_TRUE(ret.isOk());
-  ASSERT_TRUE(error == Error::NONE || error == Error::NOT_SHARED);
-  EXPECT_EQ(1u, buffers.size());
-
-  if (!buffers.empty()) {
-    auto err_ret = mClient->free(buffers[0]);
-    EXPECT_TRUE(err_ret.isOk());
-    EXPECT_EQ(Error::NONE, static_cast<Error>(err_ret));
-  }
+  mClient->free(buffer);
 }
 
 /**
  * Test allocate/free with an array of buffer descriptors.
  */
 TEST_F(GraphicsAllocatorHidlTest, AllocateFreeArray) {
-  TempDescriptor descriptor1(mClient, mDummyDescriptorInfo);
-  ASSERT_TRUE(descriptor1.isValid());
+  BufferDescriptor descriptor1;
+  ASSERT_NO_FATAL_FAILURE(descriptor1 =
+                              mClient->createDescriptor(mDummyDescriptorInfo));
 
-  TempDescriptor descriptor2(mClient, mDummyDescriptorInfo);
-  ASSERT_TRUE(descriptor2.isValid());
+  BufferDescriptor descriptor2;
+  ASSERT_NO_FATAL_FAILURE(descriptor2 =
+                              mClient->createDescriptor(mDummyDescriptorInfo));
 
   hidl_vec<BufferDescriptor> descriptors;
   descriptors.resize(3);
@@ -245,54 +145,27 @@
   descriptors[1] = descriptor1;
   descriptors[2] = descriptor2;
 
-  Error error;
   std::vector<Buffer> buffers;
-  auto ret = mClient->allocate(
-      descriptors, [&](const auto& tmpError, const auto& tmpBuffers) {
-        error = tmpError;
-        buffers = tmpBuffers;
-      });
-
-  ASSERT_TRUE(ret.isOk());
-  ASSERT_TRUE(error == Error::NONE || error == Error::NOT_SHARED);
-  EXPECT_EQ(descriptors.size(), buffers.size());
+  ASSERT_NO_FATAL_FAILURE(mClient->allocate(descriptors, buffers));
 
   for (auto buf : buffers) {
-    auto err_ret = mClient->free(buf);
-    EXPECT_TRUE(err_ret.isOk());
-    EXPECT_EQ(Error::NONE, static_cast<Error>(err_ret));
+    mClient->free(buf);
   }
 }
 
 TEST_F(GraphicsAllocatorHidlTest, ExportHandle) {
-  TempDescriptor descriptor(mClient, mDummyDescriptorInfo);
-  ASSERT_TRUE(descriptor.isValid());
+  BufferDescriptor descriptor;
+  ASSERT_NO_FATAL_FAILURE(descriptor =
+                              mClient->createDescriptor(mDummyDescriptorInfo));
 
-  hidl_vec<BufferDescriptor> descriptors;
-  descriptors.resize(1);
-  descriptors[0] = descriptor;
+  Buffer buffer;
+  ASSERT_NO_FATAL_FAILURE(buffer = mClient->allocate(descriptor));
 
-  Error error;
-  std::vector<Buffer> buffers;
-  auto ret = mClient->allocate(
-      descriptors, [&](const auto& tmpError, const auto& tmpBuffers) {
-        error = tmpError;
-        buffers = tmpBuffers;
-      });
+  native_handle_t* handle;
+  ASSERT_NO_FATAL_FAILURE(handle = mClient->exportHandle(descriptor, buffer));
 
-  ASSERT_TRUE(ret.isOk());
-  ASSERT_TRUE(error == Error::NONE || error == Error::NOT_SHARED);
-  ASSERT_EQ(1u, buffers.size());
-
-  ret = mClient->exportHandle(
-      descriptors[0], buffers[0],
-      [&](const auto& tmpError, const auto&) { error = tmpError; });
-  EXPECT_TRUE(ret.isOk());
-  EXPECT_EQ(Error::NONE, error);
-
-  auto err_ret = mClient->free(buffers[0]);
-  EXPECT_TRUE(err_ret.isOk());
-  EXPECT_EQ(Error::NONE, static_cast<Error>(err_ret));
+  native_handle_close(handle);
+  native_handle_delete(handle);
 }
 
 }  // namespace anonymous
diff --git a/graphics/composer/2.1/vts/functional/Android.bp b/graphics/composer/2.1/vts/functional/Android.bp
index 9be04d1..825bf07 100644
--- a/graphics/composer/2.1/vts/functional/Android.bp
+++ b/graphics/composer/2.1/vts/functional/Android.bp
@@ -14,6 +14,23 @@
 // limitations under the License.
 //
 
+cc_library_static {
+    name: "libVtsHalGraphicsComposerTestUtils",
+    srcs: ["VtsHalGraphicsComposerTestUtils.cpp"],
+    shared_libs: ["android.hardware.graphics.composer@2.1"],
+    static_libs: [
+        "VtsHalHidlTargetBaseTest",
+    ],
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+        "-O0",
+        "-g",
+    ],
+    export_include_dirs: ["."],
+}
+
 cc_test {
     name: "VtsHalGraphicsComposerV2_1TargetTest",
     srcs: ["VtsHalGraphicsComposerV2_1TargetTest.cpp"],
@@ -31,8 +48,17 @@
         "libsync",
         "libutils",
     ],
-    static_libs: ["VtsHalHidlTargetBaseTest", "libhwcomposer-command-buffer"],
+    static_libs: [
+        "libhwcomposer-command-buffer",
+        "libVtsHalGraphicsAllocatorTestUtils",
+        "libVtsHalGraphicsComposerTestUtils",
+        "libVtsHalGraphicsMapperTestUtils",
+        "VtsHalHidlTargetBaseTest",
+    ],
     cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
         "-O0",
         "-g",
     ]
diff --git a/graphics/composer/2.1/vts/functional/VtsHalGraphicsComposerTestUtils.cpp b/graphics/composer/2.1/vts/functional/VtsHalGraphicsComposerTestUtils.cpp
new file mode 100644
index 0000000..5b6a108
--- /dev/null
+++ b/graphics/composer/2.1/vts/functional/VtsHalGraphicsComposerTestUtils.cpp
@@ -0,0 +1,300 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#include <VtsHalHidlTargetBaseTest.h>
+
+#include "VtsHalGraphicsComposerTestUtils.h"
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace composer {
+namespace V2_1 {
+namespace tests {
+
+Composer::Composer() { init(); }
+
+void Composer::init() {
+  mComposer = ::testing::VtsHalHidlTargetBaseTest::getService<IComposer>();
+  ASSERT_NE(nullptr, mComposer.get()) << "failed to get composer service";
+
+  std::vector<IComposer::Capability> capabilities = getCapabilities();
+  mCapabilities.insert(capabilities.begin(), capabilities.end());
+}
+
+sp<IComposer> Composer::getRaw() const { return mComposer; }
+
+bool Composer::hasCapability(IComposer::Capability capability) const {
+  return mCapabilities.count(capability) > 0;
+}
+
+std::vector<IComposer::Capability> Composer::getCapabilities() {
+  std::vector<IComposer::Capability> capabilities;
+  mComposer->getCapabilities(
+      [&](const auto& tmpCapabilities) { capabilities = tmpCapabilities; });
+
+  return capabilities;
+}
+
+std::string Composer::dumpDebugInfo() {
+  std::string debugInfo;
+  mComposer->dumpDebugInfo(
+      [&](const auto& tmpDebugInfo) { debugInfo = tmpDebugInfo.c_str(); });
+
+  return debugInfo;
+}
+
+std::unique_ptr<ComposerClient> Composer::createClient() {
+  std::unique_ptr<ComposerClient> client;
+  mComposer->createClient([&](const auto& tmpError, const auto& tmpClient) {
+    ASSERT_EQ(Error::NONE, tmpError) << "failed to create client";
+    client = std::make_unique<ComposerClient>(tmpClient);
+  });
+
+  return client;
+}
+
+ComposerClient::ComposerClient(const sp<IComposerClient>& client)
+    : mClient(client) {}
+
+ComposerClient::~ComposerClient() {
+  for (auto it : mDisplayResources) {
+    Display display = it.first;
+    DisplayResource& resource = it.second;
+
+    for (auto layer : resource.layers) {
+      EXPECT_EQ(Error::NONE, mClient->destroyLayer(display, layer))
+          << "failed to destroy layer " << layer;
+    }
+
+    if (resource.isVirtual) {
+      EXPECT_EQ(Error::NONE, mClient->destroyVirtualDisplay(display))
+          << "failed to destroy virtual display " << display;
+    }
+  }
+  mDisplayResources.clear();
+}
+
+sp<IComposerClient> ComposerClient::getRaw() const { return mClient; }
+
+void ComposerClient::registerCallback(const sp<IComposerCallback>& callback) {
+  mClient->registerCallback(callback);
+}
+
+uint32_t ComposerClient::getMaxVirtualDisplayCount() {
+  return mClient->getMaxVirtualDisplayCount();
+}
+
+Display ComposerClient::createVirtualDisplay(uint32_t width, uint32_t height,
+                                             PixelFormat formatHint,
+                                             uint32_t outputBufferSlotCount,
+                                             PixelFormat* outFormat) {
+  Display display = 0;
+  mClient->createVirtualDisplay(
+      width, height, formatHint, outputBufferSlotCount,
+      [&](const auto& tmpError, const auto& tmpDisplay, const auto& tmpFormat) {
+        ASSERT_EQ(Error::NONE, tmpError) << "failed to create virtual display";
+        display = tmpDisplay;
+        *outFormat = tmpFormat;
+
+        ASSERT_TRUE(
+            mDisplayResources.insert({display, DisplayResource(true)}).second)
+            << "duplicated virtual display id " << display;
+      });
+
+  return display;
+}
+
+void ComposerClient::destroyVirtualDisplay(Display display) {
+  Error error = mClient->destroyVirtualDisplay(display);
+  ASSERT_EQ(Error::NONE, error)
+      << "failed to destroy virtual display " << display;
+
+  mDisplayResources.erase(display);
+}
+
+Layer ComposerClient::createLayer(Display display, uint32_t bufferSlotCount) {
+  Layer layer = 0;
+  mClient->createLayer(
+      display, bufferSlotCount,
+      [&](const auto& tmpError, const auto& tmpLayer) {
+        ASSERT_EQ(Error::NONE, tmpError) << "failed to create layer";
+        layer = tmpLayer;
+
+        auto resourceIt = mDisplayResources.find(display);
+        if (resourceIt == mDisplayResources.end()) {
+          resourceIt =
+              mDisplayResources.insert({display, DisplayResource(false)}).first;
+        }
+
+        ASSERT_TRUE(resourceIt->second.layers.insert(layer).second)
+            << "duplicated layer id " << layer;
+      });
+
+  return layer;
+}
+
+void ComposerClient::destroyLayer(Display display, Layer layer) {
+  Error error = mClient->destroyLayer(display, layer);
+  ASSERT_EQ(Error::NONE, error) << "failed to destroy layer " << layer;
+
+  auto resourceIt = mDisplayResources.find(display);
+  ASSERT_NE(mDisplayResources.end(), resourceIt);
+  resourceIt->second.layers.erase(layer);
+}
+
+Config ComposerClient::getActiveConfig(Display display) {
+  Config config = 0;
+  mClient->getActiveConfig(
+      display, [&](const auto& tmpError, const auto& tmpConfig) {
+        ASSERT_EQ(Error::NONE, tmpError) << "failed to get active config";
+        config = tmpConfig;
+      });
+
+  return config;
+}
+
+bool ComposerClient::getClientTargetSupport(Display display, uint32_t width,
+                                            uint32_t height, PixelFormat format,
+                                            Dataspace dataspace) {
+  Error error = mClient->getClientTargetSupport(display, width, height, format,
+                                                dataspace);
+  return error == Error::NONE;
+}
+
+std::vector<ColorMode> ComposerClient::getColorModes(Display display) {
+  std::vector<ColorMode> modes;
+  mClient->getColorModes(
+      display, [&](const auto& tmpError, const auto& tmpMode) {
+        ASSERT_EQ(Error::NONE, tmpError) << "failed to get color mode";
+        modes = tmpMode;
+      });
+
+  return modes;
+}
+
+int32_t ComposerClient::getDisplayAttribute(
+    Display display, Config config, IComposerClient::Attribute attribute) {
+  int32_t value = 0;
+  mClient->getDisplayAttribute(display, config, attribute,
+                               [&](const auto& tmpError, const auto& tmpValue) {
+                                 ASSERT_EQ(Error::NONE, tmpError)
+                                     << "failed to get display attribute";
+                                 value = tmpValue;
+                               });
+
+  return value;
+}
+
+std::vector<Config> ComposerClient::getDisplayConfigs(Display display) {
+  std::vector<Config> configs;
+  mClient->getDisplayConfigs(
+      display, [&](const auto& tmpError, const auto& tmpConfigs) {
+        ASSERT_EQ(Error::NONE, tmpError) << "failed to get display configs";
+        configs = tmpConfigs;
+      });
+
+  return configs;
+}
+
+std::string ComposerClient::getDisplayName(Display display) {
+  std::string name;
+  mClient->getDisplayName(
+      display, [&](const auto& tmpError, const auto& tmpName) {
+        ASSERT_EQ(Error::NONE, tmpError) << "failed to get display name";
+        name = tmpName.c_str();
+      });
+
+  return name;
+}
+
+IComposerClient::DisplayType ComposerClient::getDisplayType(Display display) {
+  IComposerClient::DisplayType type = IComposerClient::DisplayType::INVALID;
+  mClient->getDisplayType(
+      display, [&](const auto& tmpError, const auto& tmpType) {
+        ASSERT_EQ(Error::NONE, tmpError) << "failed to get display type";
+        type = tmpType;
+      });
+
+  return type;
+}
+
+bool ComposerClient::getDozeSupport(Display display) {
+  bool support = false;
+  mClient->getDozeSupport(
+      display, [&](const auto& tmpError, const auto& tmpSupport) {
+        ASSERT_EQ(Error::NONE, tmpError) << "failed to get doze support";
+        support = tmpSupport;
+      });
+
+  return support;
+}
+
+std::vector<Hdr> ComposerClient::getHdrCapabilities(
+    Display display, float* outMaxLuminance, float* outMaxAverageLuminance,
+    float* outMinLuminance) {
+  std::vector<Hdr> types;
+  mClient->getHdrCapabilities(
+      display,
+      [&](const auto& tmpError, const auto& tmpTypes,
+          const auto& tmpMaxLuminance, const auto& tmpMaxAverageLuminance,
+          const auto& tmpMinLuminance) {
+        ASSERT_EQ(Error::NONE, tmpError) << "failed to get HDR capabilities";
+        types = tmpTypes;
+        *outMaxLuminance = tmpMaxLuminance;
+        *outMaxAverageLuminance = tmpMaxAverageLuminance;
+        *outMinLuminance = tmpMinLuminance;
+      });
+
+  return types;
+}
+
+void ComposerClient::setClientTargetSlotCount(Display display,
+                                              uint32_t clientTargetSlotCount) {
+  Error error =
+      mClient->setClientTargetSlotCount(display, clientTargetSlotCount);
+  ASSERT_EQ(Error::NONE, error) << "failed to set client target slot count";
+}
+
+void ComposerClient::setActiveConfig(Display display, Config config) {
+  Error error = mClient->setActiveConfig(display, config);
+  ASSERT_EQ(Error::NONE, error) << "failed to set active config";
+}
+
+void ComposerClient::setColorMode(Display display, ColorMode mode) {
+  Error error = mClient->setColorMode(display, mode);
+  ASSERT_EQ(Error::NONE, error) << "failed to set color mode";
+}
+
+void ComposerClient::setPowerMode(Display display,
+                                  IComposerClient::PowerMode mode) {
+  Error error = mClient->setPowerMode(display, mode);
+  ASSERT_EQ(Error::NONE, error) << "failed to set power mode";
+}
+
+void ComposerClient::setVsyncEnabled(Display display, bool enabled) {
+  IComposerClient::Vsync vsync = (enabled) ? IComposerClient::Vsync::ENABLE
+                                           : IComposerClient::Vsync::DISABLE;
+  Error error = mClient->setVsyncEnabled(display, vsync);
+  ASSERT_EQ(Error::NONE, error) << "failed to set vsync mode";
+}
+
+}  // namespace tests
+}  // namespace V2_1
+}  // namespace composer
+}  // namespace graphics
+}  // namespace hardware
+}  // namespace android
diff --git a/graphics/composer/2.1/vts/functional/VtsHalGraphicsComposerTestUtils.h b/graphics/composer/2.1/vts/functional/VtsHalGraphicsComposerTestUtils.h
new file mode 100644
index 0000000..4b57264
--- /dev/null
+++ b/graphics/composer/2.1/vts/functional/VtsHalGraphicsComposerTestUtils.h
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#ifndef VTS_HAL_GRAPHICS_COMPOSER_UTILS
+#define VTS_HAL_GRAPHICS_COMPOSER_UTILS
+
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <unordered_set>
+#include <vector>
+
+#include <android/hardware/graphics/composer/2.1/IComposer.h>
+#include <utils/StrongPointer.h>
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace composer {
+namespace V2_1 {
+namespace tests {
+
+using android::hardware::graphics::common::V1_0::ColorMode;
+using android::hardware::graphics::common::V1_0::Dataspace;
+using android::hardware::graphics::common::V1_0::Hdr;
+using android::hardware::graphics::common::V1_0::PixelFormat;
+
+class ComposerClient;
+
+// A wrapper to IComposer.
+class Composer {
+ public:
+  Composer();
+
+  sp<IComposer> getRaw() const;
+
+  // Returns true when the composer supports the specified capability.
+  bool hasCapability(IComposer::Capability capability) const;
+
+  std::vector<IComposer::Capability> getCapabilities();
+  std::string dumpDebugInfo();
+  std::unique_ptr<ComposerClient> createClient();
+
+ private:
+  void init();
+
+  sp<IComposer> mComposer;
+  std::unordered_set<IComposer::Capability> mCapabilities;
+};
+
+// A wrapper to IComposerClient.
+class ComposerClient {
+ public:
+  ComposerClient(const sp<IComposerClient>& client);
+  ~ComposerClient();
+
+  sp<IComposerClient> getRaw() const;
+
+  void registerCallback(const sp<IComposerCallback>& callback);
+  uint32_t getMaxVirtualDisplayCount();
+
+  Display createVirtualDisplay(uint32_t width, uint32_t height,
+                               PixelFormat formatHint,
+                               uint32_t outputBufferSlotCount,
+                               PixelFormat* outFormat);
+  void destroyVirtualDisplay(Display display);
+
+  Layer createLayer(Display display, uint32_t bufferSlotCount);
+  void destroyLayer(Display display, Layer layer);
+
+  Config getActiveConfig(Display display);
+  bool getClientTargetSupport(Display display, uint32_t width, uint32_t height,
+                              PixelFormat format, Dataspace dataspace);
+  std::vector<ColorMode> getColorModes(Display display);
+  int32_t getDisplayAttribute(Display display, Config config,
+                              IComposerClient::Attribute attribute);
+  std::vector<Config> getDisplayConfigs(Display display);
+  std::string getDisplayName(Display display);
+  IComposerClient::DisplayType getDisplayType(Display display);
+  bool getDozeSupport(Display display);
+  std::vector<Hdr> getHdrCapabilities(Display display, float* outMaxLuminance,
+                                      float* outMaxAverageLuminance,
+                                      float* outMinLuminance);
+
+  void setClientTargetSlotCount(Display display,
+                                uint32_t clientTargetSlotCount);
+  void setActiveConfig(Display display, Config config);
+  void setColorMode(Display display, ColorMode mode);
+  void setPowerMode(Display display, IComposerClient::PowerMode mode);
+  void setVsyncEnabled(Display display, bool enabled);
+
+ private:
+  sp<IComposerClient> mClient;
+
+  // Keep track of all virtual displays and layers.  When a test fails with
+  // ASSERT_*, the destructor will clean up the resources for the test.
+  struct DisplayResource {
+    DisplayResource(bool isVirtual_) : isVirtual(isVirtual_) {}
+
+    bool isVirtual;
+    std::unordered_set<Layer> layers;
+  };
+  std::unordered_map<Display, DisplayResource> mDisplayResources;
+};
+
+}  // namespace tests
+}  // namespace V2_1
+}  // namespace composer
+}  // namespace graphics
+}  // namespace hardware
+}  // namespace android
+
+#endif  // VTS_HAL_GRAPHICS_COMPOSER_UTILS
diff --git a/graphics/composer/2.1/vts/functional/VtsHalGraphicsComposerV2_1TargetTest.cpp b/graphics/composer/2.1/vts/functional/VtsHalGraphicsComposerV2_1TargetTest.cpp
index a565845..0390c88 100644
--- a/graphics/composer/2.1/vts/functional/VtsHalGraphicsComposerV2_1TargetTest.cpp
+++ b/graphics/composer/2.1/vts/functional/VtsHalGraphicsComposerV2_1TargetTest.cpp
@@ -18,9 +18,9 @@
 
 #include <IComposerCommandBuffer.h>
 #include <android-base/logging.h>
-#include <android/hardware/graphics/allocator/2.0/IAllocator.h>
-#include <android/hardware/graphics/composer/2.1/IComposer.h>
-#include <android/hardware/graphics/mapper/2.0/IMapper.h>
+#include "VtsHalGraphicsAllocatorTestUtils.h"
+#include "VtsHalGraphicsComposerTestUtils.h"
+#include "VtsHalGraphicsMapperTestUtils.h"
 
 #include <VtsHalHidlTargetBaseTest.h>
 #include <unistd.h>
@@ -46,12 +46,15 @@
 using android::hardware::graphics::allocator::V2_0::IAllocator;
 using android::hardware::graphics::allocator::V2_0::IAllocatorClient;
 using android::hardware::graphics::allocator::V2_0::ProducerUsage;
+using android::hardware::graphics::allocator::V2_0::tests::Allocator;
+using android::hardware::graphics::allocator::V2_0::tests::AllocatorClient;
 using android::hardware::graphics::common::V1_0::ColorMode;
 using android::hardware::graphics::common::V1_0::ColorTransform;
 using android::hardware::graphics::common::V1_0::Dataspace;
 using android::hardware::graphics::common::V1_0::PixelFormat;
 using android::hardware::graphics::common::V1_0::Transform;
 using android::hardware::graphics::mapper::V2_0::IMapper;
+using android::hardware::graphics::mapper::V2_0::tests::Mapper;
 using GrallocError = android::hardware::graphics::allocator::V2_0::Error;
 
 // IComposerCallback to be installed with IComposerClient::registerCallback.
@@ -134,13 +137,8 @@
 class GraphicsComposerHidlTest : public ::testing::VtsHalHidlTargetBaseTest {
  protected:
   void SetUp() override {
-    mComposer = ::testing::VtsHalHidlTargetBaseTest::getService<IComposer>();
-    ASSERT_NE(nullptr, mComposer.get());
-
-    mComposerClient = createClient();
-    ASSERT_NE(nullptr, mComposerClient.get());
-
-    initCapabilities();
+    ASSERT_NO_FATAL_FAILURE(mComposer = std::make_unique<Composer>());
+    ASSERT_NO_FATAL_FAILURE(mComposerClient = mComposer->createClient());
 
     mComposerCallback = new GraphicsComposerCallback;
     mComposerClient->registerCallback(mComposerCallback);
@@ -157,177 +155,16 @@
     }
   }
 
-  /**
-   * Initialize the set of supported capabilities.
-   */
-  void initCapabilities() {
-    mComposer->getCapabilities([this](const auto& capabilities) {
-      std::vector<IComposer::Capability> caps = capabilities;
-      mCapabilities.insert(caps.cbegin(), caps.cend());
-    });
-  }
-
-  /**
-   * Test whether a capability is supported.
-   */
-  bool hasCapability(IComposer::Capability capability) const {
-    return (mCapabilities.count(capability) > 0);
-  }
-
-  IComposerClient::DisplayType getDisplayType(Display display) {
-    IComposerClient::DisplayType type = IComposerClient::DisplayType::INVALID;
-    mComposerClient->getDisplayType(
-        display, [&](const auto& tmpError, const auto& tmpType) {
-          ASSERT_EQ(Error::NONE, tmpError);
-          type = tmpType;
-        });
-    return type;
-  }
-
-  Error createVirtualDisplay(Display* outDisplay) {
-    auto ret_count = mComposerClient->getMaxVirtualDisplayCount();
-    if (ret_count == 0) {
-      return Error::UNSUPPORTED;
-    }
-
-    Error err = Error::NO_RESOURCES;
-    Display display;
-    mComposerClient->createVirtualDisplay(
-        64, 64, PixelFormat::IMPLEMENTATION_DEFINED, kBufferSlotCount,
-        [&](const auto& tmpError, const auto& tmpDisplay, const auto&) {
-          err = tmpError;
-          display = tmpDisplay;
-        });
-
-    *outDisplay = display;
-    return err;
-  }
-
-  void destroyVirtualDisplay(Display display) {
-    auto ret = mComposerClient->destroyVirtualDisplay(display);
-    ASSERT_EQ(Error::NONE, static_cast<Error>(ret));
-  }
-
-  Error createLayer(Layer* outLayer) {
-    Error err = Error::NO_RESOURCES;
-    Layer layer;
-    mComposerClient->createLayer(
-        mPrimaryDisplay, kBufferSlotCount,
-        [&](const auto& tmpError, const auto& tmpLayer) {
-          err = tmpError;
-          layer = tmpLayer;
-        });
-
-    *outLayer = layer;
-    return err;
-  }
-
-  void destroyLayer(Layer layer) {
-    auto ret = mComposerClient->destroyLayer(mPrimaryDisplay, layer);
-    ASSERT_EQ(Error::NONE, static_cast<Error>(ret));
-  }
-
-  int32_t getDisplayAttribute(Config config,
-                              IComposerClient::Attribute attribute) {
-    int32_t value = -1;
-    mComposerClient->getDisplayAttribute(
-        mPrimaryDisplay, config, attribute,
-        [&](const auto& tmpError, const auto& tmpValue) {
-          ASSERT_EQ(Error::NONE, tmpError);
-          value = tmpValue;
-        });
-    return value;
-  }
-
-  std::vector<Config> getDisplayConfigs() {
-    std::vector<Config> configs;
-    mComposerClient->getDisplayConfigs(
-        mPrimaryDisplay, [&](const auto& tmpError, const auto& tmpConfigs) {
-          ASSERT_EQ(Error::NONE, tmpError);
-
-          configs = tmpConfigs;
-          ASSERT_FALSE(configs.empty());
-        });
-
-    return configs;
-  }
-
-  std::vector<ColorMode> getColorModes() {
-    std::vector<ColorMode> modes;
-    mComposerClient->getColorModes(
-        mPrimaryDisplay, [&](const auto& tmpError, const auto& tmpModes) {
-          ASSERT_EQ(Error::NONE, tmpError);
-
-          modes = tmpModes;
-          ASSERT_NE(modes.end(),
-                    std::find(modes.begin(), modes.end(), ColorMode::NATIVE));
-        });
-
-    return modes;
-  }
-
-  std::vector<IComposerClient::PowerMode> getPowerModes() {
-    std::vector<IComposerClient::PowerMode> modes;
-    modes.push_back(IComposerClient::PowerMode::OFF);
-
-    mComposerClient->getDozeSupport(
-        mPrimaryDisplay, [&](const auto& tmpError, const auto& tmpSupport) {
-          ASSERT_EQ(Error::NONE, tmpError);
-          if (tmpSupport) {
-            modes.push_back(IComposerClient::PowerMode::DOZE);
-            modes.push_back(IComposerClient::PowerMode::DOZE_SUSPEND);
-          }
-        });
-
-    // push ON last
-    modes.push_back(IComposerClient::PowerMode::ON);
-
-    return modes;
-  }
-
-  void setActiveConfig(Config config) {
-    auto ret = mComposerClient->setActiveConfig(mPrimaryDisplay, config);
-    ASSERT_EQ(Error::NONE, static_cast<Error>(ret));
-  }
-
-  void setColorMode(ColorMode mode) {
-    auto ret = mComposerClient->setColorMode(mPrimaryDisplay, mode);
-    ASSERT_EQ(Error::NONE, static_cast<Error>(ret));
-  }
-
-  void setPowerMode(IComposerClient::PowerMode mode) {
-    auto ret = mComposerClient->setPowerMode(mPrimaryDisplay, mode);
-    ASSERT_EQ(Error::NONE, static_cast<Error>(ret));
-  }
-
-  void setVsyncEnabled(bool enable) {
-    auto ret = mComposerClient->setVsyncEnabled(
-        mPrimaryDisplay,
-        enable ? IComposerClient::Vsync::ENABLE
-               : IComposerClient::Vsync::DISABLE);
-    ASSERT_EQ(Error::NONE, static_cast<Error>(ret));
-  }
   // use the slot count usually set by SF
   static constexpr uint32_t kBufferSlotCount = 64;
 
-  sp<IComposer> mComposer;
-  sp<IComposerClient> mComposerClient;
+  std::unique_ptr<Composer> mComposer;
+  std::unique_ptr<ComposerClient> mComposerClient;
   sp<GraphicsComposerCallback> mComposerCallback;
   // the first display and is assumed never to be removed
   Display mPrimaryDisplay;
 
  private:
-  sp<IComposerClient> createClient() {
-    sp<IComposerClient> client;
-    mComposer->createClient([&](const auto& tmpError, const auto& tmpClient) {
-      if (tmpError == Error::NONE) {
-        client = tmpClient;
-      }
-    });
-
-    return client;
-  }
-
   Display waitForFirstDisplay() {
     while (true) {
       std::vector<Display> displays = mComposerCallback->getDisplays();
@@ -339,9 +176,6 @@
       return displays[0];
     }
   }
-
-  // the set of all supported capabilities
-  std::unordered_set<IComposer::Capability> mCapabilities;
 };
 
 /**
@@ -350,22 +184,16 @@
  * Test that IComposer::getCapabilities returns no invalid capabilities.
  */
 TEST_F(GraphicsComposerHidlTest, GetCapabilities) {
-  mComposer->getCapabilities([](const auto& tmpCapabilities) {
-    std::vector<IComposer::Capability> capabilities = tmpCapabilities;
-    ASSERT_EQ(capabilities.end(),
-              std::find(capabilities.begin(), capabilities.end(),
-                        IComposer::Capability::INVALID));
-  });
+  auto capabilities = mComposer->getCapabilities();
+  ASSERT_EQ(capabilities.end(),
+            std::find(capabilities.begin(), capabilities.end(),
+                      IComposer::Capability::INVALID));
 }
 
 /**
  * Test IComposer::dumpDebugInfo.
  */
-TEST_F(GraphicsComposerHidlTest, DumpDebugInfo) {
-  mComposer->dumpDebugInfo([](const auto&) {
-    // nothing to do
-  });
-}
+TEST_F(GraphicsComposerHidlTest, DumpDebugInfo) { mComposer->dumpDebugInfo(); }
 
 /**
  * Test IComposer::createClient.
@@ -373,7 +201,7 @@
  * Test that IComposerClient is a singleton.
  */
 TEST_F(GraphicsComposerHidlTest, CreateClientSingleton) {
-  mComposer->createClient([&](const auto& tmpError, const auto&) {
+  mComposer->getRaw()->createClient([&](const auto& tmpError, const auto&) {
     EXPECT_EQ(Error::NO_RESOURCES, tmpError);
   });
 }
@@ -385,19 +213,22 @@
  * Test that virtual displays can be created and has the correct display type.
  */
 TEST_F(GraphicsComposerHidlTest, CreateVirtualDisplay) {
-  Display display;
-  Error err = createVirtualDisplay(&display);
-  if (err == Error::UNSUPPORTED) {
+  if (mComposerClient->getMaxVirtualDisplayCount() == 0) {
     GTEST_SUCCEED() << "no virtual display support";
     return;
   }
-  ASSERT_EQ(Error::NONE, err);
+
+  Display display;
+  PixelFormat format;
+  ASSERT_NO_FATAL_FAILURE(display = mComposerClient->createVirtualDisplay(
+                              64, 64, PixelFormat::IMPLEMENTATION_DEFINED,
+                              kBufferSlotCount, &format));
 
   // test display type
-  IComposerClient::DisplayType type = getDisplayType(display);
+  IComposerClient::DisplayType type = mComposerClient->getDisplayType(display);
   EXPECT_EQ(IComposerClient::DisplayType::VIRTUAL, type);
 
-  destroyVirtualDisplay(display);
+  mComposerClient->destroyVirtualDisplay(display);
 }
 
 /**
@@ -407,20 +238,17 @@
  */
 TEST_F(GraphicsComposerHidlTest, CreateLayer) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
-  destroyLayer(layer);
+  mComposerClient->destroyLayer(mPrimaryDisplay, layer);
 }
 
 /**
  * Test IComposerClient::getDisplayName.
  */
 TEST_F(GraphicsComposerHidlTest, GetDisplayName) {
-  mComposerClient->getDisplayName(mPrimaryDisplay,
-                                  [&](const auto& tmpError, const auto&) {
-                                    ASSERT_EQ(Error::NONE, tmpError);
-                                  });
+  mComposerClient->getDisplayName(mPrimaryDisplay);
 }
 
 /**
@@ -430,8 +258,8 @@
  * for the primary display.
  */
 TEST_F(GraphicsComposerHidlTest, GetDisplayType) {
-  IComposerClient::DisplayType type = getDisplayType(mPrimaryDisplay);
-  EXPECT_EQ(IComposerClient::DisplayType::PHYSICAL, type);
+  ASSERT_EQ(IComposerClient::DisplayType::PHYSICAL,
+            mComposerClient->getDisplayType(mPrimaryDisplay));
 }
 
 /**
@@ -441,21 +269,21 @@
  * required client targets.
  */
 TEST_F(GraphicsComposerHidlTest, GetClientTargetSupport) {
-  std::vector<Config> configs = getDisplayConfigs();
+  std::vector<Config> configs =
+      mComposerClient->getDisplayConfigs(mPrimaryDisplay);
   for (auto config : configs) {
-    int32_t width =
-        getDisplayAttribute(config, IComposerClient::Attribute::WIDTH);
-    int32_t height =
-        getDisplayAttribute(config, IComposerClient::Attribute::HEIGHT);
+    int32_t width = mComposerClient->getDisplayAttribute(
+        mPrimaryDisplay, config, IComposerClient::Attribute::WIDTH);
+    int32_t height = mComposerClient->getDisplayAttribute(
+        mPrimaryDisplay, config, IComposerClient::Attribute::HEIGHT);
     ASSERT_LT(0, width);
     ASSERT_LT(0, height);
 
-    setActiveConfig(config);
+    mComposerClient->setActiveConfig(mPrimaryDisplay, config);
 
-    auto ret = mComposerClient->getClientTargetSupport(
+    ASSERT_TRUE(mComposerClient->getClientTargetSupport(
         mPrimaryDisplay, width, height, PixelFormat::RGBA_8888,
-        Dataspace::UNKNOWN);
-    ASSERT_EQ(Error::NONE, static_cast<Error>(ret));
+        Dataspace::UNKNOWN));
   }
 }
 
@@ -466,21 +294,22 @@
  * formats, and succeeds or fails correctly for optional attributes.
  */
 TEST_F(GraphicsComposerHidlTest, GetDisplayAttribute) {
-  std::vector<Config> configs = getDisplayConfigs();
+  std::vector<Config> configs =
+      mComposerClient->getDisplayConfigs(mPrimaryDisplay);
   for (auto config : configs) {
     const std::array<IComposerClient::Attribute, 3> requiredAttributes = {{
         IComposerClient::Attribute::WIDTH, IComposerClient::Attribute::HEIGHT,
         IComposerClient::Attribute::VSYNC_PERIOD,
     }};
     for (auto attribute : requiredAttributes) {
-      getDisplayAttribute(config, attribute);
+      mComposerClient->getDisplayAttribute(mPrimaryDisplay, config, attribute);
     }
 
     const std::array<IComposerClient::Attribute, 2> optionalAttributes = {{
         IComposerClient::Attribute::DPI_X, IComposerClient::Attribute::DPI_Y,
     }};
     for (auto attribute : optionalAttributes) {
-      mComposerClient->getDisplayAttribute(
+      mComposerClient->getRaw()->getDisplayAttribute(
           mPrimaryDisplay, config, attribute,
           [&](const auto& tmpError, const auto&) {
             EXPECT_TRUE(tmpError == Error::NONE ||
@@ -494,19 +323,18 @@
  * Test IComposerClient::getHdrCapabilities.
  */
 TEST_F(GraphicsComposerHidlTest, GetHdrCapabilities) {
-  mComposerClient->getHdrCapabilities(
-      mPrimaryDisplay,
-      [&](const auto& tmpError, const auto&, const auto&, const auto&,
-          const auto&) { ASSERT_EQ(Error::NONE, tmpError); });
+  float maxLuminance;
+  float maxAverageLuminance;
+  float minLuminance;
+  mComposerClient->getHdrCapabilities(mPrimaryDisplay, &maxLuminance,
+                                      &maxAverageLuminance, &minLuminance);
 }
 
 /**
  * Test IComposerClient::setClientTargetSlotCount.
  */
 TEST_F(GraphicsComposerHidlTest, SetClientTargetSlotCount) {
-  auto ret = mComposerClient->setClientTargetSlotCount(mPrimaryDisplay,
-                                                       kBufferSlotCount);
-  ASSERT_EQ(Error::NONE, static_cast<Error>(ret));
+  mComposerClient->setClientTargetSlotCount(mPrimaryDisplay, kBufferSlotCount);
 }
 
 /**
@@ -516,15 +344,11 @@
  * configs.
  */
 TEST_F(GraphicsComposerHidlTest, SetActiveConfig) {
-  std::vector<Config> configs = getDisplayConfigs();
+  std::vector<Config> configs =
+      mComposerClient->getDisplayConfigs(mPrimaryDisplay);
   for (auto config : configs) {
-    setActiveConfig(config);
-
-    mComposerClient->getActiveConfig(
-        mPrimaryDisplay, [&](const auto& tmpError, const auto& tmpConfig) {
-          EXPECT_EQ(Error::NONE, tmpError);
-          EXPECT_EQ(config, tmpConfig);
-        });
+    mComposerClient->setActiveConfig(mPrimaryDisplay, config);
+    ASSERT_EQ(config, mComposerClient->getActiveConfig(mPrimaryDisplay));
   }
 }
 
@@ -534,9 +358,10 @@
  * Test that IComposerClient::setColorMode succeeds for all color modes.
  */
 TEST_F(GraphicsComposerHidlTest, SetColorMode) {
-  std::vector<ColorMode> modes = getColorModes();
+  std::vector<ColorMode> modes =
+      mComposerClient->getColorModes(mPrimaryDisplay);
   for (auto mode : modes) {
-    setColorMode(mode);
+    mComposerClient->setColorMode(mPrimaryDisplay, mode);
   }
 }
 
@@ -546,9 +371,19 @@
  * Test that IComposerClient::setPowerMode succeeds for all power modes.
  */
 TEST_F(GraphicsComposerHidlTest, SetPowerMode) {
-  std::vector<IComposerClient::PowerMode> modes = getPowerModes();
+  std::vector<IComposerClient::PowerMode> modes;
+  modes.push_back(IComposerClient::PowerMode::OFF);
+
+  if (mComposerClient->getDozeSupport(mPrimaryDisplay)) {
+    modes.push_back(IComposerClient::PowerMode::DOZE);
+    modes.push_back(IComposerClient::PowerMode::DOZE_SUSPEND);
+  }
+
+  // push ON last
+  modes.push_back(IComposerClient::PowerMode::ON);
+
   for (auto mode : modes) {
-    setPowerMode(mode);
+    mComposerClient->setPowerMode(mPrimaryDisplay, mode);
   }
 }
 
@@ -561,9 +396,9 @@
 TEST_F(GraphicsComposerHidlTest, SetVsyncEnabled) {
   mComposerCallback->setVsyncAllowed(true);
 
-  setVsyncEnabled(true);
+  mComposerClient->setVsyncEnabled(mPrimaryDisplay, true);
   usleep(60 * 1000);
-  setVsyncEnabled(false);
+  mComposerClient->setVsyncEnabled(mPrimaryDisplay, false);
 
   mComposerCallback->setVsyncAllowed(false);
 }
@@ -573,7 +408,10 @@
  protected:
   void SetUp() override {
     ASSERT_NO_FATAL_FAILURE(GraphicsComposerHidlTest::SetUp());
-    ASSERT_NO_FATAL_FAILURE(SetUpGralloc());
+
+    ASSERT_NO_FATAL_FAILURE(mAllocator = std::make_unique<Allocator>());
+    ASSERT_NO_FATAL_FAILURE(mAllocatorClient = mAllocator->createClient());
+    ASSERT_NO_FATAL_FAILURE(mMapper = std::make_unique<Mapper>());
 
     mWriter = std::make_unique<CommandWriterBase>(1024);
     mReader = std::make_unique<CommandReader>();
@@ -583,80 +421,6 @@
     ASSERT_NO_FATAL_FAILURE(GraphicsComposerHidlTest::TearDown());
   }
 
-  const native_handle_t* cloneBuffer(const native_handle_t* handle) {
-    auto clone = native_handle_clone(handle);
-    if (!clone) {
-      return nullptr;
-    }
-
-    GrallocError err = mMapper->retain(clone);
-    if (err != GrallocError::NONE) {
-      native_handle_close(clone);
-      native_handle_delete(const_cast<native_handle_t*>(clone));
-      return nullptr;
-    }
-
-    return clone;
-  }
-
-  const native_handle_t* allocate(
-      const IAllocatorClient::BufferDescriptorInfo& info) {
-    // create descriptor
-    GrallocError err = GrallocError::NO_RESOURCES;
-    BufferDescriptor descriptor;
-    mAllocatorClient->createDescriptor(
-        info, [&](const auto& tmpError, const auto& tmpDescriptor) {
-          err = tmpError;
-          descriptor = tmpDescriptor;
-        });
-    if (err != GrallocError::NONE) {
-      return nullptr;
-    }
-
-    // allocate buffer
-    hidl_vec<BufferDescriptor> descriptors;
-    hidl_vec<Buffer> buffers;
-    descriptors.setToExternal(&descriptor, 1);
-    err = GrallocError::NO_RESOURCES;
-    mAllocatorClient->allocate(
-        descriptors, [&](const auto& tmpError, const auto& tmpBuffers) {
-          err = tmpError;
-          buffers = tmpBuffers;
-        });
-    if ((err != GrallocError::NONE && err != GrallocError::NOT_SHARED) ||
-        buffers.size() != 1) {
-      mAllocatorClient->destroyDescriptor(descriptors[0]);
-      return nullptr;
-    }
-
-    // export handle
-    err = GrallocError::NO_RESOURCES;
-    const native_handle_t* handle = nullptr;
-    mAllocatorClient->exportHandle(
-        descriptors[0], buffers[0],
-        [&](const auto& tmpError, const auto& tmpHandle) {
-          err = tmpError;
-          if (err != GrallocError::NONE) {
-            return;
-          }
-
-          handle = cloneBuffer(tmpHandle.getNativeHandle());
-          if (!handle) {
-            err = GrallocError::NO_RESOURCES;
-            return;
-          }
-        });
-
-    mAllocatorClient->destroyDescriptor(descriptors[0]);
-    mAllocatorClient->free(buffers[0]);
-
-    if (err != GrallocError::NONE) {
-      return nullptr;
-    }
-
-    return handle;
-  }
-
   const native_handle_t* allocate() {
     IAllocatorClient::BufferDescriptorInfo info{};
     info.width = 64;
@@ -666,12 +430,7 @@
     info.producerUsageMask = static_cast<uint64_t>(ProducerUsage::CPU_WRITE);
     info.consumerUsageMask = static_cast<uint64_t>(ConsumerUsage::CPU_READ);
 
-    return allocate(info);
-  }
-
-  void free(const native_handle_t* handle) {
-    auto ret = mMapper->release(handle);
-    ASSERT_EQ(GrallocError::NONE, static_cast<GrallocError>(ret));
+    return mMapper->allocate(mAllocatorClient, info);
   }
 
   void execute() {
@@ -682,20 +441,20 @@
         mWriter->writeQueue(&queueChanged, &commandLength, &commandHandles));
 
     if (queueChanged) {
-      auto ret =
-          mComposerClient->setInputCommandQueue(*mWriter->getMQDescriptor());
+      auto ret = mComposerClient->getRaw()->setInputCommandQueue(
+          *mWriter->getMQDescriptor());
       ASSERT_EQ(Error::NONE, static_cast<Error>(ret));
       return;
     }
 
-    mComposerClient->executeCommands(
+    mComposerClient->getRaw()->executeCommands(
         commandLength, commandHandles,
         [&](const auto& tmpError, const auto& tmpOutQueueChanged,
             const auto& tmpOutLength, const auto& tmpOutHandles) {
           ASSERT_EQ(Error::NONE, tmpError);
 
           if (tmpOutQueueChanged) {
-            mComposerClient->getOutputCommandQueue(
+            mComposerClient->getRaw()->getOutputCommandQueue(
                 [&](const auto& tmpError, const auto& tmpDescriptor) {
                   ASSERT_EQ(Error::NONE, tmpError);
                   mReader->setMQDescriptor(tmpDescriptor);
@@ -748,25 +507,9 @@
   std::unique_ptr<CommandReader> mReader;
 
  private:
-  void SetUpGralloc() {
-    mAllocator = ::testing::VtsHalHidlTargetBaseTest::getService<IAllocator>();
-    ASSERT_NE(nullptr, mAllocator.get());
-
-    mAllocator->createClient([this](const auto& error, const auto& client) {
-      if (error == GrallocError::NONE) {
-        mAllocatorClient = client;
-      }
-    });
-    ASSERT_NE(nullptr, mAllocatorClient.get());
-
-    mMapper = ::testing::VtsHalHidlTargetBaseTest::getService<IMapper>();
-    ASSERT_NE(nullptr, mMapper.get());
-    ASSERT_FALSE(mMapper->isRemote());
-  }
-
-  sp<IAllocator> mAllocator;
-  sp<IAllocatorClient> mAllocatorClient;
-  sp<IMapper> mMapper;
+  std::unique_ptr<Allocator> mAllocator;
+  std::unique_ptr<AllocatorClient> mAllocatorClient;
+  std::unique_ptr<Mapper> mMapper;
 };
 
 /**
@@ -801,22 +544,23 @@
  * Test IComposerClient::Command::SET_OUTPUT_BUFFER.
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_OUTPUT_BUFFER) {
-  auto handle = allocate();
-  ASSERT_NE(nullptr, handle);
-
-  Display display;
-  Error err = createVirtualDisplay(&display);
-  if (err == Error::UNSUPPORTED) {
+  if (mComposerClient->getMaxVirtualDisplayCount() == 0) {
     GTEST_SUCCEED() << "no virtual display support";
     return;
   }
-  ASSERT_EQ(Error::NONE, err);
+
+  Display display;
+  PixelFormat format;
+  ASSERT_NO_FATAL_FAILURE(display = mComposerClient->createVirtualDisplay(
+                              64, 64, PixelFormat::IMPLEMENTATION_DEFINED,
+                              kBufferSlotCount, &format));
+
+  const native_handle_t* handle;
+  ASSERT_NO_FATAL_FAILURE(handle = allocate());
 
   mWriter->selectDisplay(display);
   mWriter->setOutputBuffer(0, handle, -1);
-
-  destroyVirtualDisplay(display);
-  free(handle);
+  execute();
 }
 
 /**
@@ -853,16 +597,14 @@
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_CURSOR_POSITION) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   mWriter->selectDisplay(mPrimaryDisplay);
   mWriter->selectLayer(layer);
   mWriter->setLayerCursorPosition(1, 1);
   mWriter->setLayerCursorPosition(0, 0);
   execute();
-
-  destroyLayer(layer);
 }
 
 /**
@@ -873,16 +615,13 @@
   ASSERT_NE(nullptr, handle);
 
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   mWriter->selectDisplay(mPrimaryDisplay);
   mWriter->selectLayer(layer);
   mWriter->setLayerBuffer(0, handle, -1);
   execute();
-
-  destroyLayer(layer);
-  free(handle);
 }
 
 /**
@@ -890,8 +629,8 @@
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_SURFACE_DAMAGE) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   IComposerClient::Rect empty{0, 0, 0, 0};
   IComposerClient::Rect unit{0, 0, 1, 1};
@@ -902,8 +641,6 @@
   mWriter->setLayerSurfaceDamage(std::vector<IComposerClient::Rect>(1, unit));
   mWriter->setLayerSurfaceDamage(std::vector<IComposerClient::Rect>());
   execute();
-
-  destroyLayer(layer);
 }
 
 /**
@@ -911,8 +648,8 @@
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_BLEND_MODE) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   mWriter->selectDisplay(mPrimaryDisplay);
   mWriter->selectLayer(layer);
@@ -920,8 +657,6 @@
   mWriter->setLayerBlendMode(IComposerClient::BlendMode::PREMULTIPLIED);
   mWriter->setLayerBlendMode(IComposerClient::BlendMode::COVERAGE);
   execute();
-
-  destroyLayer(layer);
 }
 
 /**
@@ -929,16 +664,14 @@
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_COLOR) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   mWriter->selectDisplay(mPrimaryDisplay);
   mWriter->selectLayer(layer);
   mWriter->setLayerColor(IComposerClient::Color{0xff, 0xff, 0xff, 0xff});
   mWriter->setLayerColor(IComposerClient::Color{0, 0, 0, 0});
   execute();
-
-  destroyLayer(layer);
 }
 
 /**
@@ -946,8 +679,8 @@
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_COMPOSITION_TYPE) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   mWriter->selectDisplay(mPrimaryDisplay);
   mWriter->selectLayer(layer);
@@ -956,8 +689,6 @@
   mWriter->setLayerCompositionType(IComposerClient::Composition::SOLID_COLOR);
   mWriter->setLayerCompositionType(IComposerClient::Composition::CURSOR);
   execute();
-
-  destroyLayer(layer);
 }
 
 /**
@@ -965,15 +696,13 @@
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_DATASPACE) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   mWriter->selectDisplay(mPrimaryDisplay);
   mWriter->selectLayer(layer);
   mWriter->setLayerDataspace(Dataspace::UNKNOWN);
   execute();
-
-  destroyLayer(layer);
 }
 
 /**
@@ -981,15 +710,13 @@
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_DISPLAY_FRAME) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   mWriter->selectDisplay(mPrimaryDisplay);
   mWriter->selectLayer(layer);
   mWriter->setLayerDisplayFrame(IComposerClient::Rect{0, 0, 1, 1});
   execute();
-
-  destroyLayer(layer);
 }
 
 /**
@@ -997,23 +724,21 @@
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_PLANE_ALPHA) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   mWriter->selectDisplay(mPrimaryDisplay);
   mWriter->selectLayer(layer);
   mWriter->setLayerPlaneAlpha(0.0f);
   mWriter->setLayerPlaneAlpha(1.0f);
   execute();
-
-  destroyLayer(layer);
 }
 
 /**
  * Test IComposerClient::Command::SET_LAYER_SIDEBAND_STREAM.
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_SIDEBAND_STREAM) {
-  if (!hasCapability(IComposer::Capability::SIDEBAND_STREAM)) {
+  if (!mComposer->hasCapability(IComposer::Capability::SIDEBAND_STREAM)) {
     GTEST_SUCCEED() << "no sideband stream support";
     return;
   }
@@ -1022,16 +747,13 @@
   ASSERT_NE(nullptr, handle);
 
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   mWriter->selectDisplay(mPrimaryDisplay);
   mWriter->selectLayer(layer);
   mWriter->setLayerSidebandStream(handle);
   execute();
-
-  destroyLayer(layer);
-  free(handle);
 }
 
 /**
@@ -1039,15 +761,13 @@
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_SOURCE_CROP) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   mWriter->selectDisplay(mPrimaryDisplay);
   mWriter->selectLayer(layer);
   mWriter->setLayerSourceCrop(IComposerClient::FRect{0.0f, 0.0f, 1.0f, 1.0f});
   execute();
-
-  destroyLayer(layer);
 }
 
 /**
@@ -1055,8 +775,8 @@
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_TRANSFORM) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   mWriter->selectDisplay(mPrimaryDisplay);
   mWriter->selectLayer(layer);
@@ -1071,8 +791,6 @@
   mWriter->setLayerTransform(
       static_cast<Transform>(Transform::FLIP_V | Transform::ROT_90));
   execute();
-
-  destroyLayer(layer);
 }
 
 /**
@@ -1080,8 +798,8 @@
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_VISIBLE_REGION) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   IComposerClient::Rect empty{0, 0, 0, 0};
   IComposerClient::Rect unit{0, 0, 1, 1};
@@ -1092,8 +810,6 @@
   mWriter->setLayerVisibleRegion(std::vector<IComposerClient::Rect>(1, unit));
   mWriter->setLayerVisibleRegion(std::vector<IComposerClient::Rect>());
   execute();
-
-  destroyLayer(layer);
 }
 
 /**
@@ -1101,16 +817,14 @@
  */
 TEST_F(GraphicsComposerHidlCommandTest, SET_LAYER_Z_ORDER) {
   Layer layer;
-  Error err = createLayer(&layer);
-  ASSERT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(
+      layer = mComposerClient->createLayer(mPrimaryDisplay, kBufferSlotCount));
 
   mWriter->selectDisplay(mPrimaryDisplay);
   mWriter->selectLayer(layer);
   mWriter->setLayerZOrder(10);
   mWriter->setLayerZOrder(0);
   execute();
-
-  destroyLayer(layer);
 }
 
 }  // namespace anonymous
diff --git a/graphics/mapper/2.0/vts/functional/Android.bp b/graphics/mapper/2.0/vts/functional/Android.bp
index 24cd1be..8b3379f 100644
--- a/graphics/mapper/2.0/vts/functional/Android.bp
+++ b/graphics/mapper/2.0/vts/functional/Android.bp
@@ -14,6 +14,27 @@
 // limitations under the License.
 //
 
+cc_library_static {
+    name: "libVtsHalGraphicsMapperTestUtils",
+    srcs: ["VtsHalGraphicsMapperTestUtils.cpp"],
+    shared_libs: [
+        "android.hardware.graphics.allocator@2.0",
+        "android.hardware.graphics.mapper@2.0",
+    ],
+    static_libs: [
+        "VtsHalHidlTargetBaseTest",
+        "libVtsHalGraphicsAllocatorTestUtils",
+    ],
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+        "-O0",
+        "-g",
+    ],
+    export_include_dirs: ["."],
+}
+
 cc_test {
     name: "VtsHalGraphicsMapperV2_0TargetTest",
     srcs: ["VtsHalGraphicsMapperV2_0TargetTest.cpp"],
@@ -30,8 +51,15 @@
         "android.hardware.graphics.mapper@2.0",
         "android.hardware.graphics.common@1.0",
     ],
-    static_libs: ["VtsHalHidlTargetBaseTest"],
+    static_libs: [
+        "libVtsHalGraphicsAllocatorTestUtils",
+        "libVtsHalGraphicsMapperTestUtils",
+        "VtsHalHidlTargetBaseTest",
+    ],
     cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
         "-O0",
         "-g",
     ]
diff --git a/graphics/mapper/2.0/vts/functional/VtsHalGraphicsMapperTestUtils.cpp b/graphics/mapper/2.0/vts/functional/VtsHalGraphicsMapperTestUtils.cpp
new file mode 100644
index 0000000..fc26587
--- /dev/null
+++ b/graphics/mapper/2.0/vts/functional/VtsHalGraphicsMapperTestUtils.cpp
@@ -0,0 +1,257 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#include <VtsHalHidlTargetBaseTest.h>
+
+#include "VtsHalGraphicsMapperTestUtils.h"
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace mapper {
+namespace V2_0 {
+namespace tests {
+
+using android::hardware::graphics::allocator::V2_0::Buffer;
+using android::hardware::graphics::allocator::V2_0::BufferDescriptor;
+using android::hardware::graphics::allocator::V2_0::Error;
+
+Mapper::Mapper() { init(); }
+
+void Mapper::init() {
+  mMapper = ::testing::VtsHalHidlTargetBaseTest::getService<IMapper>();
+  ASSERT_NE(nullptr, mMapper.get()) << "failed to get mapper service";
+  ASSERT_FALSE(mMapper->isRemote()) << "mapper is not in passthrough mode";
+}
+
+Mapper::~Mapper() {
+  for (auto it : mHandles) {
+    while (it.second) {
+      EXPECT_EQ(Error::NONE, mMapper->release(it.first))
+          << "failed to release handle " << it.first;
+      it.second--;
+    }
+  }
+  mHandles.clear();
+}
+
+sp<IMapper> Mapper::getRaw() const { return mMapper; }
+
+void Mapper::retain(const native_handle_t* handle) {
+  Error error = mMapper->retain(handle);
+  ASSERT_EQ(Error::NONE, error) << "failed to retain handle " << handle;
+
+  mHandles[handle]++;
+}
+
+void Mapper::release(const native_handle_t* handle) {
+  Error error = mMapper->release(handle);
+  ASSERT_EQ(Error::NONE, error) << "failed to release handle " << handle;
+
+  if (--mHandles[handle] == 0) {
+    mHandles.erase(handle);
+  }
+}
+
+Mapper::Dimensions Mapper::getDimensions(const native_handle_t* handle) {
+  Dimensions dimensions = {};
+  mMapper->getDimensions(handle, [&](const auto& tmpError, const auto& tmpWidth,
+                                     const auto& tmpHeight) {
+    ASSERT_EQ(Error::NONE, tmpError)
+        << "failed to get dimensions for handle " << handle;
+    dimensions.width = tmpWidth;
+    dimensions.height = tmpHeight;
+  });
+
+  return dimensions;
+}
+
+PixelFormat Mapper::getFormat(const native_handle_t* handle) {
+  PixelFormat format = static_cast<PixelFormat>(0);
+  mMapper->getFormat(handle, [&](const auto& tmpError, const auto& tmpFormat) {
+    ASSERT_EQ(Error::NONE, tmpError)
+        << "failed to get format for handle " << handle;
+    format = tmpFormat;
+  });
+
+  return format;
+}
+
+uint32_t Mapper::getLayerCount(const native_handle_t* handle) {
+  uint32_t count = 0;
+  mMapper->getLayerCount(
+      handle, [&](const auto& tmpError, const auto& tmpCount) {
+        ASSERT_EQ(Error::NONE, tmpError)
+            << "failed to get layer count for handle " << handle;
+        count = tmpCount;
+      });
+
+  return count;
+}
+
+uint64_t Mapper::getProducerUsageMask(const native_handle_t* handle) {
+  uint64_t usageMask = 0;
+  mMapper->getProducerUsageMask(
+      handle, [&](const auto& tmpError, const auto& tmpUsageMask) {
+        ASSERT_EQ(Error::NONE, tmpError)
+            << "failed to get producer usage mask for handle " << handle;
+        usageMask = tmpUsageMask;
+      });
+
+  return usageMask;
+}
+
+uint64_t Mapper::getConsumerUsageMask(const native_handle_t* handle) {
+  uint64_t usageMask = 0;
+  mMapper->getConsumerUsageMask(
+      handle, [&](const auto& tmpError, const auto& tmpUsageMask) {
+        ASSERT_EQ(Error::NONE, tmpError)
+            << "failed to get consumer usage mask for handle " << handle;
+        usageMask = tmpUsageMask;
+      });
+
+  return usageMask;
+}
+
+BackingStore Mapper::getBackingStore(const native_handle_t* handle) {
+  BackingStore backingStore = 0;
+  mMapper->getBackingStore(
+      handle, [&](const auto& tmpError, const auto& tmpBackingStore) {
+        ASSERT_EQ(Error::NONE, tmpError)
+            << "failed to get backing store for handle " << handle;
+        backingStore = tmpBackingStore;
+      });
+
+  return backingStore;
+}
+
+uint32_t Mapper::getStride(const native_handle_t* handle) {
+  uint32_t stride = 0;
+  mMapper->getStride(handle, [&](const auto& tmpError, const auto& tmpStride) {
+    ASSERT_EQ(Error::NONE, tmpError)
+        << "failed to get stride for handle " << handle;
+    stride = tmpStride;
+  });
+
+  return stride;
+}
+
+void* Mapper::lock(const native_handle_t* handle, uint64_t producerUsageMask,
+                   uint64_t consumerUsageMask,
+                   const IMapper::Rect& accessRegion, int acquireFence) {
+  NATIVE_HANDLE_DECLARE_STORAGE(acquireFenceStorage, 0, 1);
+  native_handle_t* acquireFenceHandle = nullptr;
+  if (acquireFence >= 0) {
+    acquireFenceHandle = native_handle_init(acquireFenceStorage, 0, 1);
+    acquireFenceHandle->data[0] = acquireFence;
+  }
+
+  void* data = nullptr;
+  mMapper->lock(
+      handle, producerUsageMask, consumerUsageMask, accessRegion,
+      acquireFenceHandle, [&](const auto& tmpError, const auto& tmpData) {
+        ASSERT_EQ(Error::NONE, tmpError) << "failed to lock handle " << handle;
+        data = tmpData;
+      });
+
+  if (acquireFence >= 0) {
+    close(acquireFence);
+  }
+
+  return data;
+}
+
+FlexLayout Mapper::lockFlex(const native_handle_t* handle,
+                            uint64_t producerUsageMask,
+                            uint64_t consumerUsageMask,
+                            const IMapper::Rect& accessRegion,
+                            int acquireFence) {
+  NATIVE_HANDLE_DECLARE_STORAGE(acquireFenceStorage, 0, 1);
+  native_handle_t* acquireFenceHandle = nullptr;
+  if (acquireFence >= 0) {
+    acquireFenceHandle = native_handle_init(acquireFenceStorage, 0, 1);
+    acquireFenceHandle->data[0] = acquireFence;
+  }
+
+  FlexLayout layout = {};
+  mMapper->lockFlex(handle, producerUsageMask, consumerUsageMask, accessRegion,
+                    acquireFenceHandle,
+                    [&](const auto& tmpError, const auto& tmpLayout) {
+                      ASSERT_EQ(Error::NONE, tmpError)
+                          << "failed to lockFlex handle " << handle;
+                      layout = tmpLayout;
+                    });
+
+  if (acquireFence >= 0) {
+    close(acquireFence);
+  }
+
+  return layout;
+}
+
+int Mapper::unlock(const native_handle_t* handle) {
+  int releaseFence = -1;
+  mMapper->unlock(handle, [&](const auto& tmpError,
+                              const auto& tmpReleaseFence) {
+    ASSERT_EQ(Error::NONE, tmpError) << "failed to unlock handle " << handle;
+
+    auto handle = tmpReleaseFence.getNativeHandle();
+    if (handle) {
+      ASSERT_EQ(0, handle->numInts) << "invalid fence handle " << handle;
+      if (handle->numFds == 1) {
+        releaseFence = dup(handle->data[0]);
+        ASSERT_LT(0, releaseFence) << "failed to dup fence fd";
+      } else {
+        ASSERT_EQ(0, handle->numFds) << " invalid fence handle " << handle;
+      }
+    }
+  });
+
+  return releaseFence;
+}
+
+const native_handle_t* Mapper::allocate(
+    std::unique_ptr<AllocatorClient>& allocatorClient,
+    const IAllocatorClient::BufferDescriptorInfo& info) {
+  BufferDescriptor descriptor = allocatorClient->createDescriptor(info);
+  if (::testing::Test::HasFatalFailure()) {
+    return nullptr;
+  }
+
+  Buffer buffer = allocatorClient->allocate(descriptor);
+  if (::testing::Test::HasFatalFailure()) {
+    allocatorClient->destroyDescriptor(descriptor);
+    return nullptr;
+  }
+
+  const native_handle_t* handle =
+      allocatorClient->exportHandle(descriptor, buffer);
+  if (handle) {
+    retain(handle);
+  }
+
+  allocatorClient->free(buffer);
+  allocatorClient->destroyDescriptor(descriptor);
+
+  return handle;
+}
+
+}  // namespace tests
+}  // namespace V2_0
+}  // namespace mapper
+}  // namespace graphics
+}  // namespace hardware
+}  // namespace android
diff --git a/graphics/mapper/2.0/vts/functional/VtsHalGraphicsMapperTestUtils.h b/graphics/mapper/2.0/vts/functional/VtsHalGraphicsMapperTestUtils.h
new file mode 100644
index 0000000..c186b00
--- /dev/null
+++ b/graphics/mapper/2.0/vts/functional/VtsHalGraphicsMapperTestUtils.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#ifndef VTS_HAL_GRAPHICS_MAPPER_UTILS
+#define VTS_HAL_GRAPHICS_MAPPER_UTILS
+
+#include <memory>
+#include <unordered_map>
+
+#include <android/hardware/graphics/mapper/2.0/IMapper.h>
+#include <utils/StrongPointer.h>
+
+#include "VtsHalGraphicsAllocatorTestUtils.h"
+
+namespace android {
+namespace hardware {
+namespace graphics {
+namespace mapper {
+namespace V2_0 {
+namespace tests {
+
+using android::hardware::graphics::common::V1_0::PixelFormat;
+using android::hardware::graphics::allocator::V2_0::IAllocatorClient;
+using android::hardware::graphics::allocator::V2_0::tests::AllocatorClient;
+
+// A wrapper to IMapper.
+class Mapper {
+ public:
+  Mapper();
+  ~Mapper();
+
+  sp<IMapper> getRaw() const;
+
+  void retain(const native_handle_t* handle);
+  void release(const native_handle_t* handle);
+
+  struct Dimensions {
+    uint32_t width;
+    uint32_t height;
+  };
+  Dimensions getDimensions(const native_handle_t* handle);
+
+  PixelFormat getFormat(const native_handle_t* handle);
+  uint32_t getLayerCount(const native_handle_t* handle);
+  uint64_t getProducerUsageMask(const native_handle_t* handle);
+  uint64_t getConsumerUsageMask(const native_handle_t* handle);
+  BackingStore getBackingStore(const native_handle_t* handle);
+  uint32_t getStride(const native_handle_t* handle);
+
+  // We use fd instead of hidl_handle in these functions to pass fences
+  // in and out of the mapper.  The ownership of the fd is always transferred
+  // with each of these functions.
+  void* lock(const native_handle_t* handle, uint64_t producerUsageMask,
+             uint64_t consumerUsageMask, const IMapper::Rect& accessRegion,
+             int acquireFence);
+  FlexLayout lockFlex(const native_handle_t* handle, uint64_t producerUsageMask,
+                      uint64_t consumerUsageMask,
+                      const IMapper::Rect& accessRegion, int acquireFence);
+  int unlock(const native_handle_t* handle);
+
+  // Requests AllocatorClient to allocate a buffer, export the handle, and
+  // register the handle with mapper.
+  const native_handle_t* allocate(
+      std::unique_ptr<AllocatorClient>& allocatorClient,
+      const IAllocatorClient::BufferDescriptorInfo& info);
+
+ private:
+  void init();
+
+  sp<IMapper> mMapper;
+
+  // Keep track of all registered (retained) handles.  When a test fails with
+  // ASSERT_*, the destructor will release the handles for the test.
+  std::unordered_map<const native_handle_t*, uint64_t> mHandles;
+};
+
+}  // namespace tests
+}  // namespace V2_0
+}  // namespace mapper
+}  // namespace graphics
+}  // namespace hardware
+}  // namespace android
+
+#endif  // VTS_HAL_GRAPHICS_MAPPER_UTILS
diff --git a/graphics/mapper/2.0/vts/functional/VtsHalGraphicsMapperV2_0TargetTest.cpp b/graphics/mapper/2.0/vts/functional/VtsHalGraphicsMapperV2_0TargetTest.cpp
index b2a37dd..bd8315e 100644
--- a/graphics/mapper/2.0/vts/functional/VtsHalGraphicsMapperV2_0TargetTest.cpp
+++ b/graphics/mapper/2.0/vts/functional/VtsHalGraphicsMapperV2_0TargetTest.cpp
@@ -17,10 +17,9 @@
 #define LOG_TAG "graphics_mapper_hidl_hal_test"
 
 #include <android-base/logging.h>
-#include <android/hardware/graphics/allocator/2.0/IAllocator.h>
-#include <android/hardware/graphics/mapper/2.0/IMapper.h>
 #include <VtsHalHidlTargetBaseTest.h>
 #include <sync/sync.h>
+#include "VtsHalGraphicsMapperTestUtils.h"
 
 namespace android {
 namespace hardware {
@@ -31,24 +30,14 @@
 namespace {
 
 using namespace android::hardware::graphics::allocator::V2_0;
-using namespace android::hardware::graphics::common::V1_0;
+using namespace android::hardware::graphics::allocator::V2_0::tests;
 
 class GraphicsMapperHidlTest : public ::testing::VtsHalHidlTargetBaseTest {
  protected:
   void SetUp() override {
-    mAllocator = ::testing::VtsHalHidlTargetBaseTest::getService<IAllocator>();
-    ASSERT_NE(mAllocator, nullptr);
-
-    mAllocator->createClient([this](const auto& error, const auto& client) {
-      if (error == Error::NONE) {
-        mAllocatorClient = client;
-      }
-    });
-    ASSERT_NE(mAllocatorClient, nullptr);
-
-    mMapper = ::testing::VtsHalHidlTargetBaseTest::getService<IMapper>();
-    ASSERT_NE(nullptr, mMapper.get());
-    ASSERT_FALSE(mMapper->isRemote());
+    ASSERT_NO_FATAL_FAILURE(mAllocator = std::make_unique<Allocator>());
+    ASSERT_NO_FATAL_FAILURE(mAllocatorClient = mAllocator->createClient());
+    ASSERT_NO_FATAL_FAILURE(mMapper = std::make_unique<Mapper>());
 
     mDummyDescriptorInfo.width = 64;
     mDummyDescriptorInfo.height = 64;
@@ -62,134 +51,51 @@
 
   void TearDown() override {}
 
-  const native_handle_t* allocate(
-      const IAllocatorClient::BufferDescriptorInfo& info) {
-    // create descriptor
-    Error err = Error::NO_RESOURCES;
-    BufferDescriptor descriptor;
-    mAllocatorClient->createDescriptor(
-        info, [&](const auto& tmpError, const auto& tmpDescriptor) {
-          err = tmpError;
-          descriptor = tmpDescriptor;
-        });
-    if (err != Error::NONE) {
-      return nullptr;
-    }
-
-    // allocate buffer
-    hidl_vec<BufferDescriptor> descriptors;
-    hidl_vec<Buffer> buffers;
-    descriptors.setToExternal(&descriptor, 1);
-    err = Error::NO_RESOURCES;
-    mAllocatorClient->allocate(
-        descriptors, [&](const auto& tmpError, const auto& tmpBuffers) {
-          err = tmpError;
-          buffers = tmpBuffers;
-        });
-    if ((err != Error::NONE && err != Error::NOT_SHARED) ||
-        buffers.size() != 1) {
-      mAllocatorClient->destroyDescriptor(descriptors[0]);
-      return nullptr;
-    }
-
-    // export handle
-    err = Error::NO_RESOURCES;
-    const native_handle_t* handle = nullptr;
-    mAllocatorClient->exportHandle(
-        descriptors[0], buffers[0],
-        [&](const auto& tmpError, const auto& tmpHandle) {
-          err = tmpError;
-          if (err != Error::NONE) {
-            return;
-          }
-
-          handle = native_handle_clone(tmpHandle);
-          if (!handle) {
-            err = Error::NO_RESOURCES;
-            return;
-          }
-
-          err = mMapper->retain(handle);
-          if (err != Error::NONE) {
-            native_handle_close(handle);
-            native_handle_delete(const_cast<native_handle_t*>(handle));
-            handle = nullptr;
-          }
-        });
-
-    mAllocatorClient->destroyDescriptor(descriptors[0]);
-    mAllocatorClient->free(buffers[0]);
-
-    if (err != Error::NONE) {
-      return nullptr;
-    }
-
-    return handle;
-  }
-
-  sp<IMapper> mMapper;
-
+  std::unique_ptr<Allocator> mAllocator;
+  std::unique_ptr<AllocatorClient> mAllocatorClient;
+  std::unique_ptr<Mapper> mMapper;
   IAllocatorClient::BufferDescriptorInfo mDummyDescriptorInfo{};
-
- private:
-  sp<IAllocator> mAllocator;
-  sp<IAllocatorClient> mAllocatorClient;
 };
 
 /**
  * Test IMapper::retain and IMapper::release.
  */
 TEST_F(GraphicsMapperHidlTest, RetainRelease) {
-  const native_handle_t* buffer = allocate(mDummyDescriptorInfo);
-  ASSERT_NE(buffer, nullptr);
+  const native_handle_t* buffer;
+  ASSERT_NO_FATAL_FAILURE(
+      buffer = mMapper->allocate(mAllocatorClient, mDummyDescriptorInfo));
 
   const int maxRefs = 10;
   for (int i = 0; i < maxRefs; i++) {
-    auto err = mMapper->retain(buffer);
-    EXPECT_EQ(Error::NONE, err);
+    ASSERT_NO_FATAL_FAILURE(mMapper->retain(buffer));
   }
   for (int i = 0; i < maxRefs; i++) {
-    auto err = mMapper->release(buffer);
-    EXPECT_EQ(Error::NONE, err);
+    ASSERT_NO_FATAL_FAILURE(mMapper->release(buffer));
   }
 
-  auto err = mMapper->release(buffer);
-  EXPECT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(mMapper->release(buffer));
 }
 
 /**
  * Test IMapper::get* getters.
  */
 TEST_F(GraphicsMapperHidlTest, Getters) {
-  const native_handle_t* buffer = allocate(mDummyDescriptorInfo);
-  ASSERT_NE(buffer, nullptr);
+  const native_handle_t* buffer;
+  ASSERT_NO_FATAL_FAILURE(
+      buffer = mMapper->allocate(mAllocatorClient, mDummyDescriptorInfo));
 
-  Error err = Error::NO_RESOURCES;
-  IAllocatorClient::BufferDescriptorInfo info{};
-  mMapper->getDimensions(buffer, [&](const auto& tmpError, const auto& tmpWidth,
-                                     const auto& tmpHeight) {
-    err = tmpError;
-    info.width = tmpWidth;
-    info.height = tmpHeight;
-  });
-  EXPECT_EQ(Error::NONE, err);
-  mMapper->getFormat(buffer, [&](const auto& tmpError, const auto& tmpFormat) {
-    err = tmpError;
-    info.format = tmpFormat;
-  });
-  EXPECT_EQ(Error::NONE, err);
-  mMapper->getProducerUsageMask(
-      buffer, [&](const auto& tmpError, const auto& tmpUsage) {
-        err = tmpError;
-        info.producerUsageMask = tmpUsage;
-      });
-  EXPECT_EQ(Error::NONE, err);
-  mMapper->getConsumerUsageMask(
-      buffer, [&](const auto& tmpError, const auto& tmpUsage) {
-        err = tmpError;
-        info.consumerUsageMask = tmpUsage;
-      });
-  EXPECT_EQ(Error::NONE, err);
+  IAllocatorClient::BufferDescriptorInfo info = {};
+
+  Mapper::Dimensions dimensions;
+  ASSERT_NO_FATAL_FAILURE(dimensions = mMapper->getDimensions(buffer));
+  info.width = dimensions.width;
+  info.height = dimensions.height;
+
+  ASSERT_NO_FATAL_FAILURE(info.format = mMapper->getFormat(buffer));
+  ASSERT_NO_FATAL_FAILURE(info.producerUsageMask =
+                              mMapper->getProducerUsageMask(buffer));
+  ASSERT_NO_FATAL_FAILURE(info.consumerUsageMask =
+                              mMapper->getConsumerUsageMask(buffer));
 
   EXPECT_EQ(mDummyDescriptorInfo.width, info.width);
   EXPECT_EQ(mDummyDescriptorInfo.height, info.height);
@@ -197,24 +103,11 @@
   EXPECT_EQ(mDummyDescriptorInfo.producerUsageMask, info.producerUsageMask);
   EXPECT_EQ(mDummyDescriptorInfo.consumerUsageMask, info.consumerUsageMask);
 
-  BackingStore store = 0;
-  mMapper->getBackingStore(buffer,
-                           [&](const auto& tmpError, const auto& tmpStore) {
-                             err = tmpError;
-                             store = tmpStore;
-                           });
-  EXPECT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(mMapper->getBackingStore(buffer));
 
-  uint32_t stride = 0;
-  mMapper->getStride(buffer, [&](const auto& tmpError, const auto& tmpStride) {
-    err = tmpError;
-    stride = tmpStride;
-  });
-  EXPECT_EQ(Error::NONE, err);
+  uint32_t stride;
+  ASSERT_NO_FATAL_FAILURE(stride = mMapper->getStride(buffer));
   EXPECT_LE(info.width, stride);
-
-  err = mMapper->release(buffer);
-  EXPECT_EQ(Error::NONE, err);
 }
 
 /**
@@ -222,79 +115,113 @@
  */
 TEST_F(GraphicsMapperHidlTest, LockBasic) {
   const auto& info = mDummyDescriptorInfo;
-  const native_handle_t* buffer = allocate(info);
-  ASSERT_NE(buffer, nullptr);
 
-  Error err = Error::NO_RESOURCES;
-  uint32_t stride = 0;
-  mMapper->getStride(buffer, [&](const auto& tmpError, const auto& tmpStride) {
-    err = tmpError;
-    stride = tmpStride;
-  });
-  EXPECT_EQ(Error::NONE, err);
+  const native_handle_t* buffer;
+  ASSERT_NO_FATAL_FAILURE(
+      buffer = mMapper->allocate(mAllocatorClient, mDummyDescriptorInfo));
+
+  uint32_t stride;
+  ASSERT_NO_FATAL_FAILURE(stride = mMapper->getStride(buffer));
 
   // lock buffer for writing
   const IMapper::Rect region{0, 0, static_cast<int32_t>(info.width),
                              static_cast<int32_t>(info.height)};
-  hidl_handle acquireFence(nullptr);
+  int fence = -1;
   uint32_t* data;
-  err = Error::NO_RESOURCES;
-  mMapper->lock(buffer, info.producerUsageMask, 0, region, acquireFence,
-          [&](const auto& tmpError, const auto& tmpData) {
-            err = tmpError;
-            data = static_cast<uint32_t*>(tmpData);
-          });
+  ASSERT_NO_FATAL_FAILURE(
+      data = static_cast<uint32_t*>(
+          mMapper->lock(buffer, info.producerUsageMask, 0, region, fence)));
 
-  if (err == Error::NONE) {
-    for (uint32_t y = 0; y < info.height; y++) {
-      for (uint32_t x = 0; x < info.width; x++) {
-        data[stride * y + x] = info.height * y + x;
-      }
+  for (uint32_t y = 0; y < info.height; y++) {
+    for (uint32_t x = 0; x < info.width; x++) {
+      data[stride * y + x] = info.height * y + x;
     }
-  } else {
-    EXPECT_EQ(Error::NONE, err);
   }
 
-  err = Error::NO_RESOURCES;
-  mMapper->unlock(buffer, [&](const auto& tmpError, const auto& tmpReleaseFence) {
-            err = tmpError;
-            auto handle = tmpReleaseFence.getNativeHandle();
-            if (handle && handle->numFds == 1) {
-                sync_wait(handle->data[0], -1);
-                close(handle->data[0]);
-            }
-          });
-  EXPECT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(fence = mMapper->unlock(buffer));
 
   // lock buffer for reading
-  mMapper->lock(buffer, 0, info.consumerUsageMask, region, acquireFence,
-          [&](const auto& tmpError, const auto& tmpData) {
-            err = tmpError;
-            data = static_cast<uint32_t*>(tmpData);
-          });
-  if (err == Error::NONE) {
-    for (uint32_t y = 0; y < info.height; y++) {
-      for (uint32_t x = 0; x < info.width; x++) {
-        EXPECT_EQ(info.height * y + x, data[stride * y + x]);
-      }
+  ASSERT_NO_FATAL_FAILURE(
+      data = static_cast<uint32_t*>(
+          mMapper->lock(buffer, 0, info.consumerUsageMask, region, fence)));
+  for (uint32_t y = 0; y < info.height; y++) {
+    for (uint32_t x = 0; x < info.width; x++) {
+      EXPECT_EQ(info.height * y + x, data[stride * y + x]);
     }
-  } else {
-    EXPECT_EQ(Error::NONE, err);
   }
 
-  err = Error::NO_RESOURCES;
-  mMapper->unlock(buffer, [&](const auto& tmpError, const auto& tmpReleaseFence) {
-            err = tmpError;
-            auto handle = tmpReleaseFence.getNativeHandle();
-            if (handle && handle->numFds == 1) {
-                sync_wait(handle->data[0], -1);
-                close(handle->data[0]);
-            }
-          });
-  EXPECT_EQ(Error::NONE, err);
+  ASSERT_NO_FATAL_FAILURE(fence = mMapper->unlock(buffer));
+  if (fence >= 0) {
+    close(fence);
+  }
+}
 
-  err = mMapper->release(buffer);
-  EXPECT_EQ(Error::NONE, err);
+/**
+ * Test IMapper::lockFlex.  This locks a YV12 buffer, and makes sure we can
+ * write to and read from it.
+ */
+TEST_F(GraphicsMapperHidlTest, LockFlexBasic) {
+  auto info = mDummyDescriptorInfo;
+  info.format = PixelFormat::YV12;
+
+  const native_handle_t* buffer;
+  ASSERT_NO_FATAL_FAILURE(buffer = mMapper->allocate(mAllocatorClient, info));
+
+  // lock buffer for writing
+  const IMapper::Rect region{0, 0, static_cast<int32_t>(info.width),
+                             static_cast<int32_t>(info.height)};
+  int fence = -1;
+  FlexLayout layout;
+  ASSERT_NO_FATAL_FAILURE(
+      layout =
+          mMapper->lockFlex(buffer, info.producerUsageMask, 0, region, fence));
+  ASSERT_EQ(FlexFormat::YCBCR, layout.format);
+  ASSERT_EQ(3u, layout.planes.size());
+
+  const auto y_stride = layout.planes[0].vIncrement;
+  const auto c_stride = layout.planes[1].vIncrement;
+  auto y_data = static_cast<uint8_t*>(layout.planes[0].topLeft);
+  auto cb_data = static_cast<uint8_t*>(layout.planes[1].topLeft);
+  auto cr_data = static_cast<uint8_t*>(layout.planes[2].topLeft);
+
+  for (uint32_t y = 0; y < info.height; y++) {
+    for (uint32_t x = 0; x < info.width; x++) {
+      auto val = static_cast<uint8_t>(info.height * y + x);
+
+      y_data[y_stride * y + x] = val;
+      if (y % 2 == 0 && x % 2 == 0) {
+        cb_data[c_stride * y / 2 + x / 2] = val;
+        cr_data[c_stride * y / 2 + x / 2] = val;
+      }
+    }
+  }
+
+  ASSERT_NO_FATAL_FAILURE(fence = mMapper->unlock(buffer));
+
+  // lock buffer for reading
+  ASSERT_NO_FATAL_FAILURE(
+      layout =
+          mMapper->lockFlex(buffer, 0, info.consumerUsageMask, region, fence));
+
+  y_data = static_cast<uint8_t*>(layout.planes[0].topLeft);
+  cb_data = static_cast<uint8_t*>(layout.planes[1].topLeft);
+  cr_data = static_cast<uint8_t*>(layout.planes[2].topLeft);
+  for (uint32_t y = 0; y < info.height; y++) {
+    for (uint32_t x = 0; x < info.width; x++) {
+      auto val = static_cast<uint8_t>(info.height * y + x);
+
+      EXPECT_EQ(val, y_data[y_stride * y + x]);
+      if (y % 2 == 0 && x % 2 == 0) {
+        EXPECT_EQ(val, cb_data[c_stride * y / 2 + x / 2]);
+        EXPECT_EQ(val, cr_data[c_stride * y / 2 + x / 2]);
+      }
+    }
+  }
+
+  ASSERT_NO_FATAL_FAILURE(fence = mMapper->unlock(buffer));
+  if (fence >= 0) {
+    close(fence);
+  }
 }
 
 }  // namespace anonymous