Skip to content
Merged
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
87 changes: 6 additions & 81 deletions graalpython/com.oracle.graal.python.cext/src/memoryobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,9 @@ PyTypeObject _PyManagedBuffer_Type = {

/* In the process of breaking reference cycles mbuf_release() can be
called before memory_release(). */
// GraalPy change: don't use the manager
// GraalPy change: upcall
#define BASE_INACCESSIBLE(mv) \
(((PyMemoryViewObject *)mv)->flags&_Py_MEMORYVIEW_RELEASED)
GraalPyPrivate_MemoryViewIsReleased((PyObject *)(mv))

#define CHECK_RELEASED(mv) \
if (BASE_INACCESSIBLE(mv)) { \
Expand Down Expand Up @@ -1513,88 +1513,13 @@ memoryview_toreadonly_impl(PyMemoryViewObject *self)
Py_LOCAL_SYMBOL int // GraalPy change: hidden for capi.c
memory_getbuf(PyMemoryViewObject *self, Py_buffer *view, int flags)
{
Py_buffer *base = &self->view;
int baseflags = self->flags;

CHECK_RELEASED_INT(self);
CHECK_RESTRICTED_INT(self);

/* start with complete information */
*view = *base;
view->obj = NULL;

if (REQ_WRITABLE(flags) && base->readonly) {
PyErr_SetString(PyExc_BufferError,
"memoryview: underlying buffer is not writable");
return -1;
}
if (!REQ_FORMAT(flags)) {
/* NULL indicates that the buffer's data type has been cast to 'B'.
view->itemsize is the _previous_ itemsize. If shape is present,
the equality product(shape) * itemsize = len still holds at this
point. The equality calcsize(format) = itemsize does _not_ hold
from here on! */
view->format = NULL;
}

if (REQ_C_CONTIGUOUS(flags) && !MV_C_CONTIGUOUS(baseflags)) {
PyErr_SetString(PyExc_BufferError,
"memoryview: underlying buffer is not C-contiguous");
return -1;
}
if (REQ_F_CONTIGUOUS(flags) && !MV_F_CONTIGUOUS(baseflags)) {
PyErr_SetString(PyExc_BufferError,
"memoryview: underlying buffer is not Fortran contiguous");
return -1;
}
if (REQ_ANY_CONTIGUOUS(flags) && !MV_ANY_CONTIGUOUS(baseflags)) {
PyErr_SetString(PyExc_BufferError,
"memoryview: underlying buffer is not contiguous");
return -1;
}
if (!REQ_INDIRECT(flags) && (baseflags & _Py_MEMORYVIEW_PIL)) {
PyErr_SetString(PyExc_BufferError,
"memoryview: underlying buffer requires suboffsets");
return -1;
}
if (!REQ_STRIDES(flags)) {
if (!MV_C_CONTIGUOUS(baseflags)) {
PyErr_SetString(PyExc_BufferError,
"memoryview: underlying buffer is not C-contiguous");
return -1;
}
view->strides = NULL;
}
if (!REQ_SHAPE(flags)) {
/* PyBUF_SIMPLE or PyBUF_WRITABLE: at this point buf is C-contiguous,
so base->buf = ndbuf->data. */
if (view->format != NULL) {
/* PyBUF_SIMPLE|PyBUF_FORMAT and PyBUF_WRITABLE|PyBUF_FORMAT do
not make sense. */
PyErr_Format(PyExc_BufferError,
"memoryview: cannot cast to unsigned bytes if the format flag "
"is present");
return -1;
}
/* product(shape) * itemsize = len and calcsize(format) = itemsize
do _not_ hold from here on! */
view->ndim = 1;
view->shape = NULL;
}


view->obj = Py_NewRef(self);
self->exports++;

return 0;
return GraalPyPrivate_MemoryViewGetBuffer((PyObject *)self, view, flags);
}

Py_LOCAL_SYMBOL void // GraalPy change: hidden for capi.c
memory_releasebuf(PyMemoryViewObject *self, Py_buffer *view)
{
self->exports--;
return;
/* PyBuffer_Release() decrements view->obj after this function returns. */
GraalPyPrivate_MemoryViewReleaseBuffer((PyObject *)self, view);
}

#if 0 // GraalPy change
Expand Down Expand Up @@ -3525,11 +3450,11 @@ GraalPyPrivate_ReleaseBuffer(Py_buffer* buffer)
Py_buffer *
GraalPyMemoryView_GET_BUFFER(PyObject *op)
{
return &_PyMemoryView_CAST(op)->view;
return GraalPyPrivate_MemoryViewBuffer(op);
}

PyObject *
GraalPyMemoryView_GET_BASE(PyObject *op)
{
return _PyMemoryView_CAST(op)->view.obj;
return GraalPyPrivate_MemoryViewBase(op);
}
Original file line number Diff line number Diff line change
Expand Up @@ -108,14 +108,14 @@ assert list(proxy) == []
ReadFrameNode.AllPythonFramesSelector.INSTANCE, 0, CallerFlags.ALL_FRAME_FLAGS);
assertNotNull(result);
MaterializeFrameNode materialize = MaterializeFrameNode.getUncached();
assertThrows(AssertionError.class, () -> materialize.execute(null, false, false, result.frame()));
assertThrows(AssertionError.class, () -> materialize.execute(null, false, 0, result.frame()));
BytecodeFrame captured = null;
if (captureFirst) {
captured = materialize.execute(result.callNode(), true, true, result.frame()).getBytecodeFrame();
captured = materialize.execute(result.callNode(), true, CallerFlags.NEEDS_LOCALS, result.frame()).getBytecodeFrame();
assertNotNull(captured);
}
Node unavailable = PythonLanguage.get(null).unavailableSafepointLocation;
PFrame pyFrame = materialize.execute(unavailable, true, true, result.frame());
PFrame pyFrame = materialize.execute(unavailable, true, CallerFlags.NEEDS_LOCALS, result.frame());
assertNull(pyFrame.getBytecodeNode());
assertEquals(-1, pyFrame.getBci());
assertEquals(-1, pyFrame.getLine());
Expand All @@ -126,7 +126,7 @@ assert list(proxy) == []
checkLocals.execute(context.asValue(pyFrame), captureFirst);

// A later observation with a valid location must resume normal locals capture.
assertSame(pyFrame, materialize.execute(result.callNode(), true, true, result.frame()));
assertSame(pyFrame, materialize.execute(result.callNode(), true, CallerFlags.NEEDS_LOCALS, result.frame()));
assertNotNull(pyFrame.getBytecodeNode());
assertNotNull(pyFrame.getBytecodeFrame());
assertTrue(pyFrame.hasMaterializedFrame() || pyFrame.syncsLocals());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# The Universal Permissive License (UPL), Version 1.0
#
# Subject to the condition set forth below, permission is hereby granted to any
# person obtaining a copy of this software, associated documentation and/or
# data (collectively the "Software"), free of charge and under any and all
# copyright rights in the Software, and any and all patent rights owned or
# freely licensable by each licensor hereunder covering either (i) the
# unmodified Software as contributed to or provided by such licensor, or (ii)
# the Larger Works (as defined below), to deal in both
#
# (a) the Software, and
#
# (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
# one is included with the Software each a "Larger Work" to which the Software
# is contributed by such licensors),
#
# without restriction, including without limitation the rights to copy, create
# derivative works of, display, perform, and distribute the Software and make,
# use, sell, offer for sale, import, export, have made, and have sold the
# Software and the Larger Work(s), and to sublicense the foregoing rights on
# either these or other terms.
#
# This license is subject to the following condition:
#
# The above copyright notice and either this complete permission notice or at a
# minimum a reference to the UPL must be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from unittest import TestCase, skipUnless

from . import CPyExtType, GRAALPYTHON

if GRAALPYTHON:
import java
from __graalpython__ import is_native
else:
is_native = False


@skipUnless(GRAALPYTHON and not is_native, "requires GraalPy Java interop")
class TestInteropBuffer(TestCase):
@classmethod
def setUpClass(cls):
cls.reader = CPyExtType(
"InteropBufferReader",
"""
static PyObject* read_buffer(PyObject* self, PyObject* obj) {
Py_buffer view;
if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) < 0) {
return NULL;
}
PyObject* result = PyBytes_FromStringAndSize((const char*)view.buf, view.len);
PyBuffer_Release(&view);
return result;
}
""",
tp_methods='{"read_buffer", read_buffer, METH_O, ""}',
)()

def setUp(self):
self.buffer = java.type("java.nio.ByteBuffer").allocate(4)
for i, value in enumerate(b"test"):
self.buffer.put(i, value)

def test_getbuffer(self):
self.assertRaises(TypeError, self.reader.read_buffer, self.buffer)

def test_getbuffer_memoryview(self):
with memoryview(self.buffer) as view:
# memoryview supports interop objects, but sending them to native causes a copy with a warning
self.assertEqual(self.reader.read_buffer(view), b"test")
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,79 @@ class TestPyMemoryView(CPyExtTestCase):


class TestObject(unittest.TestCase):
def test_memoryview_native_exports(self):
TestType = CPyExtType(
"TestMemoryViewNativeExports",
"""
static PyObject *acquire(PyObject *self, PyObject *args) {
PyObject *obj;
int flags;
if (!PyArg_ParseTuple(args, "Oi", &obj, &flags)) {
return NULL;
}
TestMemoryViewNativeExportsObject *holder = (TestMemoryViewNativeExportsObject *)self;
if (holder->view.obj != NULL) {
PyErr_SetString(PyExc_RuntimeError, "buffer already acquired");
return NULL;
}
if (PyObject_GetBuffer(obj, &holder->view, flags) < 0) {
return NULL;
}
Py_buffer *v = &holder->view;
return Py_BuildValue("nniiii", v->len, v->itemsize, v->ndim,
v->format != NULL, v->shape != NULL, v->strides != NULL);
}
static PyObject *drop(PyObject *self, PyObject *unused) {
PyBuffer_Release(&((TestMemoryViewNativeExportsObject *)self)->view);
Py_RETURN_NONE;
}
static PyObject *read_buffer(PyObject *self, PyObject *unused) {
Py_buffer *v = &((TestMemoryViewNativeExportsObject *)self)->view;
PyObject *result = PyBytes_FromStringAndSize(NULL, v->len);
if (result != NULL && PyBuffer_ToContiguous(PyBytes_AS_STRING(result), v, v->len, 'C') < 0) {
Py_CLEAR(result);
}
return result;
}
""",
cmembers='Py_buffer view;',
tp_methods='''
{"acquire", acquire, METH_VARARGS, ""},
{"drop", drop, METH_NOARGS, ""},
{"read", read_buffer, METH_NOARGS, ""}
''',
)
first, second = TestType(), TestType()
mv = memoryview(bytearray(b'abcdefgh'))[1:7].cast('H', shape=[1, 3])
assert first.acquire(mv, 0x11c) == (6, 2, 2, 1, 1, 1) # PyBUF_FULL_RO
assert second.acquire(mv, 0) == (6, 2, 1, 0, 0, 0) # PyBUF_SIMPLE
assert first.read() == b'bcdefg'
with self.assertRaises(BufferError):
mv.release()
first.drop()
with self.assertRaises(BufferError):
mv.release()
second.drop()
mv.release()
with self.assertRaises(ValueError):
first.acquire(mv, 0x11c)

for mv, flags in [(memoryview(b'abc'), 1), # PyBUF_WRITABLE
(memoryview(b'abcdef')[::2], 0),
(memoryview(b'abcdef')[::2], 0x38), # PyBUF_C_CONTIGUOUS
(memoryview(b'abcdef')[::2], 0x58), # PyBUF_F_CONTIGUOUS
(memoryview(b'abcdef')[::2], 0x98), # PyBUF_ANY_CONTIGUOUS
(memoryview(b'abc'), 4)]: # PyBUF_SIMPLE | PyBUF_FORMAT
with self.assertRaises(BufferError):
first.acquire(mv, flags)
mv.release() # Failed acquisition must not leave an export behind.

mv = memoryview(bytearray(b'abcdef'))[::2]
assert first.acquire(mv, 0x11c) == (3, 1, 1, 1, 1, 1)
assert first.read() == b'ace'
first.drop()
mv.release()

def test_memoryview_fromobject_multidim(self):
TestType = CPyExtType(
"TestMemoryViewMultidim",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
import com.oracle.graal.python.pegparser.sst.StmtTy;
import com.oracle.graal.python.pegparser.sst.TypeParamTy;
import com.oracle.graal.python.pegparser.tokenizer.SourceRange;
import com.oracle.graal.python.runtime.CallerFlags;
import com.oracle.graal.python.runtime.GilNode;
import com.oracle.graal.python.runtime.IndirectCallData.BoundaryCallData;
import com.oracle.graal.python.runtime.IndirectCallData.InteropCallData;
Expand Down Expand Up @@ -752,7 +753,7 @@ public ExecutableNode parse(InlineParsingRequest request) {
@Override
public Object execute(VirtualFrame frame) {
Object[] arguments = PArguments.create();
PFrame pFrame = materializeFrameNode.execute(this, false, true, frame);
PFrame pFrame = materializeFrameNode.execute(this, false, CallerFlags.NEEDS_LOCALS, frame);
Object pLocals = getFrameLocalsNode.executeCached(frame, pFrame, true);
PArguments.setSpecialArgument(arguments, pLocals);
PArguments.setCodeObject(arguments, PFactory.createCode(getLanguage(PythonLanguage.class), callTarget));
Expand Down
Loading
Loading