Skip to content

Commit 55c99b7

Browse files
authored
[mypyc] Allow native classes to support weak refs (#22387)
Fixes mypyc/mypyc#1102. Native classes support weak references if they opt in using `@mypyc_attr(weakrefs=True)`, which adds a weak reference list field to the object struct. The base class of a hierarchy must opt in, since the offset of the field must be the same in all subclasses. Native subclasses of non-native classes (other than dict/Exception subclasses) always support weak references, like interpreted subclasses. Previously some of these classes were weak-referenceable (on 3.11 and earlier, or if the base class supported them), but tp_dealloc never cleared the weak references, so they resurrected freed memory. Now tp_dealloc clears weak references for all classes that support them. On 3.11 and earlier, callable classes (used for nested functions, lambdas and singledispatch functions) and native dict/Exception subclasses used to accept weak references, but the result crashed or corrupted memory once the object died. They now reject weak references, as on 3.12+, and their instances are one pointer smaller.
1 parent 5dc2840 commit 55c99b7

12 files changed

Lines changed: 684 additions & 21 deletions

File tree

‎mypyc/codegen/emitclass.py‎

Lines changed: 51 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,11 @@ def generate_class(
336336
and not managed_dict
337337
and emitter.capi_version < (3, 12)
338338
)
339-
generate_dealloc_slots = generate_full or managed_dict or needs_builtin_dict_cleanup
339+
# Weak references to a dead object must be cleared in tp_dealloc, or they will
340+
# resurrect freed memory.
341+
generate_dealloc_slots = (
342+
generate_full or managed_dict or needs_builtin_dict_cleanup or cl.has_weakref_list()
343+
)
340344
if generate_dealloc_slots:
341345
fields["tp_dealloc"] = f"(destructor){name_prefix}_dealloc"
342346
if not cl.is_acyclic:
@@ -405,27 +409,36 @@ def emit_line() -> None:
405409
# values. PyType_Ready will inherit the offsets from tp_base but
406410
# that isn't what we want.
407411

408-
# XXX: there is no reason for the __weakref__ stuff to be mixed up with __dict__
409-
if cl.has_dict and not has_managed_dict(cl, emitter):
410-
# __dict__ lives right after the struct and __weakref__ lives right after that
412+
if cl.has_dict and not managed_dict:
413+
# __dict__ lives right after the struct, and __weakref__ (if any) after that.
411414
# TODO: They should get members in the struct instead of doing this nonsense.
412-
weak_offset = f"{base_size} + sizeof(PyObject *)"
415+
#
416+
# We can't inherit tp_dictoffset/tp_weaklistoffset from the base class, since
417+
# the base class slots would overlap with fields of our object struct, which
418+
# doesn't model the layout of the non-native base class at all.
419+
needs_own_weak_slot = (
420+
emitter.capi_version < (3, 12) and cl.has_weakref_list() and not cl.has_weakref_slot()
421+
)
413422
emitter.emit_lines(
414423
f"PyMemberDef {members_name}[] = {{",
415424
f'{{"__dict__", T_OBJECT_EX, {base_size}, 0, NULL}},',
416-
f'{{"__weakref__", T_OBJECT_EX, {weak_offset}, 0, NULL}},',
417425
"{0}",
418426
"};",
419427
)
420428

421429
fields["tp_members"] = members_name
422-
fields["tp_basicsize"] = f"{base_size} + 2*sizeof(PyObject *)"
430+
num_slots = 2 if needs_own_weak_slot else 1
431+
fields["tp_basicsize"] = f"{base_size} + {num_slots}*sizeof(PyObject *)"
423432
if emitter.capi_version < (3, 12):
424433
fields["tp_dictoffset"] = base_size
425-
fields["tp_weaklistoffset"] = weak_offset
434+
if needs_own_weak_slot:
435+
fields["tp_weaklistoffset"] = f"{base_size} + sizeof(PyObject *)"
426436
else:
427437
fields["tp_basicsize"] = base_size
428438

439+
if cl.has_weakref_slot():
440+
fields["tp_weaklistoffset"] = f"offsetof({struct_name}, weakreflist)"
441+
429442
if generate_dealloc_slots:
430443
if not cl.is_acyclic:
431444
generate_traverse_for_class(cl, traverse_name, emitter)
@@ -524,6 +537,11 @@ def emit_line() -> None:
524537
fields["tp_call"] = "PyVectorcall_Call"
525538
if managed_dict:
526539
flags.append("Py_TPFLAGS_MANAGED_DICT")
540+
if cl.has_weakref_list() and not cl.has_weakref_slot():
541+
# The pre-header has room for both __dict__ and the weak reference list, so
542+
# this is free. The flag is usually inherited from the base class, but not
543+
# if the base class doesn't support weak references (e.g. abc.ABC).
544+
flags.append("Py_TPFLAGS_MANAGED_WEAKREF")
527545
fields["tp_flags"] = " | ".join(flags)
528546

529547
fields["tp_doc"] = f"PyDoc_STR({native_class_doc_initializer(cl)})"
@@ -565,6 +583,10 @@ def generate_object_struct(cl: ClassIR, emitter: Emitter) -> None:
565583
seen_attrs: set[str] = set()
566584
lines: list[str] = []
567585
lines += ["typedef struct {", "PyObject_HEAD", "CPyVTableItem *vtable;"]
586+
if cl.has_weakref_slot():
587+
# This must come before any field whose presence depends on the class, since
588+
# tp_weaklistoffset has to agree between a base class and its subclasses.
589+
lines.append("PyObject *weakreflist;")
568590
if cl.has_method("__call__"):
569591
lines.append("vectorcallfunc vectorcall;")
570592
# The flag affects attribute offsets, so concrete bases must agree on its presence.
@@ -1052,12 +1074,10 @@ def generate_traverse_for_class(cl: ClassIR, func_name: str, emitter: Emitter) -
10521074
emitter.emit_line(f"rv = PyObject_VisitManagedDict({base_args});")
10531075
emitter.emit_line("if (rv != 0) return rv;")
10541076
elif cl.has_dict:
1055-
# __dict__ lives at tp_dictoffset (== base_size), __weakref__ right after it.
1077+
# __dict__ lives at tp_dictoffset (== base_size). The weak reference list, if
1078+
# any, is deliberately not visited: it holds borrowed references.
10561079
base_size = f"sizeof({cl.builtin_base or cl.struct_name(emitter.names)})"
10571080
emitter.emit_gc_visit(f"*((PyObject **)((char *)self + {base_size}))", object_rprimitive)
1058-
emitter.emit_gc_visit(
1059-
f"*((PyObject **)((char *)self + sizeof(PyObject *) + {base_size}))", object_rprimitive
1060-
)
10611081
emitter.emit_line("return rv;")
10621082
emitter.emit_line("}")
10631083

@@ -1111,12 +1131,11 @@ def generate_subtype_clear_body(cl: ClassIR, emitter: Emitter, skip_attrs: set[s
11111131
if has_managed_dict(cl, emitter):
11121132
emitter.emit_line(f"PyObject_ClearManagedDict({base_args});")
11131133
elif cl.has_dict:
1114-
# __dict__ lives at tp_dictoffset (== base_size), __weakref__ right after it.
1134+
# __dict__ lives at tp_dictoffset (== base_size). The weak reference list, if
1135+
# any, is not cleared here: it holds borrowed references, and it's cleared in
1136+
# tp_dealloc instead.
11151137
base_size = f"sizeof({cl.builtin_base or cl.struct_name(emitter.names)})"
11161138
emitter.emit_gc_clear(f"*((PyObject **)((char *)self + {base_size}))", object_rprimitive)
1117-
emitter.emit_gc_clear(
1118-
f"*((PyObject **)((char *)self + sizeof(PyObject *) + {base_size}))", object_rprimitive
1119-
)
11201139

11211140

11221141
def generate_dealloc_for_class(
@@ -1156,6 +1175,18 @@ def generate_dealloc_for_class(
11561175
emitter.emit_line("}")
11571176
if not cl.is_acyclic:
11581177
emitter.emit_line("PyObject_GC_UnTrack(self);")
1178+
if cl.has_weakref_list():
1179+
# Invalidate all weak references to the object, and call their callbacks.
1180+
# This must happen after the finalizer has run, and before any of the
1181+
# attributes are cleared.
1182+
#
1183+
# TODO: Weak references created *inside* __del__ are not cleared. CPython
1184+
# handles these with a second _PyWeakref_ClearWeakRefsNoCallbacks pass.
1185+
if cl.has_weakref_slot():
1186+
emitter.emit_line("CPy_ClearWeakrefs((PyObject *)self, &self->weakreflist);")
1187+
else:
1188+
# The list is next to __dict__, and the offset depends on the Python version
1189+
emitter.emit_line("PyObject_ClearWeakRefs((PyObject *)self);")
11591190
if cl.builtin_base:
11601191
emitter.emit_line(f"{clear_func_name}((PyObject *)self);")
11611192
# For native subclasses of builtins such as dict, the base deallocator
@@ -1339,6 +1370,10 @@ def generate_getseters_table(cl: ClassIR, name: str, emitter: Emitter) -> None:
13391370

13401371
if cl.has_dict:
13411372
emitter.emit_line('{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},')
1373+
if cl.has_weakref_list():
1374+
# Even if a non-native base class has a __weakref__ descriptor, we can't use it,
1375+
# since it uses the weak reference list offset of the base class.
1376+
emitter.emit_line('{"__weakref__", CPy_GetWeakrefs, NULL},')
13421377

13431378
emitter.emit_line("{NULL} /* Sentinel */")
13441379
emitter.emit_line("};")

‎mypyc/doc/native_classes.rst‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,65 @@ of cyclic GC.
360360
leaks. Only use this for classes whose instances won't refer back
361361
to objects that (directly or indirectly) refer to the instance.
362362

363+
Weak references
364+
---------------
365+
366+
By default, you can't create weak references to instances of native
367+
classes, since supporting weak references requires an extra pointer in
368+
every instance::
369+
370+
import weakref
371+
372+
class Cls:
373+
pass
374+
375+
o = Cls()
376+
r = weakref.ref(o) # Error
377+
378+
You can enable support for weak references using
379+
``@mypyc_attr(weakrefs=True)``::
380+
381+
import weakref
382+
from mypy_extensions import mypyc_attr
383+
384+
@mypyc_attr(weakrefs=True)
385+
class Cls:
386+
pass
387+
388+
o = Cls()
389+
r = weakref.ref(o) # OK
390+
assert r() is o
391+
392+
Unlike ``acyclic``, weak reference support is inherited by subclasses,
393+
including subclasses defined in other modules and interpreted
394+
subclasses. If a native base class doesn't support weak references, a
395+
native subclass can't add support for them, since the location of the
396+
extra pointer must be the same in all classes of a hierarchy -- you
397+
must add ``@mypyc_attr(weakrefs=True)`` to the base class instead.
398+
399+
Native classes that inherit from a non-native class other than
400+
``object``, such as an interpreted class or ``abc.ABC``, always support
401+
weak references, like interpreted subclasses do. Their instances
402+
already have a ``__dict__``, and weak reference support costs no
403+
additional memory. Native subclasses of built-in types such as ``dict``
404+
or ``Exception`` don't support weak references yet.
405+
406+
.. note::
407+
408+
Mypyc only reports an error about an unsupported weak reference if
409+
it can infer the precise native class of the target. Otherwise the
410+
error is raised at runtime, as in interpreted Python::
411+
412+
o: object = Cls()
413+
r = weakref.ref(o) # TypeError at runtime
414+
415+
.. note::
416+
417+
Mypyc frees a local variable as soon as it's no longer used, which
418+
can be before the end of the enclosing function. Weak references
419+
to an object stored only in a local variable may thus be cleared
420+
earlier than in interpreted Python.
421+
363422
Other properties
364423
----------------
365424

‎mypyc/ir/class_ir.py‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,9 @@ def __init__(
111111
self.is_decorated = False
112112
# Does this inherit from a Python class?
113113
self.inherits_python = False
114+
# Is weak reference support explicitly requested via @mypyc_attr(weakrefs=True)?
115+
# Use supports_weakrefs() to also consider base classes.
116+
self._weakrefs = False
114117
# Do instances of this class have __dict__?
115118
self.has_dict = False
116119
# Do we allow interpreted subclasses? Derived from a mypyc_attr.
@@ -321,7 +324,13 @@ def is_final_attr(self, name: str) -> bool:
321324
@property
322325
def needs_getseters_table(self) -> bool:
323326
"""Do we generate a tp_getset table exposing the attributes to Python?"""
324-
return self.needs_getseters or not self.is_generated or self.has_dict
327+
return (
328+
self.needs_getseters
329+
or not self.is_generated
330+
or self.has_dict
331+
# For the __weakref__ getset
332+
or self.has_weakref_list()
333+
)
325334

326335
def attrs_are_thread_confined(self) -> bool:
327336
"""Can these attributes safely use plain access in free-threaded builds?
@@ -498,6 +507,49 @@ def concrete_subclasses(self) -> list[ClassIR] | None:
498507
def is_serializable(self) -> bool:
499508
return any(ci._serializable for ci in self.mro)
500509

510+
def supports_weakrefs(self) -> bool:
511+
"""Can weak references to instances of this class be created?
512+
513+
Native classes only support weak references if requested using
514+
@mypyc_attr(weakrefs=True), since it has a per-instance memory cost. Like
515+
Python subclasses, native subclasses of non-native classes always support weak
516+
references, whether or not the base class does, since they already have
517+
__dict__ storage, and adding weak reference storage next to it is free.
518+
Subclasses of built-in types (such as Exception or dict) don't support weak
519+
references yet.
520+
"""
521+
if not self.is_ext_class:
522+
# Non-native classes are ordinary heap types, so they always work.
523+
return True
524+
if self.builtin_base:
525+
return False
526+
return self.inherits_python or any(ci._weakrefs for ci in self.mro)
527+
528+
def has_weakref_list(self) -> bool:
529+
"""Is this a native class with instances that have a weak reference list?
530+
531+
This is false for non-native classes, even though they support weak
532+
references, since CPython manages the list for them. For native classes, the
533+
list is either a field of the object struct (see has_weakref_slot()), or
534+
it's stored next to __dict__ (at tp_weaklistoffset): either right after the
535+
object struct (before 3.12) or in the managed pre-header (3.12+).
536+
"""
537+
return self.is_ext_class and not self.is_trait and self.supports_weakrefs()
538+
539+
def has_weakref_slot(self) -> bool:
540+
"""Is the weak reference list stored in a field of the object struct?
541+
542+
Otherwise the list is stored next to __dict__, if weak references are
543+
supported. A native base class that uses the field determines the offset of
544+
the list in all subclasses.
545+
"""
546+
return (
547+
self.is_ext_class
548+
and not self.is_trait
549+
and not self.builtin_base
550+
and any(ci._weakrefs and not ci.inherits_python for ci in self.mro)
551+
)
552+
501553
def serialize(self) -> JsonDict:
502554
return {
503555
"name": self.name,
@@ -510,6 +562,7 @@ def serialize(self) -> JsonDict:
510562
"is_decorated": self.is_decorated,
511563
"is_final_class": self.is_final_class,
512564
"inherits_python": self.inherits_python,
565+
"_weakrefs": self._weakrefs,
513566
"has_dict": self.has_dict,
514567
"allow_interpreted_subclasses": self.allow_interpreted_subclasses,
515568
"needs_getseters": self.needs_getseters,
@@ -581,6 +634,7 @@ def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> ClassIR:
581634
ir.is_decorated = data["is_decorated"]
582635
ir.is_final_class = data["is_final_class"]
583636
ir.inherits_python = data["inherits_python"]
637+
ir._weakrefs = data["_weakrefs"]
584638
ir.has_dict = data["has_dict"]
585639
ir.allow_interpreted_subclasses = data["allow_interpreted_subclasses"]
586640
ir.needs_getseters = data["needs_getseters"]

‎mypyc/irbuild/prepare.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
NameExpr,
3636
OverloadedFuncDef,
3737
RefExpr,
38+
StrExpr,
3839
SymbolNode,
3940
TypeAlias,
4041
TypeInfo,
@@ -80,6 +81,7 @@
8081
dataclass_type,
8182
default_attr_name,
8283
get_func_def,
84+
get_mypyc_attr_call,
8385
get_mypyc_attrs,
8486
is_class_body_final,
8587
is_dataclass,
@@ -151,6 +153,7 @@ def build_type_map(
151153
with catch_errors(module.path, cdef.line):
152154
if mapper.type_to_ir[cdef.info].is_ext_class:
153155
validate_acyclic_class_bases(module.path, cdef, errors, mapper)
156+
validate_weakrefs_class_base(module.path, cdef, errors, mapper)
154157

155158
# Prepare implicit attribute accessors as needed if an attribute overrides a property.
156159
for module, cdef in classes:
@@ -485,6 +488,26 @@ def validate_acyclic_class_bases(
485488
)
486489

487490

491+
def validate_weakrefs_class_base(
492+
path: str, cdef: ClassDef, errors: Errors, mapper: Mapper
493+
) -> None:
494+
ir = mapper.type_to_ir[cdef.info]
495+
if not ir.has_weakref_slot() or ir.base is None or ir.base.has_weakref_slot():
496+
return
497+
# The weak reference list field is at a fixed offset that must be the same in a
498+
# base class and all its subclasses, so only the class that starts the hierarchy
499+
# can introduce it.
500+
line = cdef.line
501+
for dec in cdef.decorators:
502+
call = get_mypyc_attr_call(dec)
503+
if call is not None and any(
504+
name == "weakrefs" or (isinstance(arg, StrExpr) and arg.value == "weakrefs")
505+
for name, arg in zip(call.arg_names, call.args)
506+
):
507+
line = call.line
508+
errors.error(f'"weakrefs" must be used in the base class "{ir.base.name}" as well', path, line)
509+
510+
488511
def _has_own_default_attrs(cdef: ClassDef, ir: ClassIR) -> bool:
489512
"""Whether this class's own body has any default attribute assignment
490513
that would be emitted into __mypyc_defaults_setup.
@@ -669,6 +692,13 @@ def prepare_class_def(
669692
if attrs.get("acyclic") is True:
670693
ir.is_acyclic = True
671694

695+
if attrs.get("weakrefs") is True:
696+
line = attrs_lines["weakrefs"]
697+
if ir.is_trait:
698+
errors.error('"weakrefs" can\'t be used with traits', path, line)
699+
else:
700+
ir._weakrefs = True
701+
672702
# Check for subclassing from builtin types
673703
reported_base = False
674704
for cls in info.mro:
@@ -700,6 +730,14 @@ def prepare_class_def(
700730
cdef.line,
701731
)
702732

733+
if ir.builtin_base and ir._weakrefs:
734+
errors.error(
735+
'"weakrefs" can\'t be used in a class that inherits from a built-in type',
736+
path,
737+
attrs_lines["weakrefs"],
738+
)
739+
ir._weakrefs = False
740+
703741
free_list_len = attrs.get("free_list_len")
704742
if free_list_len is not None:
705743
line = attrs_lines["free_list_len"]

0 commit comments

Comments
 (0)