[mypyc] Fix race in the __weakref__ getter on free-threaded builds (#22486)

The `__weakref__` getter of native classes (`CPy_GetWeakrefs`, added in
#22387) reads the head of the object's weak reference list and increfs
it without any synchronization. On a free-threaded build another thread
can drop the last reference to that weak reference object between the
two steps. `weakref_dealloc` then unlinks it from the list and frees it,
and the getter increfs freed memory.

CPython had the same race in `subtype_getweakref` (the getter that
classes defined in Python use). It was fixed in python/cpython#150247
(for python/cpython#149816; backported to 3.14 and 3.15, not to 3.13):
the getter now holds the interpreter's weak reference list lock and uses
`_Py_TryIncref`. Both are internal APIs, and the lock is a striped mutex
in the interpreter state, so an extension can't take the same lock.
`PyUnstable_TryIncRef` alone isn't enough, because it relies on the
caller holding a lock that the deallocator also takes.

### Reproducer

```python
import threading, weakref
from mypy_extensions import mypyc_attr

@mypyc_attr(weakrefs=True)
class C:
    pass

def churn(o: C, n: int) -> None:
    for _ in range(n):
        weakref.ref(o, None)
        weakref.ref(o, lambda r: None)

def read(o: object, n: int) -> None:
    for _ in range(n):
        getattr(o, "__weakref__")
```

Running two `churn` threads and two `read` threads on one instance with
`n = 100_000`, compiled for 3.14t: on master 8 of 10 runs failed (5
segfaults, 3 hangs). With this PR all 10 passed, and the same script
with a non-native class passes on both.

### Fix

On free-threaded builds, `CPy_GetWeakrefs` now calls CPython's own
getter. It gets the `__weakref__` descriptor of a small class created
with `type()` on first use and calls its `PyGetSetDef.get` function
directly. `subtype_getweakref` only looks at
`Py_TYPE(obj)->tp_weaklistoffset`, so it works for native classes too.
That way the getter takes the right lock, and native classes behave the
same as classes defined in Python on every version: they are safe
wherever CPython is, and on versions where CPython's own getter is still
racy (3.13t, 3.14t before 3.14.9) they are no worse than interpreted
classes.

The descriptor is cached with a compare-and-swap rather than a mutex,
since creating the class can run arbitrary code through the GC, which
could reenter the getter. GIL builds are unchanged.

### Tests

I added `testConcurrentWeakrefGetter` to `run-threading.test`, with the
same pattern as the other concurrency tests there. On 3.14t it
segfaulted in 3 of 3 runs without the fix and passed in 3 of 3 runs with
it. It also passes on regular builds, where it's only a smoke test. The
weakref and threading run tests pass on 3.14t, and the full
`test_run.py` passes on 3.13.
diff --git a/mypyc/lib-rt/misc_ops.c b/mypyc/lib-rt/misc_ops.c
index d0111e8..9f1a519 100644
--- a/mypyc/lib-rt/misc_ops.c
+++ b/mypyc/lib-rt/misc_ops.c
@@ -1038,6 +1038,42 @@
 
 }
 
+#ifdef Py_GIL_DISABLED
+// The '__weakref__' descriptor of a class defined in Python, which wraps CPython's
+// own getter (subtype_getweakref in typeobject.c). Created on first use.
+static PyObject *CPy_SubtypeWeakrefDescr = NULL;
+
+static PyGetSetDef *CPy_GetSubtypeWeakrefGetSet(void) {
+    PyObject *descr = _Py_atomic_load_ptr_acquire(&CPy_SubtypeWeakrefDescr);
+    if (descr == NULL) {
+        // Don't hold a lock here, since creating the class can run arbitrary code
+        // (through the GC) that may reenter this function.
+        PyObject *cls = PyObject_CallFunction(
+            (PyObject *)&PyType_Type, "s(){}", "_CPyWeakrefGetter");
+        if (cls == NULL) {
+            return NULL;
+        }
+        descr = PyObject_GetAttrString(cls, "__weakref__");
+        Py_DECREF(cls);  // The descriptor keeps the class alive
+        if (descr == NULL) {
+            return NULL;
+        }
+        if (!Py_IS_TYPE(descr, &PyGetSetDescr_Type)) {
+            Py_DECREF(descr);
+            PyErr_SetString(PyExc_SystemError, "unexpected __weakref__ descriptor type");
+            return NULL;
+        }
+        PyObject *expected = NULL;
+        if (!_Py_atomic_compare_exchange_ptr(&CPy_SubtypeWeakrefDescr, &expected, descr)) {
+            // Another thread got there first
+            Py_DECREF(descr);
+            descr = expected;
+        }
+    }
+    return ((PyGetSetDescrObject *)descr)->d_getset;
+}
+#endif
+
 // Implementation of the '__weakref__' getter of native classes that support weak
 // references. Adapted from subtype_getweakref in CPython's typeobject.c.
 PyObject *CPy_GetWeakrefs(PyObject *obj, void *closure)
@@ -1047,11 +1083,23 @@
         PyErr_SetString(PyExc_AttributeError, "This object has no __weakref__");
         return NULL;
     }
+#ifdef Py_GIL_DISABLED
+    // Another thread may remove the head of the weak reference list and free it at
+    // any time, so the list may only be read while holding CPython's internal weak
+    // reference lock. Only CPython's own getter can take the lock, so use it. It
+    // works for any type, since it only uses tp_weaklistoffset.
+    PyGetSetDef *getset = CPy_GetSubtypeWeakrefGetSet();
+    if (getset == NULL) {
+        return NULL;
+    }
+    return getset->get(obj, getset->closure);
+#else
     PyObject **weaklistptr = (PyObject **)((char *)obj + offset);
     if (*weaklistptr == NULL) {
         return Py_NewRef(Py_None);
     }
     return Py_NewRef(*weaklistptr);
+#endif
 }
 
 // Adapted from ceval.c GET_AITER
diff --git a/mypyc/test-data/run-threading.test b/mypyc/test-data/run-threading.test
index 7ae693c..5b07d67 100644
--- a/mypyc/test-data/run-threading.test
+++ b/mypyc/test-data/run-threading.test
@@ -613,3 +613,44 @@
 for thread in threads:
     thread.join()
 assert not errors, errors
+
+[case testConcurrentWeakrefGetter]
+import threading
+import weakref
+from typing import Any
+from mypy_extensions import mypyc_attr
+
+@mypyc_attr(weakrefs=True)
+class C:
+    pass
+
+def churn(o: C, count: int) -> None:
+    # Each new weak reference becomes the head of the weak reference list, and it's
+    # freed right away
+    for _ in range(count):
+        weakref.ref(o, None)
+        weakref.ref(o, lambda r: None)
+
+def read(o: Any, count: int) -> None:
+    for _ in range(count):
+        # Note: mypy doesn't know about '__weakref__', so use getattr().
+        r = getattr(o, "__weakref__")
+        assert r is None or isinstance(r, weakref.ref)
+
+def test_concurrent_weakref_getter() -> None:
+    # On a free-threaded build, reading __weakref__ races with other threads that
+    # free the head of the list
+    o = C()
+    count = 100_000
+    threads = [
+        threading.Thread(target=churn, args=(o, count)),
+        threading.Thread(target=churn, args=(o, count)),
+        threading.Thread(target=read, args=(o, count)),
+        threading.Thread(target=read, args=(o, count)),
+    ]
+    for thread in threads:
+        thread.start()
+    for thread in threads:
+        thread.join()
+    r = weakref.ref(o)
+    assert r() is o