Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions python/cppjit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
47 changes: 40 additions & 7 deletions src/cpyrt/CPPMethod.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -32,6 +34,7 @@ extern PyObject* gBusException;
extern PyObject* gSegvException;
extern PyObject* gIllException;
extern PyObject* gAbrtException;
extern bool gUseMemoryAnalyzer;
} // namespace cppjit::cpyrt

//- public helper ------------------------------------------------------------
Expand Down Expand Up @@ -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<interop::DeallocType> 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<CPPClassMethod*>(this) ||
dynamic_cast<CPPFunction*>(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;
}

Expand Down
2 changes: 2 additions & 0 deletions src/cpyrt/CPPMethod.h
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ class CPPMethod : public PyCallable {

void SetPyError_(PyObject* msg);

void FillDeallocBehaviour();

private:
// representation
interop::TCppMethod_t fMethod;
Expand Down
39 changes: 36 additions & 3 deletions src/cpyrt/CPPOverload.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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;
}
}
}

Expand Down Expand Up @@ -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
Expand All @@ -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);

Expand Down
10 changes: 8 additions & 2 deletions src/cpyrt/LowLevelViews.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ using namespace cppjit;
#include <assert.h>
#include <limits.h>
#include <map>
#include <new>
#include <string.h>

//= memoryview-like object ===================================================
Expand Down Expand Up @@ -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 &&
Expand Down Expand Up @@ -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

//---------------------------------------------------------------------------
Expand Down Expand Up @@ -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 {
Expand Down
5 changes: 3 additions & 2 deletions src/cpyrt/LowLevelViews.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
16 changes: 16 additions & 0 deletions src/cpyrt/cpyrtModule.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ PyObject* gAbrtException = nullptr;
std::unordered_set<interop::TCppScope_t> gPinnedTypes;
std::ostringstream gCapturedError;
std::streambuf* gOldErrorBuffer = nullptr;
bool gUseMemoryAnalyzer = false;

std::unordered_map<std::string, std::vector<PyObject*>>& pythonizations() {
static std::unordered_map<std::string, std::vector<PyObject*>> pyzMap;
Expand Down Expand Up @@ -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<char*>("p"), &enable))
return nullptr;

gUseMemoryAnalyzer = enable;

Py_RETURN_NONE;
}
} // unnamed namespace

//- data -----------------------------------------------------------------------
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 4 additions & 0 deletions src/interop/cppjit_interop.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<DeallocType>& VPP);
RPY_EXPORTED
bool GetDeallocType(TCppMethod_t, std::vector<DeallocType>& VPP);
// Templated method/function reflection information
// ------------------------------------
RPY_EXPORTED
Expand Down
11 changes: 11 additions & 0 deletions src/interop/interop_wrapper.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -1313,11 +1313,22 @@ bool interop::IsDeallocator(TCppMethod_t method,
return Cpp::IsDeallocator(method, VPP);
}

bool interop::GetDeallocType(TCppMethod_t method,
std::vector<DeallocType>& VPP) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetDeallocType(method, VPP);
}

interop::AllocType interop::IsAllocator(TCppMethod_t method) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::IsAllocator(method);
}

interop::AllocType interop::GetAllocType(TCppMethod_t method) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetAllocType(method);
}

std::string interop::GetMethodReturnTypeAsString(TCppMethod_t method) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetTypeAsString(
Expand Down
24 changes: 24 additions & 0 deletions test/cpp/memory_analysis.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading
Loading