Make keymaster more self contained

Keymaster uses UniquePtr, a reimplementation of std::unique_ptr offered
by the Android framework. As keymaster becomes part of the trebbelized
HAL, it must build with the vndk. As such it must not use framework
headers. An attempt to replace UniquePtr with std::unique_ptr, which
is available in the vndk, failed because keymaster, i.e., parts thereof,
must also build and run in the Trusty environment which does not have
a full C++ STL.

This patch makes keymaster more self contained. To that end the
following was done by this patch.

 * Install a copy of UniquePtr.h in include/keymaster.
 * Add a tiny subset of STL symbols to keymaster.
 * Reorganize linking units and
 * build parts of keymaster with stl: "none".

libkeymaster1 was split into libkeymaster_portable and libkeymaster.
The former comprises all compilation units that are included
in the keymaster TA (trusted app) and must run on Trusty.
This library is built with the option stl: "none" to raise
compilation errors as soon as someone tries to use STL features.
A tiny subset of STL symbols, which are also available in Trusty
is weakly defined in keymaster_stl.cpp.
The latter library comprises some other functionality that is
used by the softkeymasterdevice on Android and may use the STL.

Bug: 37467707
Test: keymaster vts tests and keystore cts test
Change-Id: I884336e1a2d2c6402a2c7deb27010fd88b907b6b
Merged-In: I884336e1a2d2c6402a2c7deb27010fd88b907b6b
diff --git a/Android.bp b/Android.bp
index 654b076..d18e9cd 100644
--- a/Android.bp
+++ b/Android.bp
@@ -24,6 +24,7 @@
         "keymaster_tags.cpp",
         "logger.cpp",
         "serializable.cpp",
+        "keymaster_stl.cpp",
     ],
     cflags: [
         "-Wall",
@@ -31,6 +32,7 @@
         "-Wunused",
         "-DKEYMASTER_NAME_TAGS",
     ],
+    stl: "none",
     clang: true,
     // TODO(krasin): reenable coverage flags, when the new Clang toolchain is released.
     // Currently, if enabled, these flags will cause an internal error in Clang.
@@ -40,12 +42,12 @@
 
 }
 
-// libkeymaster1 contains almost everything needed for a keymaster1
+// libkeymaster_portable contains almost everything needed for a keymaster
 // implementation, lacking only a subclass of the (abstract) KeymasterContext
 // class to provide environment-specific services and a wrapper to translate from
 // the function-based keymaster HAL API to the message-based AndroidKeymaster API.
 cc_library_shared {
-    name: "libkeymaster1",
+    name: "libkeymaster_portable",
     vendor_available: true,
     srcs: [
         "aes_key.cpp",
@@ -57,20 +59,16 @@
         "asymmetric_key_factory.cpp",
         "attestation_record.cpp",
         "auth_encrypted_key_blob.cpp",
+        "authorization_set.cpp",
+        "ecdsa_operation.cpp",
         "ec_key.cpp",
         "ec_key_factory.cpp",
-        "ecdsa_operation.cpp",
-        "ecies_kem.cpp",
-        "hkdf.cpp",
-        "hmac.cpp",
         "hmac_key.cpp",
         "hmac_operation.cpp",
-        "integrity_assured_key_blob.cpp",
-        "iso18033kdf.cpp",
-        "kdf.cpp",
         "key.cpp",
         "keymaster_enforcement.cpp",
-        "nist_curve_key_exchange.cpp",
+        "keymaster_tags.cpp",
+        "logger.cpp",
         "ocb.c",
         "ocb_utils.cpp",
         "openssl_err.cpp",
@@ -80,7 +78,9 @@
         "rsa_key.cpp",
         "rsa_key_factory.cpp",
         "rsa_operation.cpp",
+        "serializable.cpp",
         "symmetric_key.cpp",
+        "keymaster_stl.cpp",
     ],
 
     shared_libs: [
@@ -91,6 +91,52 @@
         "-Wall",
         "-Werror",
         "-Wunused",
+        "-DBORINGSSL_NO_CXX",
+    ],
+    // NOTE: libkeymaster_portable must run unchanged in the trusty runtime environment.
+    // Therefore, it must not link against any c++ stl library. keymaster_stl.cpp
+    // weakly defines the subset of stl symbols required for this library to work
+    // and which are also available in the trusty context.
+    stl: "none",
+    clang: true,
+    clang_cflags: [
+        "-Wno-error=unused-const-variable",
+        "-Wno-error=unused-private-field",
+        // TODO(krasin): reenable coverage flags, when the new Clang toolchain is released.
+        // Currently, if enabled, these flags will cause an internal error in Clang.
+        "-fno-sanitize-coverage=edge,indirect-calls,8bit-counters,trace-cmp"
+    ],
+
+    export_include_dirs: ["include"],
+
+}
+
+// libkeymaster adds to libkeymaster_portable code that is needed by the softkeymaster device
+// to implement keymaster. This is sort of a staging area for functionality that may move
+// to libkeymaster_portalbe eventually. Unlike libkeymaster_portable, this library can use c++ stl
+// headers, but modules should avoid it if they are to be moved to libkeymaster_portable.
+cc_library_shared {
+    name: "libkeymaster",
+    vendor_available: true,
+    srcs: [
+        "ecies_kem.cpp",
+        "hkdf.cpp",
+        "hmac.cpp",
+        "integrity_assured_key_blob.cpp",
+        "iso18033kdf.cpp",
+        "kdf.cpp",
+        "nist_curve_key_exchange.cpp",
+    ],
+
+    shared_libs: [
+        "libcrypto",
+        "libkeymaster_portable",
+        "libkeymaster_messages",
+    ],
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wunused",
     ],
     clang: true,
     clang_cflags: [
@@ -142,7 +188,8 @@
 
     shared_libs: [
         "libkeymaster_messages",
-        "libkeymaster1",
+        "libkeymaster_portable",
+        "libkeymaster",
         "liblog",
         "libcrypto",
         "libcutils",
diff --git a/Android.mk b/Android.mk
index c70d9df..f33b871 100644
--- a/Android.mk
+++ b/Android.mk
@@ -43,7 +43,8 @@
 LOCAL_SHARED_LIBRARIES := \
 	libsoftkeymasterdevice \
 	libkeymaster_messages \
-	libkeymaster1 \
+	libkeymaster_portable \
+	libkeymaster \
 	libcrypto \
 	libsoftkeymaster
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
diff --git a/List.h b/List.h
index 403cd7f..59d7564 100644
--- a/List.h
+++ b/List.h
@@ -210,7 +210,7 @@
     /* insert before the current node; returns iterator at new node */
     iterator insert(iterator posn, const T& val) 
     {
-        _Node* newNode = new _Node(val);        // alloc & copy-construct
+        _Node* newNode = new(std::nothrow) _Node(val);        // alloc & copy-construct
         newNode->setNext(posn.getNode());
         newNode->setPrev(posn.getNode()->getPrev());
         posn.getNode()->getPrev()->setNext(newNode);
@@ -289,7 +289,7 @@
      * slightly uncouth storage alloc.
      */
     void prep() {
-        mpMiddle = (_Node*) new unsigned char[sizeof(_Node)];
+        mpMiddle = (_Node*) new(std::nothrow) unsigned char[sizeof(_Node)];
         mpMiddle->setPrev(mpMiddle);
         mpMiddle->setNext(mpMiddle);
     }
diff --git a/aes_key.cpp b/aes_key.cpp
index 6b784b7..53090fc 100644
--- a/aes_key.cpp
+++ b/aes_key.cpp
@@ -18,7 +18,7 @@
 
 #include <assert.h>
 
-#include <new>
+#include <keymaster/new>
 
 #include <openssl/err.h>
 #include <openssl/rand.h>
diff --git a/aes_operation.cpp b/aes_operation.cpp
index 4c5c88c..62c86a7 100644
--- a/aes_operation.cpp
+++ b/aes_operation.cpp
@@ -18,9 +18,9 @@
 
 #include <stdio.h>
 
-#include <new>
+#include <keymaster/new>
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 #include <openssl/aes.h>
 #include <openssl/err.h>
diff --git a/android_keymaster.cpp b/android_keymaster.cpp
index 5dc5253..d573cd2 100644
--- a/android_keymaster.cpp
+++ b/android_keymaster.cpp
@@ -19,12 +19,12 @@
 #include <assert.h>
 #include <string.h>
 
-#include <cstddef>
+#include <stddef.h>
 
 #include <openssl/rand.h>
 #include <openssl/x509.h>
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 #include <keymaster/android_keymaster_utils.h>
 #include <keymaster/key_factory.h>
@@ -66,7 +66,7 @@
 }  // anonymous namespace
 
 AndroidKeymaster::AndroidKeymaster(KeymasterContext* context, size_t operation_table_size)
-    : context_(context), operation_table_(new OperationTable(operation_table_size)) {}
+    : context_(context), operation_table_(new(std::nothrow) OperationTable(operation_table_size)) {}
 
 AndroidKeymaster::~AndroidKeymaster() {}
 
diff --git a/android_keymaster_messages.cpp b/android_keymaster_messages.cpp
index 83a1785..77276d1 100644
--- a/android_keymaster_messages.cpp
+++ b/android_keymaster_messages.cpp
@@ -478,7 +478,7 @@
     }
 
     certificate_chain.entry_count = entry_count;
-    certificate_chain.entries = new keymaster_blob_t[entry_count];
+    certificate_chain.entries = new (std::nothrow) keymaster_blob_t[entry_count];
     if (!certificate_chain.entries) {
         certificate_chain.entry_count = 0;
         return false;
diff --git a/android_keymaster_messages_test.cpp b/android_keymaster_messages_test.cpp
index c7133df..a933cf8 100644
--- a/android_keymaster_messages_test.cpp
+++ b/android_keymaster_messages_test.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 #include <gtest/gtest.h>
 
diff --git a/android_keymaster_utils.cpp b/android_keymaster_utils.cpp
index 5e92745..522611f 100644
--- a/android_keymaster_utils.cpp
+++ b/android_keymaster_utils.cpp
@@ -16,7 +16,7 @@
 
 #include <keymaster/android_keymaster_utils.h>
 
-#include <new>
+#include <keymaster/new>
 
 namespace keymaster {
 
diff --git a/asymmetric_key.cpp b/asymmetric_key.cpp
index 35406e6..2eca0ce 100644
--- a/asymmetric_key.cpp
+++ b/asymmetric_key.cpp
@@ -16,7 +16,7 @@
 
 #include "asymmetric_key.h"
 
-#include <new>
+#include <keymaster/new>
 
 #include <openssl/asn1.h>
 #include <openssl/stack.h>
@@ -76,7 +76,7 @@
     if (len < 0) {
         return TranslateLastOpenSslError();
     }
-    UniquePtr<uint8_t[]> asn1_key_usage(new uint8_t[len]);
+    UniquePtr<uint8_t[]> asn1_key_usage(new(std::nothrow) uint8_t[len]);
     if (!asn1_key_usage.get()) {
         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
     }
@@ -128,7 +128,7 @@
     if (key_data_length <= 0)
         return TranslateLastOpenSslError();
 
-    material->reset(new (std::nothrow) uint8_t[key_data_length]);
+    material->reset(new(std::nothrow) uint8_t[key_data_length]);
     if (material->get() == NULL)
         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
 
@@ -205,7 +205,7 @@
     if (len < 0)
         return TranslateLastOpenSslError();
 
-    uint8_t* data = new uint8_t[len];
+    uint8_t* data = new(std::nothrow) uint8_t[len];
     if (!data)
         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
 
@@ -227,7 +227,7 @@
     }
 
     chain->entry_count = entry_count;
-    chain->entries = new keymaster_blob_t[entry_count];
+    chain->entries = new(std::nothrow) keymaster_blob_t[entry_count];
     if (!chain->entries) {
         *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
         return false;
@@ -354,7 +354,9 @@
         return TranslateLastOpenSslError();
     }
 
-    UniquePtr<X509V3_CTX> x509v3_ctx(new X509V3_CTX);
+    UniquePtr<X509V3_CTX> x509v3_ctx(new(std::nothrow) X509V3_CTX);
+    if (!x509v3_ctx.get())
+        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
     *x509v3_ctx = {};
     X509V3_set_ctx(x509v3_ctx.get(), signing_cert.get(), certificate.get(), nullptr /* req */,
                    nullptr /* crl */, 0 /* flags */);
diff --git a/attestation_record.cpp b/attestation_record.cpp
index 9d543a5..a59148d 100644
--- a/attestation_record.cpp
+++ b/attestation_record.cpp
@@ -604,7 +604,7 @@
     if (len < 0)
         return TranslateLastOpenSslError();
     *asn1_key_desc_len = len;
-    asn1_key_desc->reset(new uint8_t[*asn1_key_desc_len]);
+    asn1_key_desc->reset(new(std::nothrow) uint8_t[*asn1_key_desc_len]);
     if (!asn1_key_desc->get())
         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
     uint8_t* p = asn1_key_desc->get();
diff --git a/authorization_set.cpp b/authorization_set.cpp
index 3f02109..0411075 100644
--- a/authorization_set.cpp
+++ b/authorization_set.cpp
@@ -21,7 +21,7 @@
 #include <stdlib.h>
 #include <string.h>
 
-#include <new>
+#include <keymaster/new>
 
 #include <keymaster/android_keymaster_utils.h>
 #include <keymaster/logger.h>
diff --git a/ecdsa_operation.h b/ecdsa_operation.h
index 7f68d82..054b844 100644
--- a/ecdsa_operation.h
+++ b/ecdsa_operation.h
@@ -20,7 +20,7 @@
 #include <openssl/ec.h>
 #include <openssl/evp.h>
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 #include "operation.h"
 
diff --git a/ecies_kem.cpp b/ecies_kem.cpp
index 2e31573..a95d28d 100644
--- a/ecies_kem.cpp
+++ b/ecies_kem.cpp
@@ -50,7 +50,7 @@
     }
     switch (kdf) {
     case KM_KDF_RFC5869_SHA256:
-        kdf_.reset(new Rfc5869Sha256Kdf());
+        kdf_.reset(new(std::nothrow) Rfc5869Sha256Kdf());
         break;
     default:
         LOG_E("Kdf %d is unsupported", kdf);
@@ -136,7 +136,7 @@
                        Buffer* output_key) {
 
     keymaster_error_t error;
-    key_exchange_.reset(new NistCurveKeyExchange(private_key, &error));
+    key_exchange_.reset(new(std::nothrow) NistCurveKeyExchange(private_key, &error));
     if (!key_exchange_.get() || error != KM_ERROR_OK) {
         return false;
     }
diff --git a/ecies_kem.h b/ecies_kem.h
index 8c1b330..91bc5ed 100644
--- a/ecies_kem.h
+++ b/ecies_kem.h
@@ -19,7 +19,7 @@
 
 #include "kem.h"
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 #include <openssl/ec.h>
 
 #include <keymaster/authorization_set.h>
diff --git a/hkdf.cpp b/hkdf.cpp
index 9727375..9bef1fd 100644
--- a/hkdf.cpp
+++ b/hkdf.cpp
@@ -16,7 +16,7 @@
 
 #include "hkdf.h"
 
-#include <new>
+#include <keymaster/new>
 
 #include <keymaster/android_keymaster_utils.h>
 
@@ -37,7 +37,7 @@
     if (salt_.get() != nullptr && salt_len_ > 0) {
         result = prk_hmac.Init(salt_.get(), salt_len_);
     } else {
-        UniquePtr<uint8_t[]> zeros(new uint8_t[digest_size_]);
+        UniquePtr<uint8_t[]> zeros(new(std::nothrow) uint8_t[digest_size_]);
         if (zeros.get() == nullptr)
             return false;
         /* If salt is not given, digest size of zeros are used. */
@@ -47,7 +47,7 @@
     if (!result)
         return false;
 
-    UniquePtr<uint8_t[]> pseudo_random_key(new uint8_t[digest_size_]);
+    UniquePtr<uint8_t[]> pseudo_random_key(new(std::nothrow) uint8_t[digest_size_]);
     if (pseudo_random_key.get() == nullptr || digest_size_ != prk_hmac.DigestLength())
         return false;
     result =
@@ -63,8 +63,8 @@
     if (num_blocks >= 256u)
         return false;
 
-    UniquePtr<uint8_t[]> buf(new uint8_t[digest_size_ + info_len + 1]);
-    UniquePtr<uint8_t[]> digest(new uint8_t[digest_size_]);
+    UniquePtr<uint8_t[]> buf(new(std::nothrow) uint8_t[digest_size_ + info_len + 1]);
+    UniquePtr<uint8_t[]> digest(new(std::nothrow) uint8_t[digest_size_]);
     if (buf.get() == nullptr || digest.get() == nullptr)
         return false;
     HmacSha256 hmac;
diff --git a/hkdf.h b/hkdf.h
index 9de39bf..de85cd1 100644
--- a/hkdf.h
+++ b/hkdf.h
@@ -21,7 +21,7 @@
 
 #include <keymaster/serializable.h>
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 namespace keymaster {
 
diff --git a/hmac_key.cpp b/hmac_key.cpp
index 40a8906..4ac42f1 100644
--- a/hmac_key.cpp
+++ b/hmac_key.cpp
@@ -16,7 +16,7 @@
 
 #include "hmac_key.h"
 
-#include <new>
+#include <keymaster/new>
 
 #include <openssl/err.h>
 #include <openssl/rand.h>
diff --git a/hmac_operation.cpp b/hmac_operation.cpp
index 7f21393..b3b4244 100644
--- a/hmac_operation.cpp
+++ b/hmac_operation.cpp
@@ -16,7 +16,7 @@
 
 #include "hmac_operation.h"
 
-#include <new>
+#include <keymaster/new>
 
 #include <openssl/evp.h>
 #include <openssl/hmac.h>
diff --git a/include/keymaster/UniquePtr.h b/include/keymaster/UniquePtr.h
new file mode 100644
index 0000000..62ded34
--- /dev/null
+++ b/include/keymaster/UniquePtr.h
@@ -0,0 +1,234 @@
+/*
+ * Copyright (C) 2010 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 INCLUDE_KEYMASTER_UNIQUEPTR_H_
+#define INCLUDE_KEYMASTER_UNIQUEPTR_H_
+
+#include <stddef.h> // for size_t
+
+namespace keymaster {
+
+// Default deleter for pointer types.
+template <typename T>
+struct DefaultDelete {
+    enum { type_must_be_complete = sizeof(T) };
+    DefaultDelete() {}
+    void operator()(T* p) const {
+        delete p;
+    }
+};
+
+// Default deleter for array types.
+template <typename T>
+struct DefaultDelete<T[]> {
+    enum { type_must_be_complete = sizeof(T) };
+    void operator()(T* p) const {
+        delete[] p;
+    }
+};
+
+// A smart pointer that deletes the given pointer on destruction.
+// Equivalent to C++0x's std::unique_ptr (a combination of boost::scoped_ptr
+// and boost::scoped_array).
+// Named to be in keeping with Android style but also to avoid
+// collision with any other implementation, until we can switch over
+// to unique_ptr.
+// Use thus:
+//   UniquePtr<C> c(new C);
+template <typename T, typename D = DefaultDelete<T> >
+class UniquePtr {
+public:
+    // Construct a new UniquePtr, taking ownership of the given raw pointer.
+    explicit UniquePtr(T* ptr = nullptr) : mPtr(ptr) {
+    }
+
+    ~UniquePtr() {
+        reset();
+    }
+
+    // Accessors.
+    T& operator*() const { return *mPtr; }
+    T* operator->() const { return mPtr; }
+    T* get() const { return mPtr; }
+
+    // Returns the raw pointer and hands over ownership to the caller.
+    // The pointer will not be deleted by UniquePtr.
+    T* release() __attribute__((warn_unused_result)) {
+        T* result = mPtr;
+        mPtr = nullptr;
+        return result;
+    }
+
+    // Takes ownership of the given raw pointer.
+    // If this smart pointer previously owned a different raw pointer, that
+    // raw pointer will be freed.
+    void reset(T* ptr = nullptr) {
+        if (ptr != mPtr) {
+            D()(mPtr);
+            mPtr = ptr;
+        }
+    }
+
+private:
+    // The raw pointer.
+    T* mPtr;
+
+    // Comparing unique pointers is probably a mistake, since they're unique.
+    template <typename T2> bool operator==(const UniquePtr<T2>& p) const;
+    template <typename T2> bool operator!=(const UniquePtr<T2>& p) const;
+
+    UniquePtr(const UniquePtr&) = delete;
+    UniquePtr & operator=(const UniquePtr&) = delete;
+};
+
+// Partial specialization for array types. Like std::unique_ptr, this removes
+// operator* and operator-> but adds operator[].
+template <typename T, typename D>
+class UniquePtr<T[], D> {
+public:
+    explicit UniquePtr(T* ptr = nullptr) : mPtr(ptr) {
+    }
+
+    ~UniquePtr() {
+        reset();
+    }
+
+    T& operator[](size_t i) const {
+        return mPtr[i];
+    }
+    T* get() const { return mPtr; }
+
+    T* release() __attribute__((warn_unused_result)) {
+        T* result = mPtr;
+        mPtr = nullptr;
+        return result;
+    }
+
+    void reset(T* ptr = nullptr) {
+        if (ptr != mPtr) {
+            D()(mPtr);
+            mPtr = ptr;
+        }
+    }
+
+private:
+    T* mPtr;
+
+    UniquePtr(const UniquePtr&) = delete;
+    UniquePtr & operator=(const UniquePtr&) = delete;
+};
+
+} // namespace keymaster
+
+#if UNIQUE_PTR_TESTS
+
+// Run these tests with:
+// g++ -g -DUNIQUE_PTR_TESTS -x c++ UniquePtr.h && ./a.out
+
+#include <stdio.h>
+using namespace keymaster;
+
+static void assert(bool b) {
+    if (!b) {
+        fprintf(stderr, "FAIL\n");
+        abort();
+    }
+    fprintf(stderr, "OK\n");
+}
+static int cCount = 0;
+struct C {
+    C() { ++cCount; }
+    ~C() { --cCount; }
+};
+static bool freed = false;
+struct Freer {
+    void operator()(int* p) {
+        assert(*p == 123);
+        free(p);
+        freed = true;
+    }
+};
+
+int main(int argc, char* argv[]) {
+    //
+    // UniquePtr<T> tests...
+    //
+
+    // Can we free a single object?
+    {
+        UniquePtr<C> c(new C);
+        assert(cCount == 1);
+    }
+    assert(cCount == 0);
+    // Does release work?
+    C* rawC;
+    {
+        UniquePtr<C> c(new C);
+        assert(cCount == 1);
+        rawC = c.release();
+    }
+    assert(cCount == 1);
+    delete rawC;
+    // Does reset work?
+    {
+        UniquePtr<C> c(new C);
+        assert(cCount == 1);
+        c.reset(new C);
+        assert(cCount == 1);
+    }
+    assert(cCount == 0);
+
+    //
+    // UniquePtr<T[]> tests...
+    //
+
+    // Can we free an array?
+    {
+        UniquePtr<C[]> cs(new C[4]);
+        assert(cCount == 4);
+    }
+    assert(cCount == 0);
+    // Does release work?
+    {
+        UniquePtr<C[]> c(new C[4]);
+        assert(cCount == 4);
+        rawC = c.release();
+    }
+    assert(cCount == 4);
+    delete[] rawC;
+    // Does reset work?
+    {
+        UniquePtr<C[]> c(new C[4]);
+        assert(cCount == 4);
+        c.reset(new C[2]);
+        assert(cCount == 2);
+    }
+    assert(cCount == 0);
+
+    //
+    // Custom deleter tests...
+    //
+    assert(!freed);
+    {
+        UniquePtr<int, Freer> i(reinterpret_cast<int*>(malloc(sizeof(int))));
+        *i = 123;
+    }
+    assert(freed);
+    return 0;
+}
+#endif
+
+#endif  // INCLUDE_KEYMASTER_UNIQUEPTR_H_
diff --git a/include/keymaster/android_keymaster_utils.h b/include/keymaster/android_keymaster_utils.h
index 699f731..3da09a8 100644
--- a/include/keymaster/android_keymaster_utils.h
+++ b/include/keymaster/android_keymaster_utils.h
@@ -21,7 +21,7 @@
 #include <string.h>
 #include <time.h>  // for time_t.
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 #include <hardware/keymaster_defs.h>
 #include <keymaster/serializable.h>
diff --git a/include/keymaster/authorization_set.h b/include/keymaster/authorization_set.h
index bebbfff..20dd478 100644
--- a/include/keymaster/authorization_set.h
+++ b/include/keymaster/authorization_set.h
@@ -17,7 +17,7 @@
 #ifndef SYSTEM_KEYMASTER_AUTHORIZATION_SET_H_
 #define SYSTEM_KEYMASTER_AUTHORIZATION_SET_H_
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 #include <hardware/keymaster_defs.h>
 #include <keymaster/keymaster_tags.h>
diff --git a/include/keymaster/new b/include/keymaster/new
new file mode 100644
index 0000000..7ffedee
--- /dev/null
+++ b/include/keymaster/new
@@ -0,0 +1,32 @@
+/*
+**
+** Copyright 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 INCLUDE_KEYMASTER_NEW_
+#define INCLUDE_KEYMASTER_NEW_
+
+#include <stddef.h>
+
+namespace std {
+struct nothrow_t;
+extern const nothrow_t nothrow;
+}
+void* operator new(size_t __sz, const std::nothrow_t&);
+void* operator new[](size_t __sz, const std::nothrow_t&);
+void operator delete(void* ptr);
+void operator delete[](void* ptr);
+
+#endif  // INCLUDE_KEYMASTER_NEW_
diff --git a/include/keymaster/serializable.h b/include/keymaster/serializable.h
index 58bfcca..acdd144 100644
--- a/include/keymaster/serializable.h
+++ b/include/keymaster/serializable.h
@@ -21,10 +21,11 @@
 #include <stdlib.h>
 #include <string.h>
 
-#include <cstddef>
-#include <new>
+#include <stddef.h>
+#include <keymaster/new>
+// #include <new>
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 namespace keymaster {
 
diff --git a/include/keymaster/soft_keymaster_device.h b/include/keymaster/soft_keymaster_device.h
index 6663ac4..2e82448 100644
--- a/include/keymaster/soft_keymaster_device.h
+++ b/include/keymaster/soft_keymaster_device.h
@@ -28,7 +28,7 @@
 #include <keymaster/android_keymaster.h>
 #include <keymaster/soft_keymaster_context.h>
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 namespace keymaster {
 
diff --git a/integrity_assured_key_blob.cpp b/integrity_assured_key_blob.cpp
index 5c317a3..1b8c8cc 100644
--- a/integrity_assured_key_blob.cpp
+++ b/integrity_assured_key_blob.cpp
@@ -18,7 +18,7 @@
 
 #include <assert.h>
 
-#include <new>
+#include <keymaster/new>
 
 #include <openssl/hmac.h>
 #include <openssl/mem.h>
diff --git a/iso18033kdf.cpp b/iso18033kdf.cpp
index 3de0fdf..89c71ed 100644
--- a/iso18033kdf.cpp
+++ b/iso18033kdf.cpp
@@ -17,8 +17,6 @@
 #include "iso18033kdf.h"
 #include "openssl_utils.h"
 
-#include <algorithm>
-
 #include <openssl/evp.h>
 
 namespace keymaster {
diff --git a/iso18033kdf.h b/iso18033kdf.h
index 40fd2d6..4b53618 100644
--- a/iso18033kdf.h
+++ b/iso18033kdf.h
@@ -23,7 +23,7 @@
 
 #include <keymaster/serializable.h>
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 namespace keymaster {
 
diff --git a/kdf.h b/kdf.h
index b90d2bc..3286c89 100644
--- a/kdf.h
+++ b/kdf.h
@@ -21,7 +21,7 @@
 #include <keymaster/android_keymaster_utils.h>
 #include <keymaster/serializable.h>
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 namespace keymaster {
 
diff --git a/kdf1.h b/kdf1.h
index fab1ef7..a2b0c59 100644
--- a/kdf1.h
+++ b/kdf1.h
@@ -23,7 +23,7 @@
 
 #include <keymaster/serializable.h>
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 namespace keymaster {
 
diff --git a/kdf2.h b/kdf2.h
index 1df97ef..28832fb 100644
--- a/kdf2.h
+++ b/kdf2.h
@@ -23,7 +23,7 @@
 
 #include <keymaster/serializable.h>
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 namespace keymaster {
 
diff --git a/key.h b/key.h
index 9fb4063..8bbd1f1 100644
--- a/key.h
+++ b/key.h
@@ -17,7 +17,7 @@
 #ifndef SYSTEM_KEYMASTER_KEY_H_
 #define SYSTEM_KEYMASTER_KEY_H_
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 #include <hardware/keymaster_defs.h>
 
diff --git a/keymaster_stl.cpp b/keymaster_stl.cpp
new file mode 100644
index 0000000..a18823c
--- /dev/null
+++ b/keymaster_stl.cpp
@@ -0,0 +1,48 @@
+/*
+**
+** Copyright 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 <keymaster/new>
+#include <stdlib.h>
+
+namespace std {
+struct nothrow_t {};
+}
+
+const std::nothrow_t __attribute__((weak)) std::nothrow = {};
+
+void* __attribute__((weak)) operator new(size_t __sz, const std::nothrow_t&) {
+    return malloc(__sz);
+}
+void* __attribute__((weak)) operator new[](size_t __sz, const std::nothrow_t&) {
+    return malloc(__sz);
+}
+
+void __attribute__((weak)) operator delete(void* ptr) {
+    if (ptr)
+        free(ptr);
+}
+
+void __attribute__((weak)) operator delete[](void* ptr) {
+    if (ptr)
+        free(ptr);
+}
+
+extern "C" {
+void __attribute__((weak)) __cxa_pure_virtual() {
+    abort();
+}
+}
diff --git a/nist_curve_key_exchange.h b/nist_curve_key_exchange.h
index 0a93882..4b2a016 100644
--- a/nist_curve_key_exchange.h
+++ b/nist_curve_key_exchange.h
@@ -22,7 +22,7 @@
 #include <keymaster/authorization_set.h>
 #include <hardware/keymaster_defs.h>
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 #include "openssl_utils.h"
 
diff --git a/ocb_utils.cpp b/ocb_utils.cpp
index 7038da0..afcf3cc 100644
--- a/ocb_utils.cpp
+++ b/ocb_utils.cpp
@@ -18,7 +18,7 @@
 
 #include <assert.h>
 
-#include <new>
+#include <keymaster/new>
 
 #include <openssl/aes.h>
 #include <openssl/sha.h>
diff --git a/openssl_utils.cpp b/openssl_utils.cpp
index 5d2cb1c..9da984e 100644
--- a/openssl_utils.cpp
+++ b/openssl_utils.cpp
@@ -62,12 +62,6 @@
     }
 }
 
-void convert_bn_to_blob(BIGNUM* bn, keymaster_blob_t* blob) {
-    blob->data_length = BN_num_bytes(bn);
-    blob->data = new uint8_t[blob->data_length];
-    BN_bn2bin(bn, const_cast<uint8_t*>(blob->data));
-}
-
 static int convert_to_evp(keymaster_algorithm_t algorithm) {
     switch (algorithm) {
     case KM_ALGORITHM_RSA:
diff --git a/openssl_utils.h b/openssl_utils.h
index 9fa6ec1..a8cd71e 100644
--- a/openssl_utils.h
+++ b/openssl_utils.h
@@ -24,7 +24,7 @@
 #include <openssl/rsa.h>
 #include <openssl/x509.h>
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 #include <hardware/keymaster_defs.h>
 
diff --git a/operation_table.cpp b/operation_table.cpp
index d30885e..533f754 100644
--- a/operation_table.cpp
+++ b/operation_table.cpp
@@ -16,7 +16,7 @@
 
 #include "operation_table.h"
 
-#include <new>
+#include <keymaster/new>
 
 #include <openssl/rand.h>
 
diff --git a/operation_table.h b/operation_table.h
index c840ad9..0f3f096 100644
--- a/operation_table.h
+++ b/operation_table.h
@@ -17,7 +17,7 @@
 #ifndef SYSTEM_KEYMASTER_OPERATION_TABLE_H
 #define SYSTEM_KEYMASTER_OPERATION_TABLE_H
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 #include <hardware/keymaster_defs.h>
 
diff --git a/rsa_key_factory.cpp b/rsa_key_factory.cpp
index 4cae693..49e8edd 100644
--- a/rsa_key_factory.cpp
+++ b/rsa_key_factory.cpp
@@ -16,7 +16,7 @@
 
 #include <keymaster/rsa_key_factory.h>
 
-#include <new>
+#include <keymaster/new>
 
 #include <keymaster/keymaster_context.h>
 
diff --git a/rsa_operation.cpp b/rsa_operation.cpp
index ce8d2f3..c44a188 100644
--- a/rsa_operation.cpp
+++ b/rsa_operation.cpp
@@ -18,7 +18,7 @@
 
 #include <limits.h>
 
-#include <new>
+#include <keymaster/new>
 
 #include <openssl/err.h>
 
@@ -307,7 +307,7 @@
 static keymaster_error_t zero_pad_left(UniquePtr<uint8_t[]>* dest, size_t padded_len, Buffer& src) {
     assert(padded_len > src.available_read());
 
-    dest->reset(new uint8_t[padded_len]);
+    dest->reset(new(std::nothrow) uint8_t[padded_len]);
     if (!dest->get())
         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
 
diff --git a/rsa_operation.h b/rsa_operation.h
index 669b21a..6393045 100644
--- a/rsa_operation.h
+++ b/rsa_operation.h
@@ -17,7 +17,7 @@
 #ifndef SYSTEM_KEYMASTER_RSA_OPERATION_H_
 #define SYSTEM_KEYMASTER_RSA_OPERATION_H_
 
-#include <UniquePtr.h>
+#include <keymaster/UniquePtr.h>
 
 #include <openssl/evp.h>
 #include <openssl/rsa.h>
diff --git a/serializable.cpp b/serializable.cpp
index 94b92d0..82f93d2 100644
--- a/serializable.cpp
+++ b/serializable.cpp
@@ -18,7 +18,7 @@
 
 #include <assert.h>
 
-#include <new>
+#include <keymaster/new>
 
 #include <keymaster/android_keymaster_utils.h>