Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
2cfd690
Use pinning instead of native malloc for Python object stubs.
fangerer Oct 20, 2025
6202699
Use pinned allocation
fangerer Nov 13, 2025
9b06ee7
Avoid handle table in image heap
fangerer Nov 17, 2025
795c41a
Fixup
fangerer Nov 27, 2025
98d55eb
Support ensureWeak
fangerer Jan 20, 2026
f7f8ba1
Refactor GraalPyVarObject
fangerer Jan 20, 2026
df0e054
Make keep-alive list a doubly-linked list
fangerer Mar 16, 2026
7104253
Support GraalPyUnicodeObject layout
fangerer May 13, 2026
4f7822d
Use pinned array allocation for unicode data
fangerer Jun 10, 2026
cbd1ec0
Fix native-image Unicode storage and GC handling
fangerer Sep 7, 2026
2bd593d
Specialize pinned native companion layouts
fangerer Sep 9, 2026
947e22a
Use org.graalvm.nativeimage.impl.PinnedObjectSupport.
peter-hofer Sep 22, 2026
3e2e51f
Fall back to off-heap storage for large Unicode buffers
fangerer Oct 9, 2026
83f396f
Handle collected pinned referents consistently during native conversion
fangerer Nov 5, 2026
b53b216
Select pinned native companions using the image GC capability
fangerer Nov 5, 2026
15e5822
Introduce a native companion facade with handle-table and pinned impl…
fangerer Nov 5, 2026
529fa17
Describe native companion ownership with explicit states and operations
fangerer Nov 5, 2026
f619482
Encapsulate native companion state in backend-specific contexts
fangerer Nov 10, 2026
5034898
Isolate the Native Image companion layout contract
fangerer Nov 12, 2026
0134fac
Share native companion storage in PythonObject
fangerer Nov 12, 2026
2b5f423
Distinguish collected referents from freed native companions
fangerer Nov 13, 2026
8a79070
Preserve backing storage of native Unicode views
fangerer Nov 13, 2026
551cc0c
Document native companion backends and memory ownership
fangerer Nov 13, 2026
37677c1
Handle unavailable native pinning APIs and remove unused compiler export
fangerer Nov 27, 2026
0eb5dab
Expose and log the selected native companion backend
fangerer Dec 1, 2026
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
573 changes: 322 additions & 251 deletions docs/contributor/IMPLEMENTATION_DETAILS.md

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion graalpython/com.oracle.graal.python.cext/src/capi.h
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,10 @@ Py_LOCAL_SYMBOL void GraalPyPrivate_DebugTrace(void);

typedef struct {
PyObject_HEAD
int32_t handle_table_index;
union {
int32_t i;
int64_t ensure_padding; /* ensures 8-byte alignment */
} handle_table_index;
} GraalPyObject;

typedef struct {
Expand Down
17 changes: 2 additions & 15 deletions graalpython/com.oracle.graal.python.cext/src/gcmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -510,21 +510,8 @@ push_native_references_to_managed(PyObject *op, GraalPyGC_Cycle *cycle)
/* An empty traversal must replace an earlier snapshot too. Managed
* objects are not traversed here; their Java references need no refresh. */
if (cycle->state == GraalPyGC_Cycle_Valid && (cycle->n > 0 || !is_managed(op))) {
int dead = 0;
// Some managed handles can be already collected if the GC is already cleaning the cycle
for (int32_t i = 0; i < cycle->n; i++) {
if (points_to_py_handle_space(cycle->items[i])) {
GraalPyObject* obj = (GraalPyObject*)pointer_to_stub(cycle->items[i]);
if (obj->handle_table_index == 0) {
dead = 1;
break;
}
}
}
if (!dead) {
if (GraalPyPrivate_Object_ReplicateNativeReferences(op, cycle->items, cycle->n) < 0) {
cycle->state = GraalPyGC_Cycle_ReplicationFailed;
}
if (GraalPyPrivate_Object_ReplicateNativeReferences(op, cycle->items, cycle->n) < 0) {
cycle->state = GraalPyGC_Cycle_ReplicationFailed;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15680,7 +15680,7 @@ void* GraalPyUnicode_NONCOMPACT_DATA(PyObject* op) {

void* GraalPyUnicode_COMPACT_DATA(PyObject* op) {
if (points_to_py_handle_space(op)) {
return _Py_STATIC_CAST(void*, GraalpyUnicodeObject_EnsureNativeData(op) + 1);
return GraalpyUnicodeObject_EnsureNativeData(op)->data;
}
if (PyUnicode_IS_ASCII(op)) {
return _Py_STATIC_CAST(void*, (_PyASCIIObject_CAST(op) + 1));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
* 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.
*/
package com.oracle.graal.python.test.builtin.objects.cext;

import static com.oracle.graal.python.util.PythonUtils.TS_ENCODING;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.junit.Assume;
import org.junit.Test;

import com.oracle.graal.python.PythonLanguage;
import com.oracle.graal.python.builtins.objects.cext.capi.CApiContext;
import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.HandlePointerConverter;
import com.oracle.graal.python.builtins.objects.cext.capi.transitions.NativeCompanions;
import com.oracle.graal.python.builtins.objects.cext.structs.CFields;
import com.oracle.graal.python.builtins.objects.cext.structs.CStructAccess;
import com.oracle.graal.python.builtins.objects.object.PythonObject;
import com.oracle.graal.python.builtins.objects.str.PString;
import com.oracle.graal.python.builtins.objects.str.StringNodes.StringMaterializeNode;
import com.oracle.graal.python.runtime.GilNode;
import com.oracle.graal.python.runtime.nativeaccess.NativeMemory;
import com.oracle.graal.python.runtime.object.PFactory;
import com.oracle.graal.python.test.PythonTests;
import com.oracle.truffle.api.strings.TruffleString;

public class NativeStringLifetimeTest {
private static void assertIndependent(String expected, TruffleString string) {
assertFalse(string.isNative());
TruffleString utf8 = string.switchEncodingUncached(TruffleString.Encoding.UTF_8);
assertFalse(utf8.isNative());
assertEquals(expected, utf8.toJavaStringUncached());
assertEquals(expected, string.switchEncodingUncached(TS_ENCODING).toJavaStringUncached());
}

@Test
@SuppressWarnings("try")
public void materializedUnicodeOutlivesContext() {
Assume.assumeFalse("Native-module isolation does not support Mach-O libraries", PythonTests.isMacOS());
List<TruffleString> retained = new ArrayList<>();
List<String> expected = new ArrayList<>();
PythonTests.enterContext(Map.of("python.IsolateNativeModules", "true"), new String[0]);
try (GilNode.UncachedAcquire ignored = GilNode.uncachedAcquire()) {
CApiContext.ensureCapiWasLoaded("native string lifetime test");
int[] characters = {'a', 0xe9, 0x20ac, 0x1f600};
for (int character : characters) {
int kind = character <= 0xff ? 1 : character <= 0xffff ? 2 : 4;
for (int length : new int[]{37, 256 * 1024}) {
PString string = PFactory.createString(PythonLanguage.get(null), null);
long size = (long) length * kind;
long pointer = NativeCompanions.get().allocateUnicode(string, PythonObject.MANAGED_REFCNT + 1,
length, size, kind, character < 128, size + kind);
long data = CStructAccess.readPtrField(HandlePointerConverter.pointerToStub(pointer), CFields.GraalPyUnicodeObject__data);
for (int i = 0; i < length; i++) {
if (kind == 1) {
NativeMemory.writeByteArrayElement(data, i, (byte) character);
} else if (kind == 2) {
NativeMemory.writeShortArrayElement(data, i, (short) character);
} else {
NativeMemory.writeIntArrayElement(data, i, character);
}
}
TruffleString materialized = StringMaterializeNode.executeUncached(string);
// Poison the still-live native allocation for a deterministic check, then
// retain only the TruffleString across context shutdown, as an AST could.
NativeMemory.memset(data, (byte) 0, size);
String value = new String(Character.toChars(character)).repeat(length);
assertIndependent(value, materialized);
retained.add(materialized);
expected.add(value);
}
}
} finally {
PythonTests.closeContext();
}
PythonTests.enterContext();
try {
for (int i = 0; i < retained.size(); i++) {
assertIndependent(expected.get(i), retained.get(i));
}
} finally {
PythonTests.closeContext();
}
}
}
105 changes: 105 additions & 0 deletions graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_gc.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
import sys
import time
import unittest
import weakref
from unittest import skipIf

from . import CPyExtType
Expand Down Expand Up @@ -1037,6 +1038,34 @@ def test_current_rss_monitor():
GCGraphNode = CPyExtType("GCGraphNode", r'''
static PyObject *saved = NULL;

#if GRAALVM_PYTHON
#include <graalpy/testcapi.h>
PyAPI_FUNC(int) _PyObject_IsFreed(PyObject *);
static PyObject *pending_companion = NULL;

static PyObject *graph_suspend_cleanup(GCGraphNodeObject *self, PyObject *unused) {
if (GraalPyTestCAPI->DisableReferenceQueuePolling()) {
PyErr_SetString(PyExc_RuntimeError, "reference queue polling is already active");
return NULL;
}
/* Borrow the pointer while queue polling is suspended: the native owner
* and its companion cannot be deallocated until cleanup resumes. */
pending_companion = self->left;
Py_RETURN_NONE;
}

static PyObject *graph_collect_and_check(PyObject *cls, PyObject *unused) {
GraalPyTestCAPI->TriggerGC(50);
return PyBool_FromLong(_PyObject_IsFreed(pending_companion));
}

static PyObject *graph_resume_cleanup(PyObject *cls, PyObject *unused) {
pending_companion = NULL;
GraalPyTestCAPI->EnableReferenceQueuePolling();
Py_RETURN_NONE;
}
#endif

static PyObject *graph_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) {
PyObject *left = NULL;
if (!PyArg_ParseTuple(args, "|O", &left)) {
Expand Down Expand Up @@ -1104,8 +1133,20 @@ def test_current_rss_monitor():
tp_methods='''
{"set", (PyCFunction)graph_set, METH_VARARGS, ""},
{"hold", (PyCFunction)graph_hold, METH_O, ""},
#if GRAALVM_PYTHON
{"suspend_cleanup", (PyCFunction)graph_suspend_cleanup, METH_NOARGS, ""},
{"collect_and_check", (PyCFunction)graph_collect_and_check, METH_NOARGS | METH_CLASS, ""},
{"resume_cleanup", (PyCFunction)graph_resume_cleanup, METH_NOARGS | METH_CLASS, ""},
#endif
{"release", (PyCFunction)graph_release, METH_NOARGS | METH_CLASS, ""}
''',
ready_code='''
#if GRAALVM_PYTHON
if (GraalPyTestCAPI_Import() < 0) {
return NULL;
}
#endif
''',
)


Expand All @@ -1120,6 +1161,70 @@ def collect_graph():
def tearDown(self):
GCGraphNode.release()

@skipIf(not GRAALPY, "Requires GraalPy reference-queue control")
def test_collected_referent_does_not_mean_freed_companion(self):
class ManagedList(list):
pass

managed = ManagedList()
holder = GCGraphNode(managed)
managed.append(holder)
self.collect_graph()
assert_is_weak(get_handle_table_id(managed))
referent = weakref.ref(managed)

holder.suspend_cleanup()
try:
del managed, holder
for _ in range(10):
freed = GCGraphNode.collect_and_check()
if referent() is None:
break
else:
self.skipTest("The managed referent was not collected")
assert not freed
finally:
GCGraphNode.resume_cleanup()
self.collect_graph()

def test_restore_native_ownership_after_gc(self):
managed = []
holder = GCGraphNode(managed)
managed.append(holder)
self.collect_graph()
# Native GC breaks the mixed cycle while Python still keeps it reachable.
assert_is_weak(get_handle_table_id(managed))

# A new native owner must restore a strong referent, even if the companion
# was already rooted to preserve the native pointers in the weak cycle.
owner = GCGraphNode(managed)
owner.hold(0)
self.collect_graph()
assert_is_strong(get_handle_table_id(managed))

owner.set(None, None)
holder.set(None, None)
managed.clear()

def test_release_last_native_reference_after_gc(self):
managed = []
holder = GCGraphNode(managed)
managed.append(holder)
self.collect_graph()
assert_is_weak(get_handle_table_id(managed))

# Drop the final native reference to an already weakened referent. The
# managed object must remain usable and acquire native ownership again.
holder.set(None, None)
self.collect_graph()
owner = GCGraphNode(managed)
owner.hold(0)
self.collect_graph()
assert_is_strong(get_handle_table_id(managed))
assert managed[0] is holder
owner.set(None, None)
managed.clear()

def test_transitive_native_root(self):
# Exercise both allocation orders; the intermediate may precede its root.
for reverse in (False, True):
Expand Down
Loading
Loading