diff --git a/python/cppjit/__init__.py b/python/cppjit/__init__.py index 8df1b926..dfb5a189 100644 --- a/python/cppjit/__init__.py +++ b/python/cppjit/__init__.py @@ -48,6 +48,7 @@ "add_library_path", # add a path to search for libraries "add_autoload_map", # explicitly include an autoload map "set_debug", # enable/disable debug output + "use_memory_analyzer", # enable/disable the memory ownership analyzer ] import ctypes @@ -397,6 +398,11 @@ def set_debug(enable=True): gbl.Cpp.EnableDebugOutput(enable) +def use_memory_analyzer(enable=True): + """Enable/disable the memory ownership analyzer.""" + _backend.UseMemoryAnalyzer(enable) + + def _get_name(tt): if isinstance(tt, str): return tt diff --git a/src/cpyrt/CPPMethod.cxx b/src/cpyrt/CPPMethod.cxx index 38aaebd2..058891ea 100644 --- a/src/cpyrt/CPPMethod.cxx +++ b/src/cpyrt/CPPMethod.cxx @@ -2,7 +2,9 @@ #include "cpyrt.h" using namespace cppjit; +#include "CPPClassMethod.h" #include "CPPExcInstance.h" +#include "CPPFunction.h" #include "CPPInstance.h" #include "CPPMethod.h" #include "Converters.h" @@ -32,6 +34,7 @@ extern PyObject* gBusException; extern PyObject* gSegvException; extern PyObject* gIllException; extern PyObject* gAbrtException; +extern bool gUseMemoryAnalyzer; } // namespace cppjit::cpyrt //- public helper ------------------------------------------------------------ @@ -719,20 +722,50 @@ interop::AllocType cpyrt::CPPMethod::GetAllocBehaviour() { return interop::AllocType::None; } interop::AllocType attrResult = interop::IsAllocator(method); + // an attribute always wins, so ask the analyzer when there is no + // relevant attribute + if (attrResult == interop::AllocType::Unknown && gUseMemoryAnalyzer) + attrResult = interop::GetAllocType(method); fAllocType = attrResult; return attrResult; } //---------------------------------------------------------------------------- -interop::DeallocType cpyrt::CPPMethod::GetDeallocBehaviour(size_t index) { - if (!fDeallocType) { - fDeallocType.emplace(); - if (interop::TCppMethod_t method = GetMethod()) - interop::IsDeallocator(method, *fDeallocType); +void cpyrt::CPPMethod::FillDeallocBehaviour() { + fDeallocType.emplace(); + interop::TCppMethod_t method = GetMethod(); + if (!method) + return; + + interop::IsDeallocator(method, *fDeallocType); + if (!gUseMemoryAnalyzer) + return; + + std::vector analyzeRes; + if (!interop::GetDeallocType(method, analyzeRes)) + return; + + // IsDeallocator puts the implicit this in slot 0, GetDeallocType does not, + // so each analyzer answer moves up by one slot for a method + size_t shift = 0; + if (!(dynamic_cast(this) || + dynamic_cast(this))) + shift = 1; + assert(analyzeRes.size() + shift == fDeallocType->size() && + "the analyzer answer must line up with the attribute slots"); + for (size_t i = 0; i < analyzeRes.size(); i++) { + // an attribute always wins, so fill only the slots there is no attribute + if ((*fDeallocType)[i + shift] == interop::DeallocType::Opaque) + (*fDeallocType)[i + shift] = analyzeRes[i]; } - if (index < fDeallocType->size()) { +} + +//---------------------------------------------------------------------------- +interop::DeallocType cpyrt::CPPMethod::GetDeallocBehaviour(size_t index) { + if (!fDeallocType) + FillDeallocBehaviour(); + if (index < fDeallocType->size()) return (*fDeallocType)[index]; - } return interop::DeallocType::Opaque; } diff --git a/src/cpyrt/CPPMethod.h b/src/cpyrt/CPPMethod.h index 0e7cc168..9a9abba8 100644 --- a/src/cpyrt/CPPMethod.h +++ b/src/cpyrt/CPPMethod.h @@ -109,6 +109,8 @@ class CPPMethod : public PyCallable { void SetPyError_(PyObject* msg); + void FillDeallocBehaviour(); + private: // representation interop::TCppMethod_t fMethod; diff --git a/src/cpyrt/CPPOverload.cxx b/src/cpyrt/CPPOverload.cxx index 5342b0d9..0def55dc 100644 --- a/src/cpyrt/CPPOverload.cxx +++ b/src/cpyrt/CPPOverload.cxx @@ -7,6 +7,7 @@ using namespace cppjit; #include "CPPInstance.h" #include "CPPOverload.h" #include "CallContext.h" +#include "LowLevelViews.h" #include "PyStrings.h" #include "Utility.h" #include "structmember.h" // from Python @@ -162,6 +163,10 @@ static inline PyObject* HandleReturn(CPPOverload* pymeth, CPPInstance* im_self, // if this method creates new objects, always take ownership if (allocates || IsCreator(pymeth->fMethodInfo->fFlags)) { + // Note: for CPPInstance returning functions, if IsCreator(..) returns + // true it will be assumed allocation is done with `new`, and for + // LowLevelView objects, it will be assumed allocator is `new[]` + // either be a constructor with a fresh object proxy self ... if (IsConstructor(pymeth->fMethodInfo->fFlags)) { if (im_self) @@ -190,6 +195,24 @@ static inline PyObject* HandleReturn(CPPOverload* pymeth, CPPInstance* im_self, default: break; } + } else if (LowLevelView_Check(result)) { + LowLevelView* LL = (LowLevelView*)result; + auto& flags = (intptr_t&)LL->fBufInfo.internal; + flags |= LowLevelView::kIsOwner; + switch (AT) { + case interop::AllocType::Malloc: + flags &= ~LowLevelView::kIsCppArray; + break; + case interop::AllocType::New: + case interop::AllocType::OperatorNew: + flags |= LowLevelView::kIsNew; + flags &= ~LowLevelView::kIsCppArray; + break; + // ll_new assumes LL is allocated with newarr default, so no need to + // touch + default: + break; + } } } @@ -230,9 +253,15 @@ static inline PyObject* HandleReturn(CPPOverload* pymeth, CPPInstance* im_self, // the array holds the positional values first, then the keyword ones for (Py_ssize_t i = 0; i < nargs + numKwds; i++) { + const bool isOwnedCppIns = + CPPInstance_Check(args[i]) && + (((CPPInstance*)args[i])->fFlags & CPPInstance::kIsOwner); + const bool isOwnedLL = + (LowLevelView_Check(args[i]) && + ((intptr_t)((LowLevelView*)args[i])->fBufInfo.internal & + LowLevelView::kIsOwner)); // only a C++ object can hold memory that the callee releases - if (!CPPInstance_Check(args[i]) || - !(((CPPInstance*)args[i])->fFlags & CPPInstance::kIsOwner)) + if (!(isOwnedCppIns || isOwnedLL)) continue; Py_ssize_t slot = -1; // no slot of its own @@ -258,7 +287,11 @@ static inline PyObject* HandleReturn(CPPOverload* pymeth, CPPInstance* im_self, if (DT == interop::DeallocType::None || DT == interop::DeallocType::Opaque) continue; - ((CPPInstance*)args[i])->CppOwns(); + if (isOwnedCppIns) + ((CPPInstance*)args[i])->CppOwns(); + else + (intptr_t&)((LowLevelView*)args[i])->fBufInfo.internal &= + ~LowLevelView::kIsOwner; } Py_XDECREF(argnames); diff --git a/src/cpyrt/LowLevelViews.cxx b/src/cpyrt/LowLevelViews.cxx index d4d81fa5..8d390892 100644 --- a/src/cpyrt/LowLevelViews.cxx +++ b/src/cpyrt/LowLevelViews.cxx @@ -11,6 +11,7 @@ using namespace cppjit; #include #include #include +#include #include //= memoryview-like object =================================================== @@ -66,9 +67,11 @@ static void ll_dealloc(cpyrt::LowLevelView* pyobj) { PyMem_Free(pyobj->fBufInfo.strides); if ((intptr_t)pyobj->fBufInfo.internal & cpyrt::LowLevelView::kIsOwner) { if ((intptr_t)pyobj->fBufInfo.internal & cpyrt::LowLevelView::kIsCppArray) - delete[] pyobj->fBuf; + ::operator delete[](pyobj->get_buf()); + else if ((intptr_t)pyobj->fBufInfo.internal & cpyrt::LowLevelView::kIsNew) + ::operator delete(pyobj->get_buf()); else - free(pyobj->fBuf); + free(pyobj->get_buf()); } if (pyobj->fElemCnv != pyobj->fConverter && pyobj->fElemCnv && @@ -107,6 +110,7 @@ static void ll_dealloc(cpyrt::LowLevelView* pyobj) { // clang-format off CPYRT_LL_FLAG_GETSET(ownership, cpyrt::LowLevelView::kIsOwner, __python_owns__) CPYRT_LL_FLAG_GETSET(cpparray, cpyrt::LowLevelView::kIsCppArray, __cpp_array__) +CPYRT_LL_FLAG_GETSET(isnew, cpyrt::LowLevelView::kIsNew, __is_new__) // clang-format on //--------------------------------------------------------------------------- @@ -916,6 +920,8 @@ static PyGetSetDef ll_getset[] = { {(char*)"format", (getter)ll_typecode, nullptr, nullptr, nullptr}, {(char*)"typecode", (getter)ll_typecode, nullptr, nullptr, nullptr}, {(char*)"shape", (getter)ll_shape, (setter)ll_setshape, nullptr, nullptr}, + {(char*)"__is_new__", (getter)ll_getisnew, (setter)ll_setisnew, + (char*)"If true, this buffer is allocated with new", nullptr}, {(char*)nullptr, nullptr, nullptr, nullptr, nullptr}}; namespace cppjit::cpyrt { diff --git a/src/cpyrt/LowLevelViews.h b/src/cpyrt/LowLevelViews.h index 80e7f02b..b3bb2e7d 100644 --- a/src/cpyrt/LowLevelViews.h +++ b/src/cpyrt/LowLevelViews.h @@ -19,8 +19,9 @@ class LowLevelView { kDefault = 0x0000, kIsCppArray = 0x0001, // allocated with new[] kIsFixed = 0x0002, // fixed size array (assumed flat) - kIsOwner = 0x0004 - }; // Python owns + kIsOwner = 0x0004, // Python owns + kIsNew = 0x0008 // memory is allocated with new + }; public: PyObject_HEAD Py_buffer fBufInfo; diff --git a/src/cpyrt/cpyrtModule.cxx b/src/cpyrt/cpyrtModule.cxx index 7f2c07ef..c89ddbc3 100644 --- a/src/cpyrt/cpyrtModule.cxx +++ b/src/cpyrt/cpyrtModule.cxx @@ -240,6 +240,7 @@ PyObject* gAbrtException = nullptr; std::unordered_set gPinnedTypes; std::ostringstream gCapturedError; std::streambuf* gOldErrorBuffer = nullptr; +bool gUseMemoryAnalyzer = false; std::unordered_map>& pythonizations() { static std::unordered_map> pyzMap; @@ -915,6 +916,19 @@ static PyObject* EndCaptureStderr(PyObject*, PyObject*) { return Py_BuildValue("s", capturedError.c_str()); } + +//---------------------------------------------------------------------------- +static PyObject* UseMemoryAnalyzer(PyObject*, PyObject* args) { + // off by default, because the analyzer reads function bodies and only + // guesses the ownership that an attribute would state + int enable = 0; + if (!PyArg_ParseTuple(args, const_cast("p"), &enable)) + return nullptr; + + gUseMemoryAnalyzer = enable; + + Py_RETURN_NONE; +} } // unnamed namespace //- data ----------------------------------------------------------------------- @@ -973,6 +987,8 @@ static PyMethodDef gcpyrtMethods[] = { METH_NOARGS, (char*)"Begin capturing stderr to a in memory buffer."}, {(char*)"_end_capture_stderr", (PyCFunction)EndCaptureStderr, METH_NOARGS, (char*)"End capturing stderr and returns the captured buffer."}, + {(char*)"UseMemoryAnalyzer", (PyCFunction)UseMemoryAnalyzer, METH_VARARGS, + (char*)"Enable/disable the memory ownership analyzer."}, {nullptr, nullptr, 0, nullptr}}; struct module_state { diff --git a/src/interop/cppjit_interop.h b/src/interop/cppjit_interop.h index d4e8e326..fe55a376 100644 --- a/src/interop/cppjit_interop.h +++ b/src/interop/cppjit_interop.h @@ -311,7 +311,11 @@ bool IsConstMethod(TCppMethod_t); RPY_EXPORTED AllocType IsAllocator(TCppMethod_t); RPY_EXPORTED +AllocType GetAllocType(TCppMethod_t); +RPY_EXPORTED bool IsDeallocator(TCppMethod_t, std::vector& VPP); +RPY_EXPORTED +bool GetDeallocType(TCppMethod_t, std::vector& VPP); // Templated method/function reflection information // ------------------------------------ RPY_EXPORTED diff --git a/src/interop/interop_wrapper.cxx b/src/interop/interop_wrapper.cxx index 822983b9..93454b46 100644 --- a/src/interop/interop_wrapper.cxx +++ b/src/interop/interop_wrapper.cxx @@ -1313,11 +1313,22 @@ bool interop::IsDeallocator(TCppMethod_t method, return Cpp::IsDeallocator(method, VPP); } +bool interop::GetDeallocType(TCppMethod_t method, + std::vector& VPP) { + std::lock_guard Lock(InterOpMutex); + return Cpp::GetDeallocType(method, VPP); +} + interop::AllocType interop::IsAllocator(TCppMethod_t method) { std::lock_guard Lock(InterOpMutex); return Cpp::IsAllocator(method); } +interop::AllocType interop::GetAllocType(TCppMethod_t method) { + std::lock_guard Lock(InterOpMutex); + return Cpp::GetAllocType(method); +} + std::string interop::GetMethodReturnTypeAsString(TCppMethod_t method) { std::lock_guard Lock(InterOpMutex); return Cpp::GetTypeAsString( diff --git a/test/cpp/memory_analysis.cxx b/test/cpp/memory_analysis.cxx index d71cd817..667515a8 100644 --- a/test/cpp/memory_analysis.cxx +++ b/test/cpp/memory_analysis.cxx @@ -71,4 +71,28 @@ void memOwner::releaseOverloaded(memOwn* keep, memOwn* obj) { delete obj; } void releaseFree(memOwner* self, memOwn* obj) { delete obj; } +int* allocIntNewArr(int count) { return new int[count]; } + +int* allocIntOperatorNewArr(size_t count) { + return (int*)::operator new[](count * sizeof(int)); +} + +int* allocIntNew() { return new int; } + +int* allocIntOperatorNew() { return (int*)::operator new(sizeof(int)); } + +int* allocIntMalloc(size_t count) { return (int*)malloc(count * sizeof(int)); } + +int* intNoAttrAlloc() { return new int[5]; } + +void releaseBufferArr(int* buf) { delete[] buf; } + +void releaseBuffer(int* buf) { delete buf; } + +void releaseBufferMalloc(int* buf) { free(buf); } + +void keepBuffer(int* buf) { return; } + +void analyzerNoBodyRelease(memOwn* obj) { delete obj; } + } // namespace memory diff --git a/test/cpp/memory_analysis.h b/test/cpp/memory_analysis.h index c288549b..687a9d57 100644 --- a/test/cpp/memory_analysis.h +++ b/test/cpp/memory_analysis.h @@ -90,6 +90,74 @@ struct memOwner { [[clang::annotate("cppDeallocDelete", 2)]] void releaseFree(memOwner* self, memOwn* obj); -} // namespace memory +// A raw pointer to a builtin type binds to a LowLevelView, not an instance +[[clang::annotate("cppAllocNewArr")]] +int* allocIntNewArr(int count); + +[[clang::annotate("cppAllocOperatorNewArr")]] +int* allocIntOperatorNewArr(size_t count); + +[[clang::annotate("cppAllocNew")]] +int* allocIntNew(); + +[[clang::annotate("cppAllocOperatorNew")]] +int* allocIntOperatorNew(); + +[[clang::annotate("cppAllocMalloc")]] +int* allocIntMalloc(size_t count); + +// No ownership attribute anywhere +int* intNoAttrAlloc(); + +[[clang::annotate("cppDeallocDeleteArr", 1)]] +void releaseBufferArr(int* buf); + +[[clang::annotate("cppDeallocDelete", 1)]] +void releaseBuffer(int* buf); + +[[clang::annotate("cppDeallocFree", 1)]] +void releaseBufferMalloc(int* buf); + +[[clang::annotate("cppDeallocNone", 1)]] +void keepBuffer(int* buf); + +// The analyzer reads function bodies, so these must be inline +inline memOwn* analyzerAllocNew() { return new memOwn; } + +inline memOwn* analyzerAllocNewArr() { return new memOwn[5]; } + +inline memOwn* analyzerAllocMalloc() { return (memOwn*)malloc(sizeof(memOwn)); } + +// A method keeps the first answer it gets, so a test that runs with the +// analyzer off needs a function that no other test calls. +inline memOwn* analyzerOffAllocNew() { return new memOwn; } + +inline memOwn* analyzerCachedAllocNew() { return new memOwn; } + +struct analyzerOwner { + void analyzerRelease(memOwn* obj) { delete obj; } + + void analyzerReleaseSecond(memOwn* keep, memOwn* obj) { delete obj; } + + static void analyzerReleaseStatic(memOwn* obj) { delete obj; } + + // the body frees nothing, so the attribute and the analyzer disagree + [[clang::annotate("cppDeallocDelete", 2)]] + void analyzerAttrWins(memOwn* obj) {} + + // the attribute answers for keep, and only the analyzer answers for obj + [[clang::annotate("cppDeallocNone", 2)]] + void analyzerMixedSlots(memOwn* keep, memOwn* obj) { + delete obj; + } + + void analyzerOffRelease(memOwn* obj) { delete obj; } +}; + +inline void analyzerReleaseFree(memOwn* obj) { delete obj; } + +// Defined in memory_analysis.cxx, so the interpreter sees no body of it +void analyzerNoBodyRelease(memOwn* obj); +} // namespace memory #endif // MEMORY_ANALYSIS_H diff --git a/test/test_memoryanalysis.py b/test/test_memoryanalysis.py index 72b3e53b..adb9b312 100644 --- a/test/test_memoryanalysis.py +++ b/test/test_memoryanalysis.py @@ -477,6 +477,379 @@ def test38_bind_object_keeps_the_allocation_kind(self): gc.collect() +class TestLOWLEVELVIEWMEMORY: + def setup_class(cls): + cls.test_dct = test_dct + import cppjit + + cppjit.add_include_path(str(currpath.join("cpp", "MemoryOwnership"))) + cppjit.include("../memory_analysis.h") + cls.memory_analysis = cppjit.load_library(cls.test_dct + ".so") + + def test01_newarr_attr(self): + import cppjit + import cppjit.types + + view = cppjit.gbl.memory.allocIntNewArr(4) + assert type(view) == cppjit.types.LowLevelView + assert view.__python_owns__ + assert view.__cpp_array__ + assert not view.__is_new__ + + # the view frees the buffer with ::operator delete[] + del view + gc.collect() + + def test02_operator_newarr_attr(self): + import cppjit + + view = cppjit.gbl.memory.allocIntOperatorNewArr(4) + assert view.__python_owns__ + assert view.__cpp_array__ + assert not view.__is_new__ + + del view + gc.collect() + + def test03_new_attr(self): + import cppjit + + view = cppjit.gbl.memory.allocIntNew() + assert view.__python_owns__ + assert view.__is_new__ + assert not view.__cpp_array__ + + # the view frees the buffer with ::operator delete + del view + gc.collect() + + def test04_operator_new_attr(self): + import cppjit + + view = cppjit.gbl.memory.allocIntOperatorNew() + assert view.__python_owns__ + assert view.__is_new__ + assert not view.__cpp_array__ + + del view + gc.collect() + + def test05_malloc_attr(self): + import cppjit + + view = cppjit.gbl.memory.allocIntMalloc(4) + assert view.__python_owns__ + # malloc has no flag of its own: no allocation flag means free() + assert not view.__cpp_array__ + assert not view.__is_new__ + + del view + gc.collect() + + def test06_no_attr(self): + import cppjit + + view = cppjit.gbl.memory.intNoAttrAlloc() + assert not view.__python_owns__ + + # function has no attribute, so the flags stay as ll_new wrote them: + # the user takes ownership, therefore the default delete[] is called + view.__python_owns__ = True + assert view.__cpp_array__ + assert not view.__is_new__ + + del view + gc.collect() + + def test07_release_newarr_buffer(self): + import cppjit + + view = cppjit.gbl.memory.allocIntNewArr(4) + assert view.__python_owns__ + + cppjit.gbl.memory.releaseBufferArr(view) + assert not view.__python_owns__ + + del view + gc.collect() + + def test08_release_newarr_buffer_keyword(self): + import cppjit + + view = cppjit.gbl.memory.allocIntNewArr(4) + + cppjit.gbl.memory.releaseBufferArr(buf=view) + assert not view.__python_owns__ + + def test09_release_new_buffer(self): + import cppjit + + view = cppjit.gbl.memory.allocIntNew() + + cppjit.gbl.memory.releaseBuffer(view) + assert not view.__python_owns__ + + del view + gc.collect() + + def test10_release_malloc_buffer(self): + import cppjit + + view = cppjit.gbl.memory.allocIntMalloc(4) + + cppjit.gbl.memory.releaseBufferMalloc(view) + assert not view.__python_owns__ + + del view + gc.collect() + + def test11_keep_buffer(self): + import cppjit + + view = cppjit.gbl.memory.allocIntNewArr(4) + + # a cppDeallocNone parameter leaves the ownership where it was + cppjit.gbl.memory.keepBuffer(view) + assert view.__python_owns__ + + del view + gc.collect() + + def test12_release_with_free(self): + import cppjit + + view = cppjit.gbl.malloc(16) + + cppjit.gbl.free(view) + assert not view.__python_owns__ + + del view + gc.collect() + + +class TestMEMORYANALYZER: + def setup_class(cls): + cls.test_dct = test_dct + import cppjit + + cppjit.add_include_path(str(currpath.join("cpp", "MemoryOwnership"))) + cppjit.include("../memory_analysis.h") + cls.memory_analysis = cppjit.load_library(cls.test_dct + ".so") + + def teardown_class(cls): + import cppjit + + # the flag is global, so the tests that follow must not inherit it + cppjit.use_memory_analyzer(False) + + def test01_alloc_with_analyzer_off(self): + import cppjit + + cppjit.use_memory_analyzer(False) + + obj = cppjit.gbl.memory.analyzerOffAllocNew() + assert not obj.__python_owns__ + + obj.__python_owns__ = True + + def test02_alloc_with_new(self): + import cppjit + + cppjit.use_memory_analyzer(True) + cppjit.gbl.memory.memOwn.dtorCount = 0 + + obj = cppjit.gbl.memory.analyzerAllocNew() + assert obj.__python_owns__ + assert not obj.__is_array_alloc__ + assert not obj.__is_malloc__ + + del obj + gc.collect() + assert cppjit.gbl.memory.memOwn.dtorCount == 1 + + def test03_alloc_with_newarr(self): + import cppjit + + cppjit.use_memory_analyzer(True) + cppjit.gbl.memory.memOwn.dtorCount = 0 + + obj = cppjit.gbl.memory.analyzerAllocNewArr() + assert obj.__python_owns__ + assert obj.__is_array_alloc__ + + del obj + gc.collect() + assert cppjit.gbl.memory.memOwn.dtorCount == 5 + + def test04_alloc_with_malloc(self): + import cppjit + + cppjit.use_memory_analyzer(True) + cppjit.gbl.memory.memOwn.dtorCount = 0 + + obj = cppjit.gbl.memory.analyzerAllocMalloc() + assert obj.__python_owns__ + assert obj.__is_malloc__ + + del obj + gc.collect() + assert cppjit.gbl.memory.memOwn.dtorCount == 0 + + def test05_cached_answer_(self): + import cppjit + + cppjit.use_memory_analyzer(True) + + first = cppjit.gbl.memory.analyzerCachedAllocNew() + assert first.__python_owns__ + + cppjit.use_memory_analyzer(False) + second = cppjit.gbl.memory.analyzerCachedAllocNew() + assert second.__python_owns__ + + def test06_release_bound_positional(self): + import cppjit + + cppjit.use_memory_analyzer(True) + owner = cppjit.gbl.memory.analyzerOwner() + obj = cppjit.gbl.memory.memOwn(5) + assert obj.__python_owns__ + + owner.analyzerRelease(obj) + assert not obj.__python_owns__ + assert owner.__python_owns__ + + def test07_release_bound_keyword(self): + import cppjit + + cppjit.use_memory_analyzer(True) + owner = cppjit.gbl.memory.analyzerOwner() + obj = cppjit.gbl.memory.memOwn(5) + + owner.analyzerRelease(obj=obj) + assert not obj.__python_owns__ + assert owner.__python_owns__ + + def test08_release_unbound_positional(self): + import cppjit + + cppjit.use_memory_analyzer(True) + owner = cppjit.gbl.memory.analyzerOwner() + obj = cppjit.gbl.memory.memOwn(5) + + cppjit.gbl.memory.analyzerOwner.analyzerRelease(owner, obj) + assert not obj.__python_owns__ + assert owner.__python_owns__ + + def test09_release_second_parameter(self): + import cppjit + + cppjit.use_memory_analyzer(True) + owner = cppjit.gbl.memory.analyzerOwner() + keep = cppjit.gbl.memory.memOwn(5) + obj = cppjit.gbl.memory.memOwn(5) + + owner.analyzerReleaseSecond(keep, obj) + assert not obj.__python_owns__ + assert keep.__python_owns__ + assert owner.__python_owns__ + + def test10_release_second_parameter_keyword_reversed(self): + import cppjit + + cppjit.use_memory_analyzer(True) + owner = cppjit.gbl.memory.analyzerOwner() + keep = cppjit.gbl.memory.memOwn(5) + obj = cppjit.gbl.memory.memOwn(5) + + owner.analyzerReleaseSecond(obj=obj, keep=keep) + assert not obj.__python_owns__ + assert keep.__python_owns__ + + def test11_release_static_from_class(self): + import cppjit + + cppjit.use_memory_analyzer(True) + obj = cppjit.gbl.memory.memOwn(5) + + cppjit.gbl.memory.analyzerOwner.analyzerReleaseStatic(obj) + assert not obj.__python_owns__ + + def test12_release_static_from_instance(self): + import cppjit + + cppjit.use_memory_analyzer(True) + owner = cppjit.gbl.memory.analyzerOwner() + obj = cppjit.gbl.memory.memOwn(5) + + owner.analyzerReleaseStatic(obj) + assert not obj.__python_owns__ + assert owner.__python_owns__ + + def test13_release_free_function(self): + import cppjit + + cppjit.use_memory_analyzer(True) + obj = cppjit.gbl.memory.memOwn(5) + + cppjit.gbl.memory.analyzerReleaseFree(obj) + assert not obj.__python_owns__ + + def test14_attribute_wins(self): + import cppjit + + cppjit.use_memory_analyzer(True) + cppjit.gbl.memory.memOwn.dtorCount = 0 + owner = cppjit.gbl.memory.analyzerOwner() + obj = cppjit.gbl.memory.memOwn(5) + + owner.analyzerAttrWins(obj) + # the attribute says delete although the body frees nothing, and the + # attribute wins + assert not obj.__python_owns__ + assert cppjit.gbl.memory.memOwn.dtorCount == 0 + + obj.__python_owns__ = True + del obj + gc.collect() + assert cppjit.gbl.memory.memOwn.dtorCount == 1 + + def test15_attribute_and_body_on_different_arg(self): + import cppjit + + cppjit.use_memory_analyzer(True) + owner = cppjit.gbl.memory.analyzerOwner() + keep = cppjit.gbl.memory.memOwn(5) + obj = cppjit.gbl.memory.memOwn(5) + + owner.analyzerMixedSlots(keep, obj) + assert keep.__python_owns__ + assert not obj.__python_owns__ + + def test16_release_with_analyzer_off(self): + import cppjit + + cppjit.use_memory_analyzer(False) + owner = cppjit.gbl.memory.analyzerOwner() + obj = cppjit.gbl.memory.memOwn(5) + + owner.analyzerOffRelease(obj) + assert obj.__python_owns__ + + obj.__python_owns__ = False + + def test17_release_without_a_body(self): + import cppjit + + cppjit.use_memory_analyzer(True) + obj = cppjit.gbl.memory.memOwn(5) + + cppjit.gbl.memory.analyzerNoBodyRelease(obj) + assert obj.__python_owns__ + + obj.__python_owns__ = False + + @mark.skipif(not IN_CHILD, reason="needs " + FLAGS) class TestMEMORYANALYSIS_APINOTES: def setup_class(cls):