Merge "Revert "Revert "Begin cleanup of HidlBinderSupport.h includes."""
diff --git a/libhidlcache/HidlMemoryCache.cpp b/libhidlcache/HidlMemoryCache.cpp
index f8fbbc1..a23c388 100644
--- a/libhidlcache/HidlMemoryCache.cpp
+++ b/libhidlcache/HidlMemoryCache.cpp
@@ -28,10 +28,10 @@
 using IMemoryToken = ::android::hidl::memory::token::V1_0::IMemoryToken;
 using IMemory = ::android::hidl::memory::V1_0::IMemory;
 
-class IMemoryDecorator : public virtual IMemory {
+class MemoryDecorator : public virtual IMemory {
    public:
-    IMemoryDecorator(sp<IMemory> heap) : mHeap(heap) {}
-    virtual ~IMemoryDecorator(){}
+    MemoryDecorator(const sp<IMemory>& heap) : mHeap(heap) {}
+    virtual ~MemoryDecorator() {}
     Return<void> update() override { return mHeap->update(); }
     Return<void> read() override { return mHeap->read(); }
     Return<void> updateRange(uint64_t start, uint64_t length) override {
@@ -49,29 +49,28 @@
     sp<IMemory> mHeap;
 };
 
-class IMemoryCacheable : public virtual IMemoryDecorator {
+class MemoryCacheable : public virtual MemoryDecorator {
    public:
-    IMemoryCacheable(sp<IMemory> heap, sp<IMemoryToken> key) : IMemoryDecorator(heap), mKey(key) {}
-    virtual ~IMemoryCacheable() { HidlMemoryCache::getInstance()->flush(mKey); }
+    MemoryCacheable(const sp<IMemory>& heap, sp<IMemoryToken> key)
+        : MemoryDecorator(heap), mKey(key) {}
+    virtual ~MemoryCacheable() { HidlMemoryCache::getInstance()->flush(mKey); }
 
    protected:
     sp<IMemoryToken> mKey;
 };
 
-class IMemoryBlock : public virtual IMemoryDecorator {
+class MemoryBlockImpl : public virtual IMemory {
    public:
-    IMemoryBlock(sp<IMemory> heap, uint64_t size, uint64_t offset)
-        : IMemoryDecorator(heap), mSize(size), mOffset(offset), mHeapSize(heap->getSize()) {}
+    MemoryBlockImpl(const sp<IMemory>& heap, uint64_t size, uint64_t offset)
+        : mHeap(heap), mSize(size), mOffset(offset), mHeapSize(heap->getSize()) {}
     bool validRange(uint64_t start, uint64_t length) {
-        return (start + length < mSize) && (start + length >= start) &&
-               (mOffset + mSize < mHeapSize);
+        return (start + length <= mSize) && (start + length >= start) &&
+               (mOffset + mSize <= mHeapSize);
     }
-    Return<void> readRange(uint64_t start, uint64_t length) {
+    Return<void> readRange(uint64_t start, uint64_t length) override {
         if (!validRange(start, length)) {
             ALOGE("IMemoryBlock::readRange: out of range");
-            Status status;
-            status.setException(Status::EX_ILLEGAL_ARGUMENT, "out of range");
-            return Return<void>(status);
+            return Void();
         }
         return mHeap->readRange(mOffset + start, length);
     }
@@ -82,6 +81,9 @@
         }
         return mHeap->updateRange(mOffset + start, length);
     }
+    Return<void> read() override { return this->readRange(0, mSize); }
+    Return<void> update() override { return this->updateRange(0, mSize); }
+    Return<void> commit() override { return mHeap->commit(); }
     Return<uint64_t> getSize() override { return mSize; }
     Return<void*> getPointer() override {
         void* p = mHeap->getPointer();
@@ -89,6 +91,7 @@
     }
 
    protected:
+    sp<IMemory> mHeap;
     uint64_t mSize;
     uint64_t mOffset;
     uint64_t mHeapSize;
@@ -102,7 +105,7 @@
 sp<IMemory> HidlMemoryCache::fillLocked(const sp<IMemoryToken>& key) {
     sp<IMemory> memory = nullptr;
     Return<void> ret = key->get(
-        [&](const hidl_memory& mem) { memory = new IMemoryCacheable(mapMemory(mem), key); });
+        [&](const hidl_memory& mem) { memory = new MemoryCacheable(mapMemory(mem), key); });
     if (!ret.isOk()) {
         ALOGE("HidlMemoryCache::fill: cannot IMemoryToken::get.");
         return nullptr;
@@ -117,7 +120,7 @@
     if (heap == nullptr) {
         return nullptr;
     }
-    return new IMemoryBlock(heap, memblk.size, memblk.offset);
+    return new MemoryBlockImpl(heap, memblk.size, memblk.offset);
 }
 
 }  // namespace hardware
diff --git a/libhidlmemory/mapping.cpp b/libhidlmemory/mapping.cpp
index 3cb6485..8f0bcf4 100644
--- a/libhidlmemory/mapping.cpp
+++ b/libhidlmemory/mapping.cpp
@@ -24,6 +24,7 @@
 #include <android-base/logging.h>
 #include <android/hidl/memory/1.0/IMapper.h>
 #include <hidl/HidlSupport.h>
+#include <log/log.h>
 
 using android::sp;
 using android::hidl::memory::V1_0::IMemory;
@@ -63,6 +64,15 @@
         return nullptr;
     }
 
+    // hidl_memory's size is stored in uint64_t, but mapMemory's mmap will map
+    // size in size_t. If size is over SIZE_MAX, mapMemory could succeed
+    // but the mapped memory's actual size will be smaller than the reported size.
+    if (memory.size() > SIZE_MAX) {
+        LOG(ERROR) << "Cannot map " << memory.size() << " bytes of memory because it is too large.";
+        android_errorWriteLog(0x534e4554, "79376389");
+        return nullptr;
+    }
+
     Return<sp<IMemory>> ret = mapper->mapMemory(memory);
 
     if (!ret.isOk()) {
diff --git a/transport/Android.bp b/transport/Android.bp
index ea9b38e..f783022 100644
--- a/transport/Android.bp
+++ b/transport/Android.bp
@@ -87,20 +87,3 @@
         },
     },
 }
-
-// deprecated/legacy (already removed in mainline Android)
-// use android-hidl-base-V1-0-java instead!
-java_library_static {
-    name: "android.hidl.base-V1.0-java-static",
-    no_framework_libs: true,
-    defaults: ["hidl-java-module-defaults"],
-    srcs: [":android.hidl.base-V1.0-java_gen_java"],
-    libs: [
-        "hwbinder",
-    ],
-    product_variables: {
-        pdk: {
-            enabled: false,
-        },
-    },
-}
\ No newline at end of file
diff --git a/transport/HidlTransportUtils.cpp b/transport/HidlTransportUtils.cpp
index eda9b8a..4e952eb 100644
--- a/transport/HidlTransportUtils.cpp
+++ b/transport/HidlTransportUtils.cpp
@@ -16,16 +16,25 @@
 
 #include <hidl/HidlTransportUtils.h>
 
+#include <android/hidl/base/1.0/IBase.h>
+
 namespace android {
 namespace hardware {
 namespace details {
 
-Return<bool> canCastInterface(::android::hidl::base::V1_0::IBase* interface,
-        const char* castTo, bool emitError) {
+using ::android::hidl::base::V1_0::IBase;
+
+Return<bool> canCastInterface(IBase* interface, const char* castTo, bool emitError) {
     if (interface == nullptr) {
         return false;
     }
 
+    // b/68217907
+    // Every HIDL interface is a base interface.
+    if (std::string(IBase::descriptor) == castTo) {
+        return true;
+    }
+
     bool canCast = false;
     auto chainRet = interface->interfaceChain([&](const hidl_vec<hidl_string> &types) {
         for (size_t i = 0; i < types.size(); i++) {
@@ -46,7 +55,7 @@
     return canCast;
 }
 
-std::string getDescriptor(::android::hidl::base::V1_0::IBase* interface) {
+std::string getDescriptor(IBase* interface) {
     std::string myDescriptor{};
     auto ret = interface->interfaceDescriptor([&](const hidl_string &types) {
         myDescriptor = types.c_str();
diff --git a/transport/ServiceManagement.cpp b/transport/ServiceManagement.cpp
index fb474c1..57434d7 100644
--- a/transport/ServiceManagement.cpp
+++ b/transport/ServiceManagement.cpp
@@ -103,29 +103,55 @@
     return cmdline;
 }
 
-void tryShortenProcessName(const std::string &packageName) {
+std::string packageWithoutVersion(const std::string& packageAndVersion) {
+    size_t at = packageAndVersion.find('@');
+    if (at == std::string::npos) return packageAndVersion;
+    return packageAndVersion.substr(0, at);
+}
+
+void tryShortenProcessName(const std::string& packageAndVersion) {
+    const static std::string kTasks = "/proc/self/task/";
+
+    // make sure that this binary name is in the same package
     std::string processName = binaryName();
 
-    if (!startsWith(processName, packageName)) {
+    // e.x. android.hardware.foo is this package
+    if (!startsWith(packageWithoutVersion(processName), packageWithoutVersion(packageAndVersion))) {
         return;
     }
 
-    // e.x. android.hardware.module.foo@1.0 -> foo@1.0
-    size_t lastDot = packageName.rfind('.');
-    size_t secondDot = packageName.rfind('.', lastDot - 1);
+    // e.x. android.hardware.module.foo@1.2 -> foo@1.2
+    size_t lastDot = packageAndVersion.rfind('.');
+    if (lastDot == std::string::npos) return;
+    size_t secondDot = packageAndVersion.rfind('.', lastDot - 1);
+    if (secondDot == std::string::npos) return;
 
-    if (secondDot == std::string::npos) {
-        return;
+    std::string newName = processName.substr(secondDot + 1, std::string::npos);
+    ALOGI("Removing namespace from process name %s to %s.", processName.c_str(), newName.c_str());
+
+    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(kTasks.c_str()), closedir);
+    if (dir == nullptr) return;
+
+    dirent* dp;
+    while ((dp = readdir(dir.get())) != nullptr) {
+        if (dp->d_type != DT_DIR) continue;
+        if (dp->d_name[0] == '.') continue;
+
+        std::fstream fs(kTasks + dp->d_name + "/comm");
+        if (!fs.is_open()) {
+            ALOGI("Could not rename process, failed read comm for %s.", dp->d_name);
+            continue;
+        }
+
+        std::string oldComm;
+        fs >> oldComm;
+
+        // don't rename if it already has an explicit name
+        if (startsWith(packageAndVersion, oldComm)) {
+            fs.seekg(0, fs.beg);
+            fs << newName;
+        }
     }
-
-    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 {
diff --git a/transport/allocator/1.0/default/AshmemAllocator.cpp b/transport/allocator/1.0/default/AshmemAllocator.cpp
index 0bd4f81..5cc2eea 100644
--- a/transport/allocator/1.0/default/AshmemAllocator.cpp
+++ b/transport/allocator/1.0/default/AshmemAllocator.cpp
@@ -36,8 +36,8 @@
 
     native_handle_t* handle = native_handle_create(1, 0);
     handle->data[0] = fd;
-    LOG(WARNING) << "ashmem_create_region(" << size << ") returning hidl_memory(" << handle
-            << ", " << size << ")";
+    LOG(VERBOSE) << "ashmem_create_region(" << size << ") returning hidl_memory(" << handle << ", "
+                 << size << ")";
     return hidl_memory("ashmem", handle, size);
 }
 
diff --git a/transport/current.txt b/transport/current.txt
index b338d12..3794dfe 100644
--- a/transport/current.txt
+++ b/transport/current.txt
@@ -16,7 +16,11 @@
 
 0b94dc876f749ed24a98f61c41d46ad75a27511163f1968a084213a33c684ef6 android.hidl.manager@1.1::IServiceManager
 
-# Documentation fixups for b/78135149
+# HALs released in Android P
+445da29052612c57db3a8504f6395814277dc3826ee0f166cc732031b35af496 android.hidl.memory.block@1.0::types
+2e19301ceb87fb0696cd8268fab9c41f95d23c7392d35bc575daaa6eb32807eb android.hidl.memory.token@1.0::IMemoryToken
+
+# ABI preserving changes to HALs during Android Q
 fcde1d0788066a62d5766f4dc19d4c1ec76967d5ddb636f59ccc66603460bcf8 android.hidl.manager@1.0::IServiceNotification
 
 # Clarification for b/67503915
diff --git a/transport/memory/1.0/default/Android.bp b/transport/memory/1.0/default/Android.bp
index 8c48f4f..d242ddf 100644
--- a/transport/memory/1.0/default/Android.bp
+++ b/transport/memory/1.0/default/Android.bp
@@ -31,6 +31,7 @@
         "libcutils",
         "libhwbinder",
         "libbase",
+        "liblog",
         "libutils",
         "libhidlbase",
         "libhidltransport",
diff --git a/transport/memory/1.0/default/AshmemMapper.cpp b/transport/memory/1.0/default/AshmemMapper.cpp
index bef4767..cefaaa4 100644
--- a/transport/memory/1.0/default/AshmemMapper.cpp
+++ b/transport/memory/1.0/default/AshmemMapper.cpp
@@ -16,6 +16,9 @@
 
 #include "AshmemMapper.h"
 
+#include <inttypes.h>
+
+#include <log/log.h>
 #include <sys/mman.h>
 
 #include "AshmemMemory.h"
@@ -32,6 +35,16 @@
         return nullptr;
     }
 
+    // If ashmem service runs in 32-bit (size_t is uint32_t) and a 64-bit
+    // client process requests a memory > 2^32 bytes, the size would be
+    // converted to a 32-bit number in mmap. mmap could succeed but the
+    // mapped memory's actual size would be smaller than the reported size.
+    if (mem.size() > SIZE_MAX) {
+        ALOGE("Cannot map %" PRIu64 " bytes of memory because it is too large.", mem.size());
+        android_errorWriteLog(0x534e4554, "79376389");
+        return nullptr;
+    }
+
     int fd = mem.handle()->data[0];
     void* data = mmap(0, mem.size(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
     if (data == MAP_FAILED) {
diff --git a/vintfdata/Android.mk b/vintfdata/Android.mk
index 3db7065..232ef6f 100644
--- a/vintfdata/Android.mk
+++ b/vintfdata/Android.mk
@@ -17,6 +17,10 @@
 LOCAL_PATH := $(call my-dir)
 
 FRAMEWORK_MANIFEST_INPUT_FILES := $(LOCAL_PATH)/manifest.xml
+# TODO(b/110487738): replace with vintf_fragment
+ifdef USE_VR_FLINGER
+  FRAMEWORK_MANIFEST_INPUT_FILES += $(LOCAL_PATH)/manifest_vr_hwc.xml
+endif
 ifdef DEVICE_FRAMEWORK_MANIFEST_FILE
   FRAMEWORK_MANIFEST_INPUT_FILES += $(DEVICE_FRAMEWORK_MANIFEST_FILE)
 endif
diff --git a/vintfdata/manifest.xml b/vintfdata/manifest.xml
index 582b5eb..27919d3 100644
--- a/vintfdata/manifest.xml
+++ b/vintfdata/manifest.xml
@@ -71,15 +71,6 @@
             <instance>default</instance>
         </interface>
     </hal>
-    <hal>
-      <name>android.hardware.graphics.composer</name>
-      <transport>hwbinder</transport>
-      <version>2.1</version>
-      <interface>
-          <name>IComposer</name>
-          <instance>vr</instance>
-      </interface>
-    </hal>
     <hal format="native">
         <name>netutils-wrapper</name>
         <!--
diff --git a/vintfdata/manifest_vr_hwc.xml b/vintfdata/manifest_vr_hwc.xml
new file mode 100644
index 0000000..1068cac
--- /dev/null
+++ b/vintfdata/manifest_vr_hwc.xml
@@ -0,0 +1,11 @@
+<manifest version="1.0" type="framework">
+    <hal>
+      <name>android.hardware.graphics.composer</name>
+      <transport>hwbinder</transport>
+      <version>2.1</version>
+      <interface>
+          <name>IComposer</name>
+          <instance>vr</instance>
+      </interface>
+    </hal>
+</manifest>