Move HidlSupport and IServiceManager from libhwbinder.

libhidl will contain data types and functionality that
is independent from libhwbinder, such as hidl_vec,
hidl_string, etc.

libhidl also contains an implementation of the service
manager interface. Initially that implementation is
exactly the same as the servicemanager we had in libhwbinder,
but eventually it should be capable of passing out
pass-through or remote HAL interfaces as well. Therefore,
the servicemanager belongs more in libhidl than in libhwbinder.

This initial version of the library still links against
libhwbinder because of the following dependencies:
- hidl_vec/hidl_string have methods for (de)serialization
  to/from a Parcel
- IServiceManager requires instantiation of a proxy for
  the hwbinder ServiceManager.

These can be dealt with in the future, if we deem it necessary,
since they don't leak through to clients; clients can link
against libhidl only when we have the other changes to the
class hierarchy in place.

Bug: 30839546
Change-Id: Ib05de8c98ba8a807618a0b2e37d809a29d2de9ca
diff --git a/Android.mk b/Android.mk
new file mode 100644
index 0000000..467090f
--- /dev/null
+++ b/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2016 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.
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libhidl
+LOCAL_SHARED_LIBRARIES := libbase liblog libutils libhwbinder
+LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := libbase libutils
+
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+
+LOCAL_CLANG := true
+LOCAL_SANITIZE := integer
+LOCAL_SRC_FILES := \
+	HidlSupport.cpp \
+	IServiceManager.cpp \
+	Static.cpp
+
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
+LOCAL_MULTILIB := both
+LOCAL_COMPATIBILITY_SUITE := vts
+include $(BUILD_SHARED_LIBRARY)
diff --git a/HidlSupport.cpp b/HidlSupport.cpp
new file mode 100644
index 0000000..71ac2b3
--- /dev/null
+++ b/HidlSupport.cpp
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2016 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 <hidl/HidlSupport.h>
+
+namespace android {
+namespace hardware {
+
+static const char *const kEmptyString = "";
+
+hidl_string::hidl_string()
+    : mBuffer(const_cast<char *>(kEmptyString)),
+      mSize(0),
+      mOwnsBuffer(true) {
+}
+
+hidl_string::~hidl_string() {
+    clear();
+}
+
+hidl_string::hidl_string(const hidl_string &other)
+    : mBuffer(const_cast<char *>(kEmptyString)),
+      mSize(0),
+      mOwnsBuffer(true) {
+    setTo(other.c_str(), other.size());
+}
+
+hidl_string &hidl_string::operator=(const hidl_string &other) {
+    if (this != &other) {
+        setTo(other.c_str(), other.size());
+    }
+
+    return *this;
+}
+
+hidl_string &hidl_string::operator=(const char *s) {
+    return setTo(s, strlen(s));
+}
+
+hidl_string &hidl_string::setTo(const char *data, size_t size) {
+    clear();
+
+    mBuffer = (char *)malloc(size + 1);
+    memcpy(mBuffer, data, size);
+    mBuffer[size] = '\0';
+
+    mSize = size;
+    mOwnsBuffer = true;
+
+    return *this;
+}
+
+void hidl_string::clear() {
+    if (mOwnsBuffer && (mBuffer != kEmptyString)) {
+        free(mBuffer);
+    }
+
+    mBuffer = const_cast<char *>(kEmptyString);
+    mSize = 0;
+    mOwnsBuffer = true;
+}
+
+void hidl_string::setToExternal(const char *data, size_t size) {
+    clear();
+
+    mBuffer = const_cast<char *>(data);
+    mSize = size;
+    mOwnsBuffer = false;
+}
+
+const char *hidl_string::c_str() const {
+    return mBuffer ? mBuffer : "";
+}
+
+size_t hidl_string::size() const {
+    return mSize;
+}
+
+bool hidl_string::empty() const {
+    return mSize == 0;
+}
+
+status_t hidl_string::readEmbeddedFromParcel(
+        const Parcel &parcel, size_t parentHandle, size_t parentOffset) {
+    const void *ptr = parcel.readEmbeddedBuffer(
+            nullptr /* buffer_handle */,
+            parentHandle,
+            parentOffset + offsetof(hidl_string, mBuffer));
+
+    return ptr != NULL ? OK : UNKNOWN_ERROR;
+}
+
+status_t hidl_string::writeEmbeddedToParcel(
+        Parcel *parcel, size_t parentHandle, size_t parentOffset) const {
+    return parcel->writeEmbeddedBuffer(
+            mBuffer,
+            mSize + 1,
+            nullptr /* handle */,
+            parentHandle,
+            parentOffset + offsetof(hidl_string, mBuffer));
+}
+
+}  // namespace hardware
+}  // namespace android
+
+
diff --git a/IServiceManager.cpp b/IServiceManager.cpp
new file mode 100644
index 0000000..ccbe28d
--- /dev/null
+++ b/IServiceManager.cpp
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#define LOG_TAG "HwServiceManager"
+
+#include <hidl/IServiceManager.h>
+#include <hidl/Static.h>
+
+#include <utils/Log.h>
+#include <hwbinder/IPCThreadState.h>
+#include <hwbinder/Parcel.h>
+#include <hwbinder/Static.h>
+#include <utils/String8.h>
+#include <utils/SystemClock.h>
+
+#include <unistd.h>
+
+
+namespace android {
+namespace hardware {
+sp<IServiceManager> defaultServiceManager()
+{
+    if (gDefaultServiceManager != NULL) return gDefaultServiceManager;
+
+    {
+        AutoMutex _l(gDefaultServiceManagerLock);
+        while (gDefaultServiceManager == NULL) {
+            gDefaultServiceManager = interface_cast<IServiceManager>(
+                ProcessState::self()->getContextObject(NULL));
+            if (gDefaultServiceManager == NULL)
+                sleep(1);
+        }
+    }
+
+    return gDefaultServiceManager;
+}
+
+// ----------------------------------------------------------------------
+
+class BpServiceManager : public BpInterface<IServiceManager>
+{
+public:
+    explicit BpServiceManager(const sp<IBinder>& impl)
+        : BpInterface<IServiceManager>(impl)
+    {
+    }
+
+    virtual sp<IBinder> getService(const String16& name, const hidl_version& version) const
+    {
+        unsigned n;
+        for (n = 0; n < 5; n++){
+            sp<IBinder> svc = checkService(name, version);
+            if (svc != NULL) return svc;
+            ALOGI("Waiting for service %s...\n", String8(name).string());
+            sleep(1);
+        }
+        return NULL;
+    }
+
+    virtual sp<IBinder> checkService( const String16& name, const hidl_version& version) const
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
+        data.writeString16(name);
+        version.writeToParcel(data);
+        remote()->transact(CHECK_SERVICE_TRANSACTION, data, &reply);
+        return reply.readStrongBinder();
+    }
+
+    virtual status_t addService(const String16& name,
+            const sp<IBinder>& service, const hidl_version& version,
+            bool allowIsolated)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
+        data.writeString16(name);
+        data.writeStrongBinder(service);
+        version.writeToParcel(data);
+        data.writeInt32(allowIsolated ? 1 : 0);
+        status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);
+        return err == NO_ERROR ? reply.readExceptionCode() : err;
+    }
+
+    virtual Vector<String16> listServices()
+    {
+        Vector<String16> res;
+        int n = 0;
+
+        for (;;) {
+            Parcel data, reply;
+            data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
+            data.writeInt32(n++);
+            status_t err = remote()->transact(LIST_SERVICES_TRANSACTION, data, &reply);
+            if (err != NO_ERROR)
+                break;
+            res.add(reply.readString16());
+        }
+        return res;
+    }
+};
+
+IMPLEMENT_HWBINDER_META_INTERFACE(ServiceManager, "android.hardware.IServiceManager");
+
+}; // namespace hardware
+}; // namespace android
diff --git a/Static.cpp b/Static.cpp
new file mode 100644
index 0000000..a7dc08f
--- /dev/null
+++ b/Static.cpp
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+// All static variables go here, to control initialization and
+// destruction order in the library.
+
+#include <hidl/Static.h>
+
+namespace android {
+namespace hardware {
+
+Mutex gDefaultServiceManagerLock;
+sp<IServiceManager> gDefaultServiceManager;
+
+}   // namespace hardware
+}   // namespace android
diff --git a/include/hidl/HidlSupport.h b/include/hidl/HidlSupport.h
new file mode 100644
index 0000000..c36b7ec
--- /dev/null
+++ b/include/hidl/HidlSupport.h
@@ -0,0 +1,224 @@
+/*
+ * Copyright (C) 2016 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 ANDROID_HIDL_SUPPORT_H
+#define ANDROID_HIDL_SUPPORT_H
+
+#include <hwbinder/Parcel.h>
+
+namespace android {
+namespace hardware {
+
+struct hidl_string {
+    hidl_string();
+    ~hidl_string();
+
+    hidl_string(const hidl_string &);
+    hidl_string &operator=(const hidl_string &);
+
+    const char *c_str() const;
+    size_t size() const;
+    bool empty() const;
+
+    hidl_string &operator=(const char *s);
+    void clear();
+
+    // Reference an external char array. Ownership is _not_ transferred.
+    // Caller is responsible for ensuring that underlying memory is valid
+    // for the lifetime of this hidl_string.
+    void setToExternal(const char *data, size_t size);
+
+    status_t readEmbeddedFromParcel(
+            const Parcel &parcel, size_t parentHandle, size_t parentOffset);
+
+    status_t writeEmbeddedToParcel(
+            Parcel *parcel, size_t parentHandle, size_t parentOffset) const;
+
+private:
+    char *mBuffer;
+    size_t mSize;  // NOT including the terminating '\0'.
+    bool mOwnsBuffer;
+
+    hidl_string &setTo(const char *data, size_t size);
+};
+
+template<typename T>
+struct hidl_vec {
+    hidl_vec()
+        : mBuffer(NULL),
+          mSize(0),
+          mOwnsBuffer(true) {
+    }
+
+    hidl_vec(const hidl_vec<T> &other)
+        : mBuffer(NULL),
+          mSize(0),
+          mOwnsBuffer(true) {
+        *this = other;
+    }
+
+    ~hidl_vec() {
+        if (mOwnsBuffer) {
+            delete[] mBuffer;
+        }
+        mBuffer = NULL;
+    }
+
+    // Reference an existing array _WITHOUT_ taking ownership. It is the
+    // caller's responsibility to ensure that the underlying memory stays
+    // valid for the lifetime of this hidl_vec.
+    void setToExternal(T *data, size_t size) {
+        if (mOwnsBuffer) {
+            delete [] mBuffer;
+        }
+        mBuffer = data;
+        mSize = size;
+        mOwnsBuffer = false;
+    }
+
+    hidl_vec &operator=(const hidl_vec &other) {
+        if (this != &other) {
+            if (mOwnsBuffer) {
+                delete[] mBuffer;
+            }
+            mBuffer = NULL;
+            mSize = other.mSize;
+            mOwnsBuffer = true;
+            if (mSize > 0) {
+                mBuffer = new T[mSize];
+                for (size_t i = 0; i < mSize; ++i) {
+                    mBuffer[i] = other.mBuffer[i];
+                }
+            }
+        }
+
+        return *this;
+    }
+
+    size_t size() const {
+        return mSize;
+    }
+
+    T &operator[](size_t index) {
+        return mBuffer[index];
+    }
+
+    const T &operator[](size_t index) const {
+        return mBuffer[index];
+    }
+
+    void resize(size_t size) {
+        T *newBuffer = new T[size];
+
+        for (size_t i = 0; i < std::min(size, mSize); ++i) {
+            newBuffer[i] = mBuffer[i];
+        }
+
+        if (mOwnsBuffer) {
+            delete[] mBuffer;
+        }
+        mBuffer = newBuffer;
+
+        mSize = size;
+        mOwnsBuffer = true;
+    }
+
+    status_t readEmbeddedFromParcel(
+            const Parcel &parcel,
+            size_t parentHandle,
+            size_t parentOffset,
+            size_t *handle);
+
+    status_t writeEmbeddedToParcel(
+            Parcel *parcel,
+            size_t parentHandle,
+            size_t parentOffset,
+            size_t *handle) const;
+
+private:
+    T *mBuffer;
+    size_t mSize;
+    bool mOwnsBuffer;
+};
+
+template<typename T>
+status_t hidl_vec<T>::readEmbeddedFromParcel(
+        const Parcel &parcel,
+        size_t parentHandle,
+        size_t parentOffset,
+        size_t *handle) {
+    const void *ptr = parcel.readEmbeddedBuffer(
+            handle,
+            parentHandle,
+            parentOffset + offsetof(hidl_vec<T>, mBuffer));
+
+    return ptr != NULL ? OK : UNKNOWN_ERROR;
+}
+
+template<typename T>
+status_t hidl_vec<T>::writeEmbeddedToParcel(
+        Parcel *parcel,
+        size_t parentHandle,
+        size_t parentOffset,
+        size_t *handle) const {
+    return parcel->writeEmbeddedBuffer(
+            mBuffer,
+            sizeof(T) * mSize,
+            handle,
+            parentHandle,
+            parentOffset + offsetof(hidl_vec<T>, mBuffer));
+}
+
+// ----------------------------------------------------------------------
+// Version functions
+struct hidl_version {
+public:
+    hidl_version(uint16_t major, uint16_t minor) : mMajor(major), mMinor(minor) {};
+
+    bool operator==(const hidl_version& other) {
+        return (mMajor == other.get_major() && mMinor == other.get_minor());
+    }
+    uint16_t get_major() const { return mMajor; }
+    uint16_t get_minor() const { return mMinor; }
+
+    android::status_t writeToParcel(android::hardware::Parcel& parcel) const {
+        return parcel.writeUint32((uint32_t) mMajor << 16 | mMinor);
+    }
+
+    static hidl_version* readFromParcel(const android::hardware::Parcel& parcel) {
+        uint32_t version;
+        android::status_t status = parcel.readUint32(&version);
+        if (status != OK) {
+            return nullptr;
+        } else {
+            return new hidl_version(version >> 16, version & 0xFFFF);
+        }
+    }
+
+private:
+    uint16_t mMajor;
+    uint16_t mMinor;
+};
+
+inline android::hardware::hidl_version make_hidl_version(uint16_t major, uint16_t minor) {
+    return hidl_version(major,minor);
+}
+
+}  // namespace hardware
+}  // namespace android
+
+#endif  // ANDROID_HIDL_SUPPORT_H
+
diff --git a/include/hidl/IServiceManager.h b/include/hidl/IServiceManager.h
new file mode 100644
index 0000000..5d6155a
--- /dev/null
+++ b/include/hidl/IServiceManager.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2016 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 ANDROID_HARDWARE_ISERVICE_MANAGER_H
+#define ANDROID_HARDWARE_ISERVICE_MANAGER_H
+
+#include <hidl/HidlSupport.h>
+#include <hwbinder/IInterface.h>
+#include <hwbinder/Parcel.h>
+#include <utils/String16.h>
+
+namespace android {
+namespace hardware {
+
+class IServiceManager : public IInterface
+{
+public:
+    DECLARE_HWBINDER_META_INTERFACE(ServiceManager);
+
+    /**
+     * Retrieve an existing service, blocking for a few seconds
+     * if it doesn't yet exist.
+     */
+    virtual sp<IBinder>         getService( const String16& name,
+                                            const android::hardware::hidl_version& version
+                                          ) const = 0;
+
+    /**
+     * Retrieve an existing service, non-blocking.
+     */
+    virtual sp<IBinder>         checkService( const String16& name,
+                                              const android::hardware::hidl_version& version
+                                            ) const = 0;
+
+    /**
+     * Register a service.
+     */
+    virtual status_t            addService( const String16& name,
+                                            const sp<IBinder>& service,
+                                            const android::hardware::hidl_version& version,
+                                            bool allowIsolated = false) = 0;
+
+    enum {
+        GET_SERVICE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
+        CHECK_SERVICE_TRANSACTION,
+        ADD_SERVICE_TRANSACTION,
+        LIST_SERVICES_TRANSACTION,
+    };
+};
+
+sp<IServiceManager> defaultServiceManager();
+
+template<typename INTERFACE>
+status_t getService(const String16& name, android::hardware::hidl_version version,
+        sp<INTERFACE>* outService)
+{
+    const sp<IServiceManager> sm = defaultServiceManager();
+    if (sm != NULL) {
+        *outService = interface_cast<INTERFACE>(sm->getService(name, version));
+        if ((*outService) != NULL) return NO_ERROR;
+    }
+    return NAME_NOT_FOUND;
+}
+
+}; // namespace hardware
+}; // namespace android
+
+#endif // ANDROID_HARDWARE_ISERVICE_MANAGER_H
+
diff --git a/include/hidl/Static.h b/include/hidl/Static.h
new file mode 100644
index 0000000..a021e6e
--- /dev/null
+++ b/include/hidl/Static.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+// All static variables go here, to control initialization and
+// destruction order in the library.
+
+#include <utils/threads.h>
+#include <hidl/IServiceManager.h>
+
+namespace android {
+namespace hardware {
+
+// For IServiceManager.cpp
+extern Mutex gDefaultServiceManagerLock;
+extern sp<IServiceManager> gDefaultServiceManager;
+
+}   // namespace hardware
+}   // namespace android