Merge "Remove unused include in MQDescriptor.h of utils/Log.h."
diff --git a/base/Android.bp b/base/Android.bp
index 321f499..dd759d2 100644
--- a/base/Android.bp
+++ b/base/Android.bp
@@ -18,15 +18,12 @@
     shared_libs: [
         "libbase",
         "libcutils",
-        "libhidl-gen-utils",
         "liblog",
         "libutils",
-        "libvintf",
     ],
     export_shared_lib_headers: [
         "libbase",
         "libutils",
-        "libvintf",
     ],
     local_include_dirs: ["include"],
     export_include_dirs: ["include"],
diff --git a/base/HidlInternal.cpp b/base/HidlInternal.cpp
index 36ffae8..3bb27f8 100644
--- a/base/HidlInternal.cpp
+++ b/base/HidlInternal.cpp
@@ -24,7 +24,6 @@
 #ifdef LIBHIDL_TARGET_DEBUGGABLE
 #include <dirent.h>
 #include <dlfcn.h>
-#include <hidl-util/FQName.h>
 #include <regex>
 #endif
 
@@ -111,14 +110,25 @@
                     const char *,
                     const char *,
                     std::vector<void *> *);
-            FQName package_name = FQName(mInstrumentationLibPackage);
+            std::string package = mInstrumentationLibPackage;
+            for (size_t i = 0; i < package.size(); i++) {
+                if (package[i] == '.') {
+                    package[i] = '_';
+                    continue;
+                }
+
+                if (package[i] == '@') {
+                    package[i] = '_';
+                    package.insert(i + 1, "V");
+                    continue;
+                }
+            }
             auto cb = (cb_fun)dlsym(handle, ("HIDL_INSTRUMENTATION_FUNCTION_"
-                        + package_name.tokenName() + "_"
-                        + mInterfaceName).c_str());
+                        + package + "_" + mInterfaceName).c_str());
             if ((error = dlerror()) != NULL) {
                 LOG(WARNING)
                     << "couldn't find symbol: HIDL_INSTRUMENTATION_FUNCTION_"
-                    << mInterfaceName << ", error: " << error;
+                    << package << "_" << mInterfaceName << ", error: " << error;
                 continue;
             }
             instrumentationCallbacks->push_back(cb);
diff --git a/base/HidlSupport.cpp b/base/HidlSupport.cpp
index e97797d..5789d04 100644
--- a/base/HidlSupport.cpp
+++ b/base/HidlSupport.cpp
@@ -21,58 +21,10 @@
 
 #include <android-base/logging.h>
 #include <android-base/parseint.h>
-#include <hidl-util/FQName.h>
-#include <vintf/VintfObject.h>
-#include <vintf/parse_string.h>
 
 namespace android {
 namespace hardware {
 
-vintf::Transport getTransportFromManifest(
-        const FQName &fqName, const std::string &instanceName,
-        const vintf::HalManifest *vm) {
-    if (vm == nullptr) {
-        return vintf::Transport::EMPTY;
-    }
-    return vm->getTransport(fqName.package(),
-            vintf::Version{fqName.getPackageMajorVersion(), fqName.getPackageMinorVersion()},
-            fqName.name(), instanceName);
-}
-
-vintf::Transport getTransport(const std::string &interfaceName, const std::string &instanceName) {
-    FQName fqName(interfaceName);
-    if (!fqName.isValid()) {
-        LOG(ERROR) << "getTransport: " << interfaceName << " is not a valid fully-qualified name.";
-        return vintf::Transport::EMPTY;
-    }
-    if (!fqName.hasVersion()) {
-        LOG(ERROR) << "getTransport: " << fqName.string()
-                   << " does not specify a version. Using default transport.";
-        return vintf::Transport::EMPTY;
-    }
-    if (fqName.name().empty()) {
-        LOG(ERROR) << "getTransport: " << fqName.string()
-                   << " does not specify an interface name. Using default transport.";
-        return vintf::Transport::EMPTY;
-    }
-
-    vintf::Transport tr = getTransportFromManifest(fqName, instanceName,
-            vintf::VintfObject::GetFrameworkHalManifest());
-    if (tr != vintf::Transport::EMPTY) {
-        return tr;
-    }
-    tr = getTransportFromManifest(fqName, instanceName,
-            vintf::VintfObject::GetDeviceHalManifest());
-    if (tr != vintf::Transport::EMPTY) {
-        return tr;
-    }
-
-    LOG(WARNING) << "getTransportFromManifest: Cannot find entry "
-                 << fqName.string()
-                 << " in either framework or device manifest, using default transport.";
-    return vintf::Transport::EMPTY;
-}
-
 namespace details {
 bool debuggable() {
 #ifdef LIBHIDL_TARGET_DEBUGGABLE
diff --git a/base/include/hidl/HidlSupport.h b/base/include/hidl/HidlSupport.h
index a8eae8c..da9a1af 100644
--- a/base/include/hidl/HidlSupport.h
+++ b/base/include/hidl/HidlSupport.h
@@ -31,7 +31,6 @@
 #include <utils/Errors.h>
 #include <utils/RefBase.h>
 #include <utils/StrongPointer.h>
-#include <vintf/Transport.h>
 #include <vector>
 
 namespace android {
@@ -56,13 +55,6 @@
 
 namespace hardware {
 
-// Get transport method from vendor interface manifest.
-// interfaceName has the format "android.hardware.foo@1.0::IFoo"
-// instanceName is "default", "ashmem", etc.
-// If it starts with "android.hidl.", a static map is looked up instead.
-vintf::Transport getTransport(const std::string &interfaceName,
-                              const std::string &instanceName);
-
 namespace details {
 // Return true on userdebug / eng builds and false on user builds.
 bool debuggable();
diff --git a/base/include/hidl/Status.h b/base/include/hidl/Status.h
index a4a83f4..a04cf77 100644
--- a/base/include/hidl/Status.h
+++ b/base/include/hidl/Status.h
@@ -21,6 +21,7 @@
 #include <sstream>
 
 #include <android-base/macros.h>
+#include <hidl/HidlInternal.h>
 #include <utils/Errors.h>
 #include <utils/StrongPointer.h>
 
@@ -129,11 +130,16 @@
 // For gtest output logging
 std::ostream& operator<< (std::ostream& stream, const Status& s);
 
+template<typename T> class Return;
+
 namespace details {
     class return_status {
     private:
         Status mStatus {};
         mutable bool mCheckedStatus = false;
+
+        template <typename T, typename U>
+        friend Return<U> StatusOf(const Return<T> &other);
     protected:
         void assertOk() const;
     public:
@@ -155,6 +161,12 @@
             return mStatus.isOk();
         }
 
+        // Check if underlying error is DEAD_OBJECT.
+        // Does not set mCheckedStatus.
+        bool isDeadObject() const {
+            return mStatus.transactionError() == DEAD_OBJECT;
+        }
+
         // For debugging purposes only
         std::string description() const {
             // Doesn't consider checked.
@@ -229,6 +241,18 @@
     return Return<void>();
 }
 
+namespace details {
+// Create a Return<U> from the Status of Return<T>. The provided
+// Return<T> must have an error status and have it checked.
+template <typename T, typename U>
+Return<U> StatusOf(const Return<T> &other) {
+    if (other.mStatus.isOk() || !other.mCheckedStatus) {
+        details::logAlwaysFatal("cannot call statusOf on an OK Status or an unchecked status");
+    }
+    return Return<U>{other.mStatus};
+}
+}  // namespace details
+
 }  // namespace hardware
 }  // namespace android
 
diff --git a/manifest.xml b/manifest.xml
index 3fe38e7..c258bce 100644
--- a/manifest.xml
+++ b/manifest.xml
@@ -1,4 +1,4 @@
-<manifest version="1.0">
+<manifest version="1.0" type="framework">
     <hal>
         <name>android.hidl.manager</name>
         <transport>hwbinder</transport>
diff --git a/transport/Android.bp b/transport/Android.bp
index 835c6e1..6f0b6a9 100644
--- a/transport/Android.bp
+++ b/transport/Android.bp
@@ -33,7 +33,6 @@
         "libhidlbase",
         "libhwbinder",
         "libcutils",
-        "libhidl-gen-utils"
     ],
     export_shared_lib_headers: [
         "libbase",
diff --git a/transport/ServiceManagement.cpp b/transport/ServiceManagement.cpp
index 5ba3ec3..c766b7a 100644
--- a/transport/ServiceManagement.cpp
+++ b/transport/ServiceManagement.cpp
@@ -19,6 +19,8 @@
 #include <condition_variable>
 #include <dlfcn.h>
 #include <dirent.h>
+#include <fstream>
+#include <pthread.h>
 #include <unistd.h>
 
 #include <mutex>
@@ -30,8 +32,6 @@
 
 #include <android-base/logging.h>
 #include <android-base/properties.h>
-#include <hidl-util/FQName.h>
-#include <hidl-util/StringHelper.h>
 #include <hwbinder/IPCThreadState.h>
 #include <hwbinder/Parcel.h>
 
@@ -68,13 +68,74 @@
     }
 }
 
-sp<IServiceManager> defaultServiceManager() {
+bool endsWith(const std::string &in, const std::string &suffix) {
+    return in.size() >= suffix.size() &&
+           in.substr(in.size() - suffix.size()) == suffix;
+}
 
+bool startsWith(const std::string &in, const std::string &prefix) {
+    return in.size() >= prefix.size() &&
+           in.substr(0, prefix.size()) == prefix;
+}
+
+std::string binaryName() {
+    std::ifstream ifs("/proc/self/cmdline");
+    std::string cmdline;
+    if (!ifs.is_open()) {
+        return "";
+    }
+    ifs >> cmdline;
+
+    size_t idx = cmdline.rfind("/");
+    if (idx != std::string::npos) {
+        cmdline = cmdline.substr(idx + 1);
+    }
+
+    return cmdline;
+}
+
+void tryShortenProcessName(const std::string &packageName) {
+    std::string processName = binaryName();
+
+    if (!startsWith(processName, packageName)) {
+        return;
+    }
+
+    // e.x. android.hardware.module.foo@1.0 -> foo@1.0
+    size_t lastDot = packageName.rfind('.');
+    size_t secondDot = packageName.rfind('.', lastDot - 1);
+
+    if (secondDot == std::string::npos) {
+        return;
+    }
+
+    std::string newName = processName.substr(secondDot + 1,
+            16 /* TASK_COMM_LEN */ - 1);
+    ALOGI("Removing namespace from process name %s to %s.",
+            processName.c_str(), newName.c_str());
+
+    int rc = pthread_setname_np(pthread_self(), newName.c_str());
+    ALOGI_IF(rc != 0, "Removing namespace from process name %s failed.",
+            processName.c_str());
+}
+
+namespace details {
+
+void onRegistration(const std::string &packageName,
+                    const std::string& /* interfaceName */,
+                    const std::string& /* instanceName */) {
+    tryShortenProcessName(packageName);
+}
+
+}  // details
+
+sp<IServiceManager> defaultServiceManager() {
     {
         AutoMutex _l(details::gDefaultServiceManagerLock);
         if (details::gDefaultServiceManager != NULL) {
             return details::gDefaultServiceManager;
         }
+
         if (access("/dev/hwbinder", F_OK|R_OK|W_OK) != 0) {
             // HwBinder not available on this device or not accessible to
             // this process.
@@ -109,8 +170,8 @@
     while ((dp = readdir(dir.get())) != nullptr) {
         std::string name = dp->d_name;
 
-        if (StringHelper::StartsWith(name, prefix) &&
-                StringHelper::EndsWith(name, suffix)) {
+        if (startsWith(name, prefix) &&
+                endsWith(name, suffix)) {
             results.push_back(name);
         }
     }
@@ -148,18 +209,23 @@
 
 struct PassthroughServiceManager : IServiceManager {
     Return<sp<IBase>> get(const hidl_string& fqName,
-                     const hidl_string& name) override {
-        const FQName iface(fqName);
+                          const hidl_string& name) override {
+        std::string stdFqName(fqName.c_str());
 
-        if (!iface.isValid() ||
-            !iface.isFullyQualified() ||
-            iface.isIdentifier()) {
+        //fqName looks like android.hardware.foo@1.0::IFoo
+        size_t idx = stdFqName.find("::");
+
+        if (idx == std::string::npos ||
+                idx + strlen("::") + 1 >= stdFqName.size()) {
             LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
             return nullptr;
         }
 
-        const std::string prefix = iface.getPackageAndVersion().string() + "-impl";
-        const std::string sym = "HIDL_FETCH_" + iface.name();
+        std::string packageAndVersion = stdFqName.substr(0, idx);
+        std::string ifaceName = stdFqName.substr(idx + strlen("::"));
+
+        const std::string prefix = packageAndVersion + "-impl";
+        const std::string sym = "HIDL_FETCH_" + ifaceName;
 
         const int dlMode = RTLD_LAZY;
         void *handle = nullptr;
@@ -218,6 +284,12 @@
         return false;
     }
 
+    Return<Transport> getTransport(const hidl_string& /* fqName */,
+                                   const hidl_string& /* name */) {
+        LOG(FATAL) << "Cannot getTransport with passthrough service manager.";
+        return Transport::EMPTY;
+    }
+
     Return<void> list(list_cb /* _hidl_cb */) override {
         LOG(FATAL) << "Cannot list services with passthrough service manager.";
         return Void();
diff --git a/transport/include/hidl/HidlTransportSupport.h b/transport/include/hidl/HidlTransportSupport.h
index 8a2a70a..3cac1e9 100644
--- a/transport/include/hidl/HidlTransportSupport.h
+++ b/transport/include/hidl/HidlTransportSupport.h
@@ -50,16 +50,28 @@
 namespace details {
 
 // cast the interface IParent to IChild.
-// Return nullptr if parent is null or any failure.
+// Return nonnull if cast successful.
+// Return nullptr if:
+// 1. parent is null
+// 2. cast failed because IChild is not a child type of IParent.
+// 3. !emitError, calling into parent fails.
+// Return an error Return object if:
+// 1. emitError, calling into parent fails.
 template<typename IChild, typename IParent, typename BpChild, typename BpParent>
-sp<IChild> castInterface(sp<IParent> parent, const char *childIndicator) {
+Return<sp<IChild>> castInterface(sp<IParent> parent, const char *childIndicator, bool emitError) {
     if (parent.get() == nullptr) {
         // casts always succeed with nullptrs.
         return nullptr;
     }
-    bool canCast = details::canCastInterface(parent.get(), childIndicator);
+    Return<bool> canCastRet = details::canCastInterface(parent.get(), childIndicator, emitError);
+    if (!canCastRet.isOk()) {
+        // call fails, propagate the error if emitError
+        return emitError
+                ? details::StatusOf<bool, sp<IChild>>(canCastRet)
+                : Return<sp<IChild>>(sp<IChild>(nullptr));
+    }
 
-    if (!canCast) {
+    if (!canCastRet) {
         return sp<IChild>(nullptr); // cast failed.
     }
     // TODO b/32001926 Needs to be fixed for socket mode.
diff --git a/transport/include/hidl/HidlTransportUtils.h b/transport/include/hidl/HidlTransportUtils.h
index 0fe70c4..fbd6516 100644
--- a/transport/include/hidl/HidlTransportUtils.h
+++ b/transport/include/hidl/HidlTransportUtils.h
@@ -25,14 +25,17 @@
 
 /*
  * Verifies the interface chain of 'interface' contains 'castTo'
+ * @param emitError if emitError is false, return Return<bool>{false} on error; if emitError
+ * is true, the Return<bool> object contains the actual error.
  */
-inline bool canCastInterface(::android::hidl::base::V1_0::IBase* interface, const char* castTo) {
+inline Return<bool> canCastInterface(::android::hidl::base::V1_0::IBase* interface,
+        const char* castTo, bool emitError = false) {
     if (interface == nullptr) {
         return false;
     }
 
     bool canCast = false;
-    auto ret = interface->interfaceChain([&](const hidl_vec<hidl_string> &types) {
+    auto chainRet = interface->interfaceChain([&](const hidl_vec<hidl_string> &types) {
         for (size_t i = 0; i < types.size(); i++) {
             if (types[i] == castTo) {
                 canCast = true;
@@ -40,7 +43,15 @@
             }
         }
     });
-    return ret.isOk() && canCast;
+
+    if (!chainRet.isOk()) {
+        // call fails, propagate the error if emitError
+        return emitError
+                ? details::StatusOf<void, bool>(chainRet)
+                : Return<bool>(false);
+    }
+
+    return canCast;
 }
 
 inline std::string getDescriptor(::android::hidl::base::V1_0::IBase* interface) {
diff --git a/transport/include/hidl/ServiceManagement.h b/transport/include/hidl/ServiceManagement.h
index 2035fb7..2b2266b 100644
--- a/transport/include/hidl/ServiceManagement.h
+++ b/transport/include/hidl/ServiceManagement.h
@@ -39,6 +39,12 @@
 sp<::android::hidl::manager::V1_0::IServiceManager> getPassthroughServiceManager();
 
 namespace details {
+// e.x.: android.hardware.foo@1.0, IFoo, default
+void onRegistration(const std::string &packageName,
+                    const std::string &interfaceName,
+                    const std::string &instanceName);
+
+// e.x.: android.hardware.foo@1.0::IFoo, default
 void waitForHwService(const std::string &interface, const std::string &instanceName);
 };
 
diff --git a/transport/manager/1.0/IServiceManager.hal b/transport/manager/1.0/IServiceManager.hal
index 9e1c2fc..1a37c54 100644
--- a/transport/manager/1.0/IServiceManager.hal
+++ b/transport/manager/1.0/IServiceManager.hal
@@ -73,6 +73,22 @@
      */
     add(string name, interface service) generates (bool success);
 
+    enum Transport : uint8_t {
+        EMPTY,
+        HWBINDER,
+        PASSTHROUGH,
+    };
+
+    /**
+     * Get the transport of a service.
+     *
+     * @param fqName     Fully-qualified interface name.
+     * @param name       Instance name. Same as in IServiceManager::add
+     *
+     * @return transport Transport of service if known.
+     */
+    getTransport(string fqName, string name) generates (Transport transport);
+
     /**
      * List all registered services. Must be sorted.
      *
diff --git a/transport/token/1.0/ITokenManager.hal b/transport/token/1.0/ITokenManager.hal
index b1bb735..23a44bd 100644
--- a/transport/token/1.0/ITokenManager.hal
+++ b/transport/token/1.0/ITokenManager.hal
@@ -26,10 +26,12 @@
      * Register an interface. The server must keep a strong reference
      * to the interface until the token is destroyed by calling unregister.
      *
+     * Must return empty token on failure.
+     *
      * @param store Interface which can later be fetched with the returned token.
      * @return token Opaque value which may be used as inputs to other functions.
      */
-    createToken(interface store) generates (uint64_t token);
+    createToken(interface store) generates (vec<uint8_t>token);
 
     /**
      * Destory a token and the strong reference to the associated interface.
@@ -37,7 +39,7 @@
      * @param token Token received from createToken
      * @return success Whether or not the token was successfully unregistered.
      */
-    unregister(uint64_t token) generates (bool success);
+    unregister(vec<uint8_t> token) generates (bool success);
 
     /**
      * Fetch an interface from a provided token.
@@ -46,5 +48,5 @@
      * @return store Interface registered with createToken and the corresponding
      *               token or nullptr.
      */
-    get(uint64_t token) generates (interface store);
+    get(vec<uint8_t> token) generates (interface store);
 };
diff --git a/transport/token/1.0/utils/HybridInterface.cpp b/transport/token/1.0/utils/HybridInterface.cpp
index f28446e..106ad4e 100644
--- a/transport/token/1.0/utils/HybridInterface.cpp
+++ b/transport/token/1.0/utils/HybridInterface.cpp
@@ -89,19 +89,17 @@
 }
 
 bool createHalToken(const sp<HInterface>& interface, HalToken* token) {
-    hardware::Return<HalToken> transaction(false);
+    hardware::Return<void> transaction;
     {
         std::lock_guard<std::mutex> lock(gTokenManagerLock);
         if (isBadTokenManager()) {
             return false;
         }
-        transaction = gTokenManager->createToken(interface);
-        if (isBadTransaction(transaction)) {
-            return false;
-        }
+        transaction = gTokenManager->createToken(interface, [&](const HalToken &newToken) {
+            *token = newToken;
+        });
     }
-    *token = static_cast<HalToken>(transaction);
-    return true;
+    return !isBadTransaction(transaction);
 }
 
 bool deleteHalToken(const HalToken& token) {
diff --git a/transport/token/1.0/utils/include/hidl/HybridInterface.h b/transport/token/1.0/utils/include/hidl/HybridInterface.h
index 42d3734..8c3e742 100644
--- a/transport/token/1.0/utils/include/hidl/HybridInterface.h
+++ b/transport/token/1.0/utils/include/hidl/HybridInterface.h
@@ -96,7 +96,7 @@
 
 namespace android {
 
-typedef uint64_t HalToken;
+typedef ::android::hardware::hidl_vec<uint8_t> HalToken;
 typedef ::android::hidl::base::V1_0::IBase HInterface;
 
 constexpr uint32_t DEFAULT_GET_HAL_TOKEN_TRANSACTION_CODE =
@@ -247,7 +247,7 @@
             ALOGE("H2BConverter: Failed to create HAL token.");
         }
         reply->writeBool(result);
-        reply->writeUint64(token);
+        reply->writeByteArray(token.size(), token.data());
         return NO_ERROR;
     }
     return BNINTERFACE::onTransact(code, data, reply, flags);
@@ -313,7 +313,11 @@
     data.writeInterfaceToken(BaseInterface::getInterfaceDescriptor());
     if (mImpl->transact(GET_HAL_TOKEN, data, &reply) == NO_ERROR) {
         bool tokenCreated = reply.readBool();
-        HalToken token = reply.readUint64();
+
+        std::vector<uint8_t> tokenVector;
+        reply.readByteVector(&tokenVector);
+        HalToken token = HalToken(tokenVector);
+
         if (tokenCreated) {
             sp<HInterface> hBase = retrieveHalInterface(token);
             if (hBase != nullptr) {