From 0b7c443256981eec3f755a5175c0d6dec0148abb Mon Sep 17 00:00:00 2001 From: Sean Silva Date: Mon, 23 Nov 2020 16:30:49 -0800 Subject: [PATCH] [RefBackend] Properly initialize refbackrt::Tensor refcount. Although `refCount` is initialized as `std::atomic refCount{0};` in the definition of Tensor, our tail-allocating malloc would ignore it, resulting in bogus values that led to leaks. Caught with LeakSanitizer, but I added an assertion that the refcount is non-negative to begin with, which should catch this bug in the future fairly consistently (assuming the garbage refcount is negative half the time). --- include/npcomp/RefBackend/Runtime/UserAPI.h | 1 + lib/RefBackend/Runtime/Runtime.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/include/npcomp/RefBackend/Runtime/UserAPI.h b/include/npcomp/RefBackend/Runtime/UserAPI.h index f5b9c24a9..05ae6cb64 100644 --- a/include/npcomp/RefBackend/Runtime/UserAPI.h +++ b/include/npcomp/RefBackend/Runtime/UserAPI.h @@ -34,6 +34,7 @@ public: // Creates a Ref and increments the refcount by 1. // rawPtr must be allocated with std::malloc. Ref(T *rawPtr) { + assert(rawPtr->refCount >= 0 && "expected non-negative refcount to start!"); ptr = rawPtr; ptr->refCount += 1; } diff --git a/lib/RefBackend/Runtime/Runtime.cpp b/lib/RefBackend/Runtime/Runtime.cpp index ee5b607e3..c8bc03990 100644 --- a/lib/RefBackend/Runtime/Runtime.cpp +++ b/lib/RefBackend/Runtime/Runtime.cpp @@ -46,6 +46,7 @@ Tensor *Tensor::createRaw(ArrayRef extents, ElementType type, auto *tensor = static_cast( std::malloc(sizeof(Tensor) + extents.size() * sizeof(std::int32_t))); + tensor->refCount.store(0); tensor->elementType = type; tensor->rank = extents.size(); auto byteSize = getElementTypeByteSize(type) * totalElements(extents);