Skip to content

Commit

Permalink
pycsp: Release Py_Buffers after use
Browse files Browse the repository at this point in the history
The documentation for `w*` specifies that
> The caller have to call PyBuffer_Release() when it is done with the buffer.

https://docs.python.org/3/c-api/arg.html
  • Loading branch information
jichgom committed Jul 1, 2024
1 parent 3367f66 commit 2173b6b
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/bindings/python/pycsp.c
Original file line number Diff line number Diff line change
Expand Up @@ -270,11 +270,12 @@ static PyObject* pycsp_transaction(PyObject *self, PyObject *args) {
Py_BEGIN_ALLOW_THREADS;
res = csp_transaction(prio, dest, port, timeout, outbuf.buf, outbuf.len, inbuf.buf, inbuf.len);
Py_END_ALLOW_THREADS;
if (res < 1) {
return PyErr_Error("csp_transaction()", res);
}

return Py_BuildValue("i", res);
PyBuffer_Release(&inbuf);
PyBuffer_Release(&outbuf);
return res < 1
? PyErr_Error("csp_transaction()", res)
: Py_BuildValue("i", res);
}

static PyObject* pycsp_sendto(PyObject *self, PyObject *args) {
Expand Down Expand Up @@ -694,6 +695,7 @@ static PyObject* pycsp_cmp_peek(PyObject *self, PyObject *args) {
}

if ((len > CSP_CMP_PEEK_MAX_LEN) || (len > outbuf.len)) {
PyBuffer_Release(&outbuf);
return PyErr_Error("csp_cmp_peek() - exceeding max size", CSP_ERR_INVAL);
}

Expand All @@ -707,11 +709,13 @@ static PyObject* pycsp_cmp_peek(PyObject *self, PyObject *args) {
res = csp_cmp_peek(node, timeout, &msg);
Py_END_ALLOW_THREADS;
if (res != CSP_ERR_NONE) {
PyBuffer_Release(&outbuf);
return PyErr_Error("csp_cmp_peek()", res);
}
memcpy(outbuf.buf, msg.peek.data, len);
outbuf.len = len;

PyBuffer_Release(&outbuf);
Py_RETURN_NONE;
}

Expand All @@ -727,6 +731,7 @@ static PyObject* pycsp_cmp_poke(PyObject *self, PyObject *args) {
}

if (len > CSP_CMP_POKE_MAX_LEN) {
PyBuffer_Release(&inbuf);
return PyErr_Error("csp_cmp_poke() - exceeding max size", CSP_ERR_INVAL);
}
struct csp_cmp_message msg;
Expand All @@ -739,9 +744,11 @@ static PyObject* pycsp_cmp_poke(PyObject *self, PyObject *args) {
res = csp_cmp_poke(node, timeout, &msg);
Py_END_ALLOW_THREADS;
if (res != CSP_ERR_NONE) {
PyBuffer_Release(&inbuf);
return PyErr_Error("csp_cmp_poke()", res);
}

PyBuffer_Release(&inbuf);
Py_RETURN_NONE;
}

Expand Down Expand Up @@ -945,15 +952,18 @@ static PyObject* pycsp_packet_set_data(PyObject *self, PyObject *args) {

csp_packet_t * packet = get_obj_as_packet(packet_capsule, false);
if (packet == NULL) {
PyBuffer_Release(&data);
return NULL; // TypeError is thrown
}
if (data.len > (int)csp_buffer_data_size()) {
PyBuffer_Release(&data);
return PyErr_Error("packet_set_data() - exceeding data size", CSP_ERR_INVAL);
}

memcpy(packet->data, data.buf, data.len);
packet->length = data.len;

PyBuffer_Release(&data);
Py_RETURN_NONE;
}

Expand Down

0 comments on commit 2173b6b

Please sign in to comment.