Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated memory management #543

Merged
merged 66 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
66 commits
Select commit Hold shift + click to select a range
9abcd0d
Retain on ObjCInstance creation, autorelease on __del__
samschott Nov 19, 2024
6605842
update tests
samschott Nov 19, 2024
931c352
add change note
samschott Nov 19, 2024
a618f2a
use autorelease instead of release in __del__
samschott Nov 20, 2024
b1bf61c
code formatting
samschott Nov 20, 2024
21f2e0b
update docs
samschott Nov 20, 2024
20ab8f9
add comment about autorelease vs release
samschott Nov 23, 2024
160c819
remove now unneeded cache staleness check
samschott Nov 23, 2024
ce9d78c
remove stale instance cache tests
samschott Nov 23, 2024
6d89330
update test_objcinstance_dealloc
samschott Nov 24, 2024
3bb7ccc
correct inline comment
samschott Nov 24, 2024
c0b091c
make returned_from_method private
samschott Nov 24, 2024
ab1f762
update ObjCInstance doc string
samschott Nov 24, 2024
544d694
updated docs
samschott Nov 24, 2024
b4a1624
update spellchecker
samschott Nov 24, 2024
f0edb5b
update change notes with migration instructions
samschott Nov 24, 2024
22396dc
Rephrase removal note
samschott Nov 25, 2024
7d51fde
remove unneeded space in doc string
samschott Nov 25, 2024
acfa546
change bugfix to feature note
samschott Nov 25, 2024
18e08cc
Fix incorrect inline comment
samschott Nov 25, 2024
532fbe0
trim trailing whitespace
samschott Nov 25, 2024
52e92c0
update test comment
samschott Nov 25, 2024
efed734
check that objects are not deallocated before end of autorelease pool
samschott Nov 25, 2024
ab8a895
merge object lifecycle tests
samschott Nov 25, 2024
30e4277
add a test case for copyWithZone returning the existing instance with…
samschott Nov 25, 2024
c3a4fe1
release additional refcounts by copy calls on the same ObjCInstance
samschott Nov 25, 2024
7bdc31f
rewrite the copy lifecycle test to use NSDictionary instead of a cust…
samschott Nov 26, 2024
460728b
prevent errors on ObjCInstance garbage collection when `send_message`…
samschott Nov 26, 2024
d9c0f62
switch copy lifecycle test to use NSString
samschott Nov 26, 2024
49d9381
remove unused import
samschott Nov 26, 2024
e0d7792
fix spelling mistake
samschott Nov 26, 2024
715912f
spelling updates
samschott Nov 26, 2024
20e45b6
spelling updates
samschott Nov 26, 2024
86b29a4
spelling updates
samschott Nov 26, 2024
944328d
black code formatting
samschott Nov 26, 2024
3b88aaa
rename test case to "immutable copy lifecycle"
samschott Nov 26, 2024
58d0276
improve inline docs
samschott Nov 27, 2024
84e3a9f
special handling for init
samschott Nov 27, 2024
ab46b9d
add tests for init object change
samschott Nov 28, 2024
2305122
implement proper method family detection
samschott Nov 28, 2024
2e4eccb
ensure partial methods are loaded from all superclasses
samschott Nov 28, 2024
2989540
remove unneeded whitespace
samschott Nov 29, 2024
0bc749c
improved release-on-cache-hit documentation
samschott Nov 29, 2024
04981e3
updated change notes
samschott Nov 29, 2024
54ed55c
add test for get_method_family
samschott Nov 29, 2024
c6096c2
remove loop that breaks early on method loading
samschott Nov 29, 2024
a28c901
make method loading slightly clearer
samschott Nov 29, 2024
1b306e2
extract and document method name to tuple logic
samschott Nov 29, 2024
849749e
fall back to full method usage if partial method lookup fails
samschott Nov 29, 2024
15593c1
update partial method cache after successful lookup
samschott Nov 29, 2024
39c548e
Revert "remove loop that breaks early on method loading"
samschott Nov 30, 2024
b78c41d
Revert "ensure partial methods are loaded from all superclasses"
samschott Nov 30, 2024
cb996ad
Reapply "ensure partial methods are loaded from all superclasses"
samschott Nov 30, 2024
6cf88a5
centralize logic for method family
samschott Dec 2, 2024
aa48b5d
update test description
samschott Dec 4, 2024
7fa9e71
update inline comments
samschott Dec 4, 2024
3be2190
fix method family detection
samschott Dec 4, 2024
dded73e
add test case for alloc without init
samschott Dec 4, 2024
199f807
race free interpreter shutdown handling
samschott Dec 4, 2024
d0961b4
black formatting
samschott Dec 4, 2024
a8e9193
more precise family determination to follow the exact rules laid out …
samschott Dec 4, 2024
296cf83
update tests for method family determination to check for non-lowerca…
samschott Dec 4, 2024
93300f3
fix typo in method_name_to_tuple doc string
samschott Dec 4, 2024
2be945b
more exhaustive refcount tests
samschott Dec 5, 2024
2387c02
remove duplicate code from test_objcinstance_returned_lifecycle
samschott Dec 5, 2024
51ba75b
Fix typo
mhsmith Dec 5, 2024
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
10 changes: 9 additions & 1 deletion changes/256.bugfix.rst
Original file line number Diff line number Diff line change
@@ -1,2 +1,10 @@
Retain Objective-C objects when creating Python wrappers and release them when the
Python wrapped is garbage collected.
Python wrapped is garbage collected. This means that manual ``retain`` calls and
subsequent ``release`` or ``autorelease`` calls from Python are no longer needed with
mhsmith marked this conversation as resolved.
Show resolved Hide resolved
very few exceptions such as:

1. When implementing methods like ``copy`` that are supposed to create an object, if
the returned object is not actually newly created.
2. When dealing with side effects of methods like ``init`` that may release an object
which is still referenced from Python. See for example
https://github.com/beeware/toga/issues/2468.
4 changes: 4 additions & 0 deletions changes/256.removal.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Rubicon no longer skips releasing an Objective-C objects when its Python wrapped is
mhsmith marked this conversation as resolved.
Show resolved Hide resolved
garbage collected. This means that fewer ``retain`` than ``release`` calls will cause
segfaults on garbage collection. Review your code carefully for unbalanced ``retain``
and ``release`` calls before updating.
32 changes: 21 additions & 11 deletions docs/how-to/memory-management.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
Memory management for Objective-C instances
===========================================

Reference counting in Objective-C
=================================

Reference counting works differently in Objective-C compared to Python. Python
will automatically track where variables are referenced and free memory when
the reference count drops to zero whereas Objective-C uses explicit reference
Expand All @@ -13,8 +16,8 @@ When enabling automatic reference counting (ARC), the appropriate calls for
memory management will be inserted for you at compile-time. However, since
Rubicon Objective-C operates at runtime, it cannot make use of ARC.

Reference counting in Rubicon Objective-C
-----------------------------------------
Reference management in Rubicon
===============================

In most cases, you won't have to manage reference counts in Python, Rubicon
Objective-C will do that work for you. It does so by calling ``retain`` on an
Expand All @@ -23,19 +26,26 @@ object when Rubicon creates a ``ObjCInstance`` for it on the Python side, and ca
the object ensures it is not deallocated while it is still referenced from Python
and releasing it again on ``__del__`` ensures that we do not leak memory.

An exception to this is when you manually ``retain`` an object. Rubicon
Objective-C will not keep track of such retain calls and you will be
responsible to insert appropriate ``release`` or ``autorelease`` calls yourself
to prevent leaking memory.
The only exception to this is when you create an object -- which is always done
through methods starting with "alloc", "new", "copy", or "mutableCopy". Rubicon does
not explicitly retain such objects because we own objects created by us, but Rubicon
does autorelease them when the Python wrapper is garbage collected.

Rubicon Objective-C will not keep track if you additionally manually ``retain`` an
object. You will be responsible to insert appropriate ``release`` or ``autorelease``
calls yourself to prevent leaking memory.

Weak references in Objective-C
------------------------------

You will also need to pay attention to reference counting in case of **weak
references**. In Objective-C, creating a **weak reference** means that the
reference count of the object is not incremented and the object will still be
You will need to pay attention to reference counting in case of **weak
references**. In Objective-C, as in Python, creating a weak reference means that
the reference count of the object is not incremented and the object will be
deallocated when no strong references remain. Any weak references to the object
are then set to ``nil``.

Some objects will store references to other objects as a weak reference. Such
properties will be declared in the Apple developer documentation as
Some Objective-C objects store references to other objects as a weak reference.
Such properties will be declared in the Apple developer documentation as
"@property(weak)" or "@property(assign)". This is commonly the case for
delegates. For example, in the code below, the ``NSOutlineView`` only stores a
weak reference to the object which is assigned to its delegate property:
Expand Down
4 changes: 4 additions & 0 deletions docs/spelling_wordlist
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
Alea
alloc
Autorelease
autorelease
autoreleased
autoreleases
Bugfixes
callables
CPython
Expand All @@ -22,6 +25,7 @@ lookups
macOS
metaclass
metaclasses
mutableCopy
namespace
namespaces
ObjC
Expand Down
23 changes: 15 additions & 8 deletions src/rubicon/objc/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ def __call__(self, receiver, *args, convert_args=True, convert_result=True):

# Convert result to python type if it is an instance or class pointer.
if self.restype is not None and issubclass(self.restype, objc_id):
result = ObjCInstance(result, returned_from_method=self.name)
result = ObjCInstance(result, _returned_from_method=self.name)
samschott marked this conversation as resolved.
Show resolved Hide resolved

return result

Expand Down Expand Up @@ -795,7 +795,7 @@ def _associated_attr_key_for_name(name):
return SEL(f"rubicon.objc.py_attr.{name}")

def __new__(
cls, object_ptr, _name=None, _bases=None, _ns=None, returned_from_method=b""
cls, object_ptr, _name=None, _bases=None, _ns=None, _returned_from_method=b""
):
"""The constructor accepts an :class:`~rubicon.objc.runtime.objc_id` or
anything that can be cast to one, such as a :class:`~ctypes.c_void_p`,
Expand All @@ -814,10 +814,17 @@ class or a metaclass, an instance of :class:`ObjCClass` or
:func:`register_type_for_objcclass`. Creating an :class:`ObjCInstance`
from a ``nil`` pointer returns ``None``.

Rubicon currently does not perform any automatic memory management on
the Objective-C object wrapped in an :class:`ObjCInstance`. It is the
user's responsibility to ``retain`` and ``release`` wrapped objects as
needed, like in Objective-C code without automatic reference counting.
Rubicon retains an Objective-C object when it is wrapped in an
:class:`ObjCInstance` and autoreleases it when the :class:`ObjCInstance` is
garbage collected.

The only exception to this are objects returned by methods which create an
object (starting with "alloc", "new", "copy", or "mutableCopy"). We do not
explicitly retain them because we already own objects created by us, but we do
autorelease them on garbage collection of the Python wrapper.

This ensures that the :class:`ObjCInstance` can always be used from Python
mhsmith marked this conversation as resolved.
Show resolved Hide resolved
without segfaults while preventing Rubicon from leaking memory.
"""

# Make sure that object_ptr is wrapped in an objc_id.
Expand All @@ -839,7 +846,7 @@ class or a metaclass, an instance of :class:`ObjCClass` or

# Explicitly retain the instance on first handover to Python unless we
# received it from a method that gives us ownership already.
if not returned_from_method.startswith(
if not _returned_from_method.startswith(
(b"alloc", b"new", b"copy", b"mutableCopy")
):
send_message(object_ptr, "retain", restype=objc_id, argtypes=[])
Expand Down Expand Up @@ -875,7 +882,7 @@ class or a metaclass, an instance of :class:`ObjCClass` or

def __del__(self):
# Autorelease our reference on garbage collection of the Python wrapper. We use
# release instead of autorelease allow ObjC to take ownership of an object when
# autorelease instead of release to allow ObjC to take ownership of an object when
# it is passed for example to a strong property.
mhsmith marked this conversation as resolved.
Show resolved Hide resolved
send_message(self, "autorelease", restype=objc_id, argtypes=[])

Expand Down
62 changes: 33 additions & 29 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1914,35 +1914,39 @@ def test_objcinstance_explicit_retained_gc_released(self):
# Assert that the obj was deallocated.
self.assertIsNone(wr.weak_property)

# def test_objcinstance_dealloc(self):
# class DeallocTester(NSObject):
# attr0 = objc_property()
# attr1 = objc_property(weak=True)
#
# @objc_method
# def dealloc(self):
# self._did_dealloc = True
#
# obj = DeallocTester.alloc().init()
# obj.__dict__["_did_dealloc"] = False
#
# attr0 = NSObject.alloc().init()
# attr1 = NSObject.alloc().init()
#
# obj.attr0 = attr0
# obj.attr1 = attr1
#
# self.assertEqual(attr0.retainCount(), 2)
# self.assertEqual(attr1.retainCount(), 1)
#
# # ObjC object will be deallocated, can only access Python attributes afterwards.
# obj.release()
#
# self.assertTrue(obj._did_dealloc, "custom dealloc did not run")
# self.assertEqual(
# attr0.retainCount(), 1, "strong property value was not released"
# )
# self.assertEqual(attr1.retainCount(), 1, "weak property value was released")
def test_objcinstance_dealloc(self):

class DeallocTester(NSObject):
did_dealloc = False

attr0 = objc_property()
attr1 = objc_property(weak=True)

@objc_method
def dealloc(self):
DeallocTester.did_dealloc = True

obj = DeallocTester.alloc().init()

attr0 = NSObject.alloc().init()
attr1 = NSObject.alloc().init()

obj.attr0 = attr0
obj.attr1 = attr1

self.assertEqual(attr0.retainCount(), 2)
self.assertEqual(attr1.retainCount(), 1)

# ObjC object will be deallocated, can only access Python attributes afterwards.
mhsmith marked this conversation as resolved.
Show resolved Hide resolved
with autoreleasepool():
del obj
gc.collect()

self.assertTrue(DeallocTester.did_dealloc, "custom dealloc did not run")
self.assertEqual(
attr0.retainCount(), 1, "strong property value was not released"
)
self.assertEqual(attr1.retainCount(), 1, "weak property value was released")

def test_partial_with_override(self):
"""If one method in a partial is overridden, that doesn't impact lookup of other partial targets"""
Expand Down